Skip to content

Commit

Permalink
Merge branch 'develop' into feature/attribute-and-response-simplifica…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
hhvrc authored Nov 8, 2024
2 parents 4304802 + fb1cf28 commit 6afbf32
Show file tree
Hide file tree
Showing 22 changed files with 210 additions and 154 deletions.
2 changes: 1 addition & 1 deletion API/Controller/Account/Authenticated/ChangeEmail.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public sealed partial class AuthenticatedAccountController
/// <exception cref="Exception"></exception>
[HttpPost("email")]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status200OK)]
public async Task<IActionResult> ChangeEmail(ChangeEmailRequest data)
public Task<IActionResult> ChangeEmail(ChangeEmailRequest data)
{
throw new NotImplementedException();
}
Expand Down
2 changes: 1 addition & 1 deletion API/Controller/Account/Authenticated/_ApiController.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using OpenShock.API.Services.Account;
using OpenShock.API.Services.Session;
using OpenShock.Common.Authentication.Attributes;
using OpenShock.Common.Authentication.ControllerBase;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.Session;
using Redis.OM.Contracts;

namespace OpenShock.API.Controller.Account.Authenticated;
Expand Down
4 changes: 1 addition & 3 deletions API/Controller/Account/Logout.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using OpenShock.API.Services.Session;
using OpenShock.Common.Authentication.Attributes;
using OpenShock.Common.Authentication.Services;
using OpenShock.Common.Problems;
using OpenShock.Common.Services.Session;
using OpenShock.Common.Utils;

namespace OpenShock.API.Controller.Account;
Expand Down
1 change: 0 additions & 1 deletion API/Controller/Account/PasswordResetCheckValid.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ public sealed partial class AccountController
/// </summary>
/// <param name="passwordResetId">The id of the password reset</param>
/// <param name="secret">The secret of the password reset</param>
/// <param name="accountService"></param>
/// <param name="cancellationToken"></param>
/// <response code="200">Valid password reset process</response>
/// <response code="404">Password reset process not found</response>
Expand Down
1 change: 0 additions & 1 deletion API/Controller/Account/PasswordResetComplete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ public sealed partial class AccountController
/// <param name="passwordResetId">The id of the password reset</param>
/// <param name="secret">The secret of the password reset</param>
/// <param name="body"></param>
/// <param name="accountService"></param>
/// <response code="200">Password successfully changed</response>
/// <response code="404">Password reset process not found</response>
[HttpPost("recover/{passwordResetId}/{secret}")]
Expand Down
1 change: 0 additions & 1 deletion API/Controller/Account/Signup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ public sealed partial class AccountController
/// Signs up a new user
/// </summary>
/// <param name="body"></param>
/// <param name="accountService"></param>
/// <response code="200">User successfully signed up</response>
/// <response code="409">Username or email already exists</response>
[HttpPost("signup")]
Expand Down
1 change: 0 additions & 1 deletion API/Controller/Account/SignupV2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public sealed partial class AccountController
/// Signs up a new user
/// </summary>
/// <param name="body"></param>
/// <param name="accountService"></param>
/// <param name="turnstileService"></param>
/// <param name="apiConfig"></param>
/// <param name="cancellationToken"></param>
Expand Down
3 changes: 1 addition & 2 deletions API/Controller/Sessions/_ApiController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using OpenShock.API.Services.Session;
using OpenShock.Common.Authentication.Attributes;
using OpenShock.Common.Authentication.ControllerBase;
using OpenShock.Common.Problems;
using OpenShock.Common.Services.Session;

namespace OpenShock.API.Controller.Sessions;

Expand Down
26 changes: 6 additions & 20 deletions API/Services/Account/AccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@
using Microsoft.EntityFrameworkCore;
using OneOf;
using OneOf.Types;
using OpenShock.API.Models.Response;
using OpenShock.API.Services.Email;
using OpenShock.API.Services.Email.Mailjet.Mail;
using OpenShock.API.Utils;
using OpenShock.Common;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Redis;
using OpenShock.Common.Services.Session;
using OpenShock.Common.Utils;
using OpenShock.Common.Validation;
using Redis.OM.Contracts;
using Redis.OM.Searching;

namespace OpenShock.API.Services.Account;

Expand All @@ -26,7 +21,7 @@ public sealed class AccountService : IAccountService

private readonly OpenShockContext _db;
private readonly IEmailService _emailService;
private readonly IRedisCollection<LoginSession> _loginSessions;
private readonly ISessionService _sessionService;
private readonly ILogger<AccountService> _logger;
private readonly ApiConfig _apiConfig;

Expand All @@ -35,17 +30,17 @@ public sealed class AccountService : IAccountService
/// </summary>
/// <param name="db"></param>
/// <param name="emailService"></param>
/// <param name="redisConnectionProvider"></param>
/// <param name="sessionService"></param>
/// <param name="logger"></param>
/// <param name="apiConfig"></param>
public AccountService(OpenShockContext db, IEmailService emailService,
IRedisConnectionProvider redisConnectionProvider, ILogger<AccountService> logger, ApiConfig apiConfig)
ISessionService sessionService, ILogger<AccountService> logger, ApiConfig apiConfig)
{
_db = db;
_emailService = emailService;
_logger = logger;
_apiConfig = apiConfig;
_loginSessions = redisConnectionProvider.RedisCollection<LoginSession>(false);
_sessionService = sessionService;
}

/// <inheritdoc />
Expand Down Expand Up @@ -124,16 +119,7 @@ await Task.Delay(100,

var randomSessionId = CryptoUtils.RandomString(64);

await _loginSessions.InsertAsync(new LoginSession
{
Id = randomSessionId,
UserId = user.Id,
UserAgent = loginContext.UserAgent,
Ip = loginContext.Ip,
PublicId = Guid.NewGuid(),
Created = DateTime.UtcNow,
Expires = DateTime.UtcNow.Add(Duration.LoginSessionLifetime),
}, Duration.LoginSessionLifetime);
await _sessionService.CreateSessionAsync(randomSessionId, user.Id, loginContext.UserAgent, loginContext.Ip);

return new Success<string>(randomSessionId);
}
Expand Down
2 changes: 1 addition & 1 deletion API/Services/Account/IAccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public interface IAccountService
/// <summary>
/// Login a user into his user session
/// </summary>
/// <param name="emailOrUsername"></param>
/// <param name="usernameOrEmail"></param>
/// <param name="password"></param>
/// <param name="loginContext"></param>
/// <param name="cancellationToken"></param>
Expand Down
62 changes: 0 additions & 62 deletions API/Services/Session/SessionService.cs

This file was deleted.

14 changes: 7 additions & 7 deletions API/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Asp.Versioning;
using Asp.Versioning;
using Asp.Versioning.ApiExplorer;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.Connections;
Expand All @@ -17,7 +13,6 @@
using OpenShock.API.Services.Account;
using OpenShock.API.Services.Email.Mailjet;
using OpenShock.API.Services.Email.Smtp;
using OpenShock.API.Services.Session;
using OpenShock.Common;
using OpenShock.Common.Authentication;
using OpenShock.Common.Authentication.Handlers;
Expand All @@ -34,13 +29,18 @@
using OpenShock.Common.Services.Device;
using OpenShock.Common.Services.LCGNodeProvisioner;
using OpenShock.Common.Services.Ota;
using OpenShock.Common.Services.Session;
using OpenShock.Common.Services.Turnstile;
using OpenShock.Common.Utils;
using Redis.OM;
using Redis.OM.Contracts;
using Scalar.AspNetCore;
using Semver;
using Serilog;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
using WebSocketOptions = Microsoft.AspNetCore.Builder.WebSocketOptions;

Expand All @@ -56,7 +56,7 @@ public sealed class Startup
ForwardedForHeaderName = "CF-Connecting-IP"
};

private ApiConfig _apiConfig;
private readonly ApiConfig _apiConfig;

public Startup(IConfiguration configuration)
{
Expand Down
51 changes: 11 additions & 40 deletions Common/Authentication/Handlers/LoginSessionAuthentication.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
Expand All @@ -13,9 +10,11 @@
using OpenShock.Common.Problems;
using OpenShock.Common.Redis;
using OpenShock.Common.Services.BatchUpdate;
using OpenShock.Common.Services.Session;
using OpenShock.Common.Utils;
using Redis.OM.Contracts;
using Redis.OM.Searching;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace OpenShock.Common.Authentication.Handlers;

Expand All @@ -25,7 +24,7 @@ public sealed class LoginSessionAuthentication : AuthenticationHandler<Authentic
private readonly IUserReferenceService _userReferenceService;
private readonly IBatchUpdateService _batchUpdateService;
private readonly OpenShockContext _db;
private readonly IRedisCollection<LoginSession> _userSessions;
private readonly ISessionService _sessionService;
private readonly JsonSerializerOptions _serializerOptions;
private OpenShockProblem? _authResultError = null;

Expand All @@ -36,16 +35,16 @@ public LoginSessionAuthentication(
IClientAuthService<LinkUser> clientAuth,
IUserReferenceService userReferenceService,
OpenShockContext db,
IRedisConnectionProvider provider,
ISessionService sessionService,
IOptions<JsonOptions> jsonOptions, IBatchUpdateService batchUpdateService)
: base(options, logger, encoder)
{
_authService = clientAuth;
_userReferenceService = userReferenceService;
_db = db;
_batchUpdateService = batchUpdateService;
_userSessions = provider.RedisCollection<LoginSession>();
_sessionService = sessionService;
_serializerOptions = jsonOptions.Value.SerializerOptions;
_batchUpdateService = batchUpdateService;
}

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
Expand Down Expand Up @@ -92,11 +91,8 @@ private async Task<AuthenticateResult> TokenAuth(string token)

private async Task<AuthenticateResult> SessionAuth(string sessionKey)
{
var session = await _userSessions.FindByIdAsync(sessionKey);
var session = await _sessionService.GetSessionById(sessionKey);
if (session == null) return Fail(AuthResultError.SessionInvalid);

// This can be removed at a later point, this is just for upgrade purposes
if(UpdateOlderLoginSessions(session)) await _userSessions.SaveAsync();

if (session.Expires!.Value < DateTime.UtcNow.Subtract(Duration.LoginSessionExpansionAfter))
{
Expand All @@ -105,7 +101,7 @@ private async Task<AuthenticateResult> SessionAuth(string sessionKey)
#pragma warning restore CS4014
{
session.Expires = DateTime.UtcNow.Add(Duration.LoginSessionLifetime);
await _userSessions.UpdateAsync(session, Duration.LoginSessionLifetime);
await _sessionService.UpdateSession(session, Duration.LoginSessionLifetime);
});
}

Expand Down Expand Up @@ -145,29 +141,4 @@ protected override Task HandleChallengeAsync(AuthenticationProperties properties
_authResultError.AddContext(Context);
return Context.Response.WriteAsJsonAsync(_authResultError, _serializerOptions, contentType: "application/problem+json");
}

public static bool UpdateOlderLoginSessions(LoginSession session)
{
var save = false;

if (session.PublicId == null)
{
session.PublicId = Guid.NewGuid();
save = true;
}

if (session.Created == null)
{
session.Created = DateTime.UtcNow;
save = true;
}

if (session.Expires == null)
{
session.Expires = DateTime.UtcNow;
save = true;
}

return save;
}
}
2 changes: 1 addition & 1 deletion Common/Geo/Alpha2CountryCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public readonly record struct Alpha2CountryCode(char Char1, char Char2)
{
public static readonly Alpha2CountryCode UnknownCountry = "XX"; // Country code for unknown country

public static bool TryParseAndValidate(string str, [MaybeNullWhen(false)] out Alpha2CountryCode code)
public static bool TryParseAndValidate(string str, [NotNullWhen(true)] out Alpha2CountryCode code)
{
if (str.Length != 2 || !char.IsAsciiLetterUpper(str[0]) || !char.IsAsciiLetterUpper(str[1]))
{
Expand Down
Loading

0 comments on commit 6afbf32

Please sign in to comment.