Skip to content

Commit 742f0d4

Browse files
authored
Merge pull request #160 from simonskodt/feat/no-ref/added-message-index
Feat/no ref/added message index
2 parents 17e4649 + 912b8a7 commit 742f0d4

File tree

9 files changed

+94
-11
lines changed

9 files changed

+94
-11
lines changed

MiniTwit.Core/IRepositories/IMessageRepository.cs

+1
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ public interface IMessageRepository
1818
Task<DBResult<IEnumerable<Message>>> GetAllNonFlaggedByUsernameAsync(string username, CancellationToken ct = default);
1919
DBResult<IEnumerable<Message>> GetAllFollowedByUserId(string userId, CancellationToken ct = default);
2020
Task<DBResult<IEnumerable<Message>>> GetAllFollowedByUserIdAsync(string userId, CancellationToken ct = default);
21+
Task IndexDB();
2122
}

MiniTwit.Infrastructure/Repositories/MessageRepository.cs

+15-8
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using MiniTwit.Core.IRepositories;
55
using MiniTwit.Core.Responses;
66
using MongoDB.Driver;
7-
using System.Linq;
87

98
namespace MiniTwit.Infrastructure.Repositories;
109

@@ -83,8 +82,8 @@ public async Task<DBResult<Message>> CreateAsync(string userId, string text)
8382

8483
public DBResult<IEnumerable<Message>> GetAllNonFlagged(CancellationToken ct = default)
8584
{
86-
var messages = _context.Messages.Find(m => m.Flagged == 0).SortByDescending(m => m.PubDate).ToList(ct);
87-
85+
var messages = _context.Messages.Find(m => m.Flagged == 0).SortByDescending(m => m.PubDate).ToList(ct);
86+
8887
return new DBResult<IEnumerable<Message>>
8988
{
9089
Model = messages,
@@ -94,8 +93,8 @@ public DBResult<IEnumerable<Message>> GetAllNonFlagged(CancellationToken ct = de
9493

9594
public async Task<DBResult<IEnumerable<Message>>> GetAllNonFlaggedAsync(CancellationToken ct = default)
9695
{
97-
var messages = await _context.Messages.Find(m => m.Flagged == 0).SortByDescending(m => m.PubDate).ToListAsync(ct);
98-
96+
var messages = await _context.Messages.Find(m => m.Flagged == 0).SortByDescending(m => m.PubDate).ToListAsync(ct);
97+
9998
return new DBResult<IEnumerable<Message>>
10099
{
101100
Model = messages,
@@ -109,10 +108,10 @@ public async Task<DBResult<IEnumerable<Message>>> GetAllNonFlaggedPageNumberLimi
109108
var messages = await _context.Messages
110109
.Find(m => m.Flagged == 0)
111110
.SortByDescending(m => m.PubDate)
112-
.Skip((pageNumber -1) * 50)
111+
.Skip((pageNumber - 1) * 50)
113112
.Limit(50)
114113
.ToListAsync();
115-
114+
116115
return new DBResult<IEnumerable<Message>>
117116
{
118117
Model = messages,
@@ -198,7 +197,7 @@ public async Task<DBResult<IEnumerable<Message>>> GetAllByUsernameAsync(string u
198197
ErrorType = ErrorType.INVALID_USERNAME
199198
};
200199
}
201-
200+
202201
//All the followers where userName is whoId
203202
var allFollows = GetAllWhoUserFollows(user);
204203

@@ -353,4 +352,12 @@ public async Task<DBResult<IEnumerable<Message>>> GetAllFollowedByUserIdAsync(st
353352
{
354353
return await _context.Users.Find(u => u.Username == username).FirstOrDefaultAsync(ct);
355354
}
355+
356+
public async Task IndexDB()
357+
{
358+
var collection = _context.Messages;
359+
var indexKeysDefinition = Builders<Message>.IndexKeys.Descending(m => m.PubDate);
360+
var indexModel = new CreateIndexModel<Message>(indexKeysDefinition, new CreateIndexOptions { Background = true });
361+
await collection.Indexes.CreateOneAsync(indexModel);
362+
}
356363
}

MiniTwit.Server/Controllers/TwitterController.cs

+7-1
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ public async Task<ActionResult> Logout()
251251
return await Task.FromResult(Ok());
252252
}
253253

254-
254+
255255
/// <summary>
256256
/// Find out if the given user is followed by the given username.
257257
/// </summary>
@@ -286,4 +286,10 @@ public ActionResult<UserDTO> GetIDByUsername(string username)
286286
var response = _serviceManager.UserService.GetByUsername(username);
287287
return response.ToActionResult();
288288
}
289+
290+
[HttpPut("/Messages/IndexDB")]
291+
public void IndexDatabase()
292+
{
293+
_serviceManager.MessageService.IndexDB();
294+
}
289295
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using NetTools;
2+
using System.Net;
3+
4+
namespace MiniTwit.Server;
5+
6+
public class IpAddressFilterMiddleware
7+
{
8+
private readonly RequestDelegate _next;
9+
private readonly IList<IPAddressRange> _allowedIpRanges;
10+
private readonly ILogger<IpAddressFilterMiddleware> _logger;
11+
12+
public IpAddressFilterMiddleware(RequestDelegate next, List<string> allowedIpRanges, ILogger<IpAddressFilterMiddleware> logger)
13+
{
14+
_next = next;
15+
_allowedIpRanges = allowedIpRanges.ConvertAll(x => IPAddressRange.Parse(x));
16+
_logger = logger;
17+
}
18+
19+
public async Task Invoke(HttpContext context)
20+
{
21+
IPAddress clientIpAddress = context.Connection.RemoteIpAddress!;
22+
23+
if (!IsIpAllowed(clientIpAddress, context))
24+
{
25+
context.Response.StatusCode = 403; // Forbidden
26+
_logger.LogCritical($"Unknown client IP address: {clientIpAddress} is trying to call backend endpoints");
27+
await context.Response.WriteAsync("The client IP address is not allowed.");
28+
return;
29+
}
30+
31+
await _next.Invoke(context);
32+
}
33+
34+
public bool IsIpAllowed(IPAddress ipAddress, HttpContext context)
35+
{
36+
if (ipAddress == null)
37+
{
38+
return true;
39+
}
40+
bool isAllowed = false;
41+
42+
foreach (IPAddressRange range in _allowedIpRanges)
43+
{
44+
if (IPAddress.IsLoopback(context.Connection.LocalIpAddress!) || range.Contains(ipAddress))
45+
{
46+
isAllowed = true;
47+
break;
48+
}
49+
}
50+
51+
return isAllowed;
52+
}
53+
}

MiniTwit.Server/MiniTwit.Server.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
</PropertyGroup>
1111

1212
<ItemGroup>
13+
<PackageReference Include="IPAddressRange" Version="5.0.0" />
1314
<PackageReference Include="prometheus-net.AspNetCore" Version="8.0.0" />
1415
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
1516
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.1.0" />

MiniTwit.Server/Program.cs

+8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using MiniTwit.Infrastructure.Repositories;
77
using MiniTwit.Security;
88
using MiniTwit.Security.Hashers;
9+
using MiniTwit.Server;
910
using MiniTwit.Server.Authentication;
1011
using MiniTwit.Server.Extensions;
1112
using MiniTwit.Service;
@@ -99,6 +100,13 @@
99100
options.AddCustomLabel("host", context => context.Request.Host.Host);
100101
});
101102

103+
//Ip filtering
104+
app.UseMiddleware<IpAddressFilterMiddleware>(new List<string>()
105+
{
106+
"164.92.167.188",
107+
"104.248.134.203"
108+
});
109+
102110
// Logging
103111
app.UseSerilogRequestLogging();
104112

MiniTwit.Service/IServices/IMessageService.cs

+1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@ public interface IMessageService
2020
Task<Response<IEnumerable<MessageWithAutherNameDTO>>> GetAllNonFlaggedPageNumberLimitAsync(int pageNumber, CancellationToken ct = default);
2121
Response<IEnumerable<MessageDTO>> GetAllNonFlaggedByUsername(string username, CancellationToken ct = default);
2222
Task<Response<IEnumerable<MessageDTO>>> GetAllNonFlaggedByUsernameAsync(string username, CancellationToken ct = default);
23+
Task IndexDB();
2324
}

MiniTwit.Service/Services/MessageService.cs

+5
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,9 @@ public async Task<Response<IEnumerable<MessageDTO>>> GetAllNonFlaggedByUsernameA
197197

198198
return new Response<IEnumerable<MessageDTO>>(Ok, dbResult.ConvertModelTo<IEnumerable<MessageDTO>>());
199199
}
200+
201+
public async Task IndexDB()
202+
{
203+
await _messageRepository.IndexDB();
204+
}
200205
}

MiniTwit.Tests/Server.Integration.Tests/Integrations/TwitterTests.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Net;
22
using System.Net.Http.Json;
33
using FluentAssertions;
4+
using Microsoft.AspNetCore.Http;
45
using MiniTwit.Core.DTOs;
56
using MiniTwit.Core.Entities;
67
using MiniTwit.Core.Error;
@@ -16,11 +17,11 @@ public TwitterTests(CustomWebApplicationFactory factory)
1617
_factory = factory;
1718
}
1819

20+
1921
[Fact]
2022
public async Task Timeline_given_valid_userId_returns_all_messages_from_followers_and_OK()
2123
{
22-
var client = _factory.CreateClient();
23-
var actual = await client.GetAsync("/?userId=000000000000000000000001");
24+
var actual = await _factory.CreateClient().GetAsync("/?userId=000000000000000000000001");
2425
var content = await actual.Content.ReadFromJsonAsync<IEnumerable<Message>>();
2526

2627
Assert.Equal(HttpStatusCode.OK, actual.StatusCode);

0 commit comments

Comments
 (0)