Add application services for profiles and neutrino

This commit is contained in:
Holden
2026-06-19 12:57:31 -05:00
parent 3eebfc9ba2
commit 0b81cb046a
25 changed files with 274 additions and 125 deletions

View File

@@ -1,4 +1,4 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using RecNet.Application.Profiles; using RecNet.Application.Profiles;
namespace API.Contracts.Profiles.Responses; namespace API.Contracts.Profiles.Responses;
@@ -7,10 +7,10 @@ public class LoginResponse
{ {
[JsonPropertyName("Profile")] [JsonPropertyName("Profile")]
public required ProfileDTO Profile { get; set; } public required ProfileDTO Profile { get; set; }
[JsonPropertyName("AccessToken")] [JsonPropertyName("AccessToken")]
public required string AccessToken { get; set; } public required string AccessToken { get; set; }
[JsonPropertyName("ExpiresIn")] [JsonPropertyName("ExpiresIn")]
public required int ExpiresIn { get; set; } public required int ExpiresIn { get; set; }
} }

View File

@@ -1,5 +1,5 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using RecNet.Domain.Services.Configuration; using RecNet.Application.Common.Interfaces;
namespace API.Controllers.Config.V1; namespace API.Controllers.Config.V1;

View File

@@ -1,28 +1,23 @@
using System.Security.Claims;
using System.Text.Json; using System.Text.Json;
using API.Contracts.Neutrino.Enums; using API.Contracts.Neutrino.Enums;
using API.Contracts.Neutrino.Requests; using API.Contracts.Neutrino.Requests;
using API.Contracts.Neutrino.Responses; using API.Contracts.Neutrino.Responses;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using RecNet.Domain.Repositories; using RecNet.Application.Neutrino;
using RecNet.Domain.Services.Tokens;
namespace API.Controllers.Neutrino; namespace API.Controllers.Neutrino;
[Route("[controller]")] [Route("[controller]")]
[ApiController] [ApiController]
public class NeutrinoController( public class NeutrinoController(INeutrinoAuthorizationService authorizationService) : ControllerBase
IProfileRepository profileRepository,
ITokenService tokenService) : ControllerBase
{ {
// This route will be kind of abysmal so bare with it. // Photon sends the request with Content-Type: text/plain instead of application/json.
[Route("authorize")] [Route("authorize")]
public async Task<ActionResult<NeutrinoAuthenticateResponse>> AuthorizeNeutrinoAsync() public async Task<ActionResult<NeutrinoAuthenticateResponse>> AuthorizeNeutrinoAsync(
CancellationToken ct)
{ {
// Photon sends the request with Content-Type: text/plain instead of application/json
// This is a really janky workaround since we can't use [FromBody] to automatically parse the data.
using var reader = new StreamReader(Request.Body); using var reader = new StreamReader(Request.Body);
string rawText = await reader.ReadToEndAsync(); string rawText = await reader.ReadToEndAsync(ct);
NeutrinoAuthenticateRequest? request; NeutrinoAuthenticateRequest? request;
@@ -41,42 +36,30 @@ public class NeutrinoController(
AuthenticationResultCode.InvalidParameters)); AuthenticationResultCode.InvalidParameters));
} }
// 1. Check if request parameters aren't empty if (request is null)
if (request is null ||
request.ProfileId == Guid.Empty ||
string.IsNullOrWhiteSpace(request.AccessToken))
return Ok( return Ok(
NeutrinoAuthenticateResponse.Failure( NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.InvalidParameters)); AuthenticationResultCode.InvalidParameters));
// 2. Verify accessToken is valid var result = await authorizationService.AuthorizeAsync(
var tokenVerifyResult = tokenService.VerifyToken(request.AccessToken); new AuthorizeNeutrinoCommand(
if (tokenVerifyResult.IsError || !TryGetProfileId(tokenVerifyResult.Claims, out var tokenAccountId)) request.ProfileId,
return Ok( request.AccessToken),
NeutrinoAuthenticateResponse.Failure( ct);
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
// 3. Verify that the accountId from the request matches the one from the token if (!result.Succeeded)
if (tokenAccountId != request.ProfileId)
return Ok( return Ok(
NeutrinoAuthenticateResponse.Failure( NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.AuthenticationFailedWrongCredentials)); MapFailure(result.Failure)));
// 4. Get the profile to check if it exists, and for the name
var profile = await profileRepository.GetByIdAsync(request.ProfileId);
if (profile is null)
return Ok(
NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
return Ok( return Ok(
NeutrinoAuthenticateResponse.Success( NeutrinoAuthenticateResponse.Success(
userId: request.ProfileId.ToString(), result.UserId!,
nickname: profile.Name result.Nickname!));
)
);
} }
private static bool TryGetProfileId(IEnumerable<Claim> claims, out Guid accountId) private static AuthenticationResultCode MapFailure(NeutrinoAuthorizationFailure? failure)
=> Guid.TryParse(claims.FirstOrDefault(c => c.Type == "sub")?.Value, out accountId); => failure == NeutrinoAuthorizationFailure.InvalidParameters
} ? AuthenticationResultCode.InvalidParameters
: AuthenticationResultCode.AuthenticationFailedWrongCredentials;
}

View File

@@ -1,79 +1,53 @@
using API.Contracts.Profiles.Responses; using API.Contracts.Profiles.Responses;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using RecNet.Application.Profiles; using RecNet.Application.Profiles;
using RecNet.Domain.Repositories;
using RecNet.Domain.Services.Tokens;
using LoginRequest = API.Contracts.Profiles.Requests.LoginRequest; using LoginRequest = API.Contracts.Profiles.Requests.LoginRequest;
using Profile = RecNet.Domain.Entities.Profiles.Profile;
namespace API.Controllers.Profiles.V1; namespace API.Controllers.Profiles.V1;
[Route("api/[controller]/v1")] [Route("api/[controller]/v1")]
[ApiController] [ApiController]
[Authorize] public class ProfilesController(IProfileService profileService) : ControllerBase
public class ProfilesController(
IProfileRepository profileRepository,
IMapper mapper,
ITokenService tokenService) : ControllerBase
{ {
[HttpGet("{id:guid}")] [HttpGet("{id:guid}")]
public async Task<ActionResult<ProfileDTO>> GetProfile( public async Task<ActionResult<ProfileDTO>> GetProfile(
Guid id, Guid id,
CancellationToken ct) CancellationToken ct)
{ {
var profile = await profileRepository.GetByIdAsync(id, ct); var profile = await profileService.GetProfileAsync(id, ct);
if (profile == null) if (profile == null)
return NotFound(); return NotFound();
return mapper.Map<ProfileDTO>(profile); return profile;
} }
[HttpGet("bulk")] [HttpGet("bulk")]
public async Task<IReadOnlyList<ProfileDTO>> GetBulkProfiles( public async Task<IReadOnlyList<ProfileDTO>> GetBulkProfiles(
[FromQuery(Name = "id")] List<Guid> ids, [FromQuery(Name = "id")] List<Guid> ids,
CancellationToken ct) CancellationToken ct)
{ => await profileService.GetProfilesAsync(ids, ct);
var profiles = await profileRepository.GetByIdsAsync(ids, ct);
return mapper.Map<List<ProfileDTO>>(profiles);
}
// TODO: Implement
[AllowAnonymous]
[HttpPost("login")] [HttpPost("login")]
public async Task<ActionResult<LoginResponse>> Login( public async Task<ActionResult<LoginResponse>> Login(
[FromBody] LoginRequest request, [FromBody] LoginRequest request,
CancellationToken ct) CancellationToken ct)
{ {
var name = GenerateRandomName(); var result = await profileService.LoginAsync(
new LoginProfileCommand(
var profile = await profileRepository.GetByPlatform(request.PlatformType, request.PlatformId, ct); request.DeviceId,
if (profile is null) request.PlatformType,
{ request.PlatformId,
profile = Profile.Create(name, request.PlatformType, request.PlatformId); request.PlatformAuthentication),
await profileRepository.AddAsync(profile, ct); ct);
}
profile.AddDeviceId(request.DeviceId); if (!result.Succeeded)
return BadRequest(result.Message);
await profileRepository.SaveChangesAsync(ct);
if (profile.IsBanned)
return BadRequest();
var token = tokenService.GenerateProfileToken(profile);
return new LoginResponse return new LoginResponse
{ {
Profile = mapper.Map<ProfileDTO>(profile), Profile = result.Profile!,
AccessToken = token.AccessToken, AccessToken = result.AccessToken!,
ExpiresIn = token.ExpiresIn ExpiresIn = result.ExpiresIn
}; };
} }
}
// TODO: REPLACE WITH BETTER GENERATOR, THIS IS TEMP.
private static string GenerateRandomName()
=> string.Concat("rr", Guid.NewGuid().ToString("N").AsSpan(0, 18));
}

View File

@@ -1,4 +1,4 @@
namespace RecNet.Domain.Services.Configuration; namespace RecNet.Application.Common.Interfaces;
public interface IConfigService public interface IConfigService
{ {

View File

@@ -1,6 +1,7 @@
using RecNet.Application.Common.Tokens;
using RecNet.Domain.Entities.Profiles; using RecNet.Domain.Entities.Profiles;
namespace RecNet.Domain.Services.Tokens; namespace RecNet.Application.Common.Interfaces;
public interface ITokenService public interface ITokenService
{ {

View File

@@ -1,4 +1,4 @@
namespace RecNet.Domain.Services.Tokens; namespace RecNet.Application.Common.Tokens;
public sealed record TokenResult( public sealed record TokenResult(
string AccessToken, string AccessToken,

View File

@@ -0,0 +1,12 @@
namespace RecNet.Application.Common.Tokens;
public sealed record TokenVerifyResult(
bool Succeeded,
Guid? ProfileId)
{
public static TokenVerifyResult Success(Guid profileId)
=> new(true, profileId);
public static TokenVerifyResult Failure()
=> new(false, null);
}

View File

@@ -1,4 +1,6 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using RecNet.Application.Neutrino;
using RecNet.Application.Profiles;
namespace RecNet.Application; namespace RecNet.Application;
@@ -7,9 +9,8 @@ public static class DependencyInjection
public static IServiceCollection AddApplication(this IServiceCollection services) public static IServiceCollection AddApplication(this IServiceCollection services)
{ {
services.AddAutoMapper(_ => { }, typeof(DependencyInjection).Assembly); services.AddAutoMapper(_ => { }, typeof(DependencyInjection).Assembly);
services.AddScoped<IProfileService, ProfileService>();
// Usually there would be CQRS, but I'm rushing out this server, so I didn't feel like adding it. services.AddScoped<INeutrinoAuthorizationService, NeutrinoAuthorizationService>();
// Enjoy a VERY barebones application layer :D
return services; return services;
} }

View File

@@ -0,0 +1,5 @@
namespace RecNet.Application.Neutrino;
public sealed record AuthorizeNeutrinoCommand(
Guid ProfileId,
string AccessToken);

View File

@@ -0,0 +1,8 @@
namespace RecNet.Application.Neutrino;
public interface INeutrinoAuthorizationService
{
Task<NeutrinoAuthorizationResult> AuthorizeAsync(
AuthorizeNeutrinoCommand command,
CancellationToken ct = default);
}

View File

@@ -0,0 +1,7 @@
namespace RecNet.Application.Neutrino;
public enum NeutrinoAuthorizationFailure
{
InvalidParameters,
AuthenticationFailed
}

View File

@@ -0,0 +1,17 @@
namespace RecNet.Application.Neutrino;
public sealed record NeutrinoAuthorizationResult(
bool Succeeded,
NeutrinoAuthorizationFailure? Failure,
string? UserId,
string? Nickname)
{
public static NeutrinoAuthorizationResult Success(Guid userId, string nickname)
=> new(true, null, userId.ToString(), nickname);
public static NeutrinoAuthorizationResult InvalidParameters()
=> new(false, NeutrinoAuthorizationFailure.InvalidParameters, null, null);
public static NeutrinoAuthorizationResult AuthenticationFailed()
=> new(false, NeutrinoAuthorizationFailure.AuthenticationFailed, null, null);
}

View File

@@ -0,0 +1,30 @@
using RecNet.Application.Common.Interfaces;
using RecNet.Domain.Repositories;
namespace RecNet.Application.Neutrino;
public class NeutrinoAuthorizationService(
IProfileRepository profileRepository,
ITokenService tokenService) : INeutrinoAuthorizationService
{
public async Task<NeutrinoAuthorizationResult> AuthorizeAsync(
AuthorizeNeutrinoCommand command,
CancellationToken ct = default)
{
if (command.ProfileId == Guid.Empty || string.IsNullOrWhiteSpace(command.AccessToken))
return NeutrinoAuthorizationResult.InvalidParameters();
var tokenVerifyResult = tokenService.VerifyToken(command.AccessToken);
if (!tokenVerifyResult.Succeeded || tokenVerifyResult.ProfileId is null)
return NeutrinoAuthorizationResult.AuthenticationFailed();
if (tokenVerifyResult.ProfileId.Value != command.ProfileId)
return NeutrinoAuthorizationResult.AuthenticationFailed();
var profile = await profileRepository.GetByIdAsync(command.ProfileId, ct);
if (profile is null)
return NeutrinoAuthorizationResult.AuthenticationFailed();
return NeutrinoAuthorizationResult.Success(profile.ProfileId, profile.Name);
}
}

View File

@@ -0,0 +1,8 @@
namespace RecNet.Application.Profiles;
public interface IProfileService
{
Task<ProfileDTO?> GetProfileAsync(Guid profileId, CancellationToken ct = default);
Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(List<Guid> profileIds, CancellationToken ct = default);
Task<LoginProfileResult> LoginAsync(LoginProfileCommand command, CancellationToken ct = default);
}

View File

@@ -0,0 +1,9 @@
using RecNet.Domain.Common;
namespace RecNet.Application.Profiles;
public sealed record LoginProfileCommand(
string DeviceId,
PlatformType PlatformType,
string PlatformId,
string PlatformAuthentication);

View File

@@ -0,0 +1,33 @@
namespace RecNet.Application.Profiles;
public class LoginProfileResult
{
public bool Succeeded { get; set; }
public string? Message { get; set; }
public ProfileDTO? Profile { get; set; }
public string? AccessToken { get; set; }
public int ExpiresIn { get; set; }
public static LoginProfileResult Success(ProfileDTO profile, string accessToken, int expiresIn)
{
return new LoginProfileResult
{
Succeeded = true,
Profile = profile,
AccessToken = accessToken,
ExpiresIn = expiresIn
};
}
public static LoginProfileResult Fail(string? message = null)
{
return new LoginProfileResult
{
Succeeded = false,
Message = message
};
}
}

View File

@@ -1,12 +1,8 @@
using System.Text.Json.Serialization;
namespace RecNet.Application.Profiles; namespace RecNet.Application.Profiles;
public class ProfileDTO public class ProfileDTO
{ {
[JsonPropertyName("ProfileId")]
public Guid ProfileId { get; init; } public Guid ProfileId { get; init; }
[JsonPropertyName("Name")]
public required string Name { get; init; } public required string Name { get; init; }
} }

View File

@@ -0,0 +1,69 @@
using AutoMapper;
using RecNet.Application.Common.Interfaces;
using RecNet.Domain.Repositories;
using ProfileEntity = RecNet.Domain.Entities.Profiles.Profile;
namespace RecNet.Application.Profiles;
public class ProfileService(
IProfileRepository profileRepository,
ITokenService tokenService,
IMapper mapper) : IProfileService
{
public async Task<ProfileDTO?> GetProfileAsync(Guid profileId, CancellationToken ct = default)
{
var profile = await profileRepository.GetByIdAsync(profileId, ct);
return profile is null
? null
: mapper.Map<ProfileDTO>(profile);
}
public async Task<IReadOnlyList<ProfileDTO>> GetProfilesAsync(
List<Guid> profileIds,
CancellationToken ct = default)
{
var profiles = await profileRepository.GetByIdsAsync(profileIds, ct);
return mapper.Map<List<ProfileDTO>>(profiles);
}
public async Task<LoginProfileResult> LoginAsync(
LoginProfileCommand command,
CancellationToken ct = default)
{
var profile = await profileRepository.GetByPlatform(
command.PlatformType,
command.PlatformId,
ct);
if (profile is null)
{
profile = ProfileEntity.Create(
GenerateRandomName(),
command.PlatformType,
command.PlatformId);
await profileRepository.AddAsync(profile, ct);
}
profile.AddDeviceId(command.DeviceId);
await profileRepository.SaveChangesAsync(ct);
if (profile.IsBanned)
return LoginProfileResult.Fail("Profile is banned");
var token = tokenService.GenerateProfileToken(profile);
return LoginProfileResult.Success(
profile: mapper.Map<ProfileDTO>(profile),
accessToken: token.AccessToken,
expiresIn: token.ExpiresIn
);
}
// Temporary until platform/user-name verification becomes a real use case.
private static string GenerateRandomName()
=> string.Concat("rr", Guid.NewGuid().ToString("N").AsSpan(0, 18));
}

View File

@@ -61,7 +61,17 @@ public class Profile
DeviceIds.Add(deviceId); DeviceIds.Add(deviceId);
} }
public void Ban()
=> IsBanned = true;
public void Unban()
=> IsBanned = false;
public void GrantModerator()
=> IsModerator = true;
public void RevokeModerator()
=> IsModerator = false;
private static string RequireValue(string value, string parameterName) private static string RequireValue(string value, string parameterName)
=> !string.IsNullOrWhiteSpace(value) ? value : throw new DomainException($"{parameterName} is required."); => !string.IsNullOrWhiteSpace(value) ? value : throw new DomainException($"{parameterName} is required.");

View File

@@ -1,21 +0,0 @@
using System.Security.Claims;
namespace RecNet.Domain.Services.Tokens;
public class TokenVerifyResult
{
public bool IsError { get; set; }
public IEnumerable<Claim> Claims { get; set; }
private TokenVerifyResult(bool isError, IEnumerable<Claim>? claims)
{
IsError = isError;
Claims = claims ?? [];
}
public static TokenVerifyResult Success(IEnumerable<Claim> claims)
=> new(false, claims);
public static TokenVerifyResult Failure()
=> new(true, null);
}

View File

@@ -1,8 +1,7 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using RecNet.Application.Common.Interfaces;
using RecNet.Domain.Repositories; using RecNet.Domain.Repositories;
using RecNet.Domain.Services.Configuration;
using RecNet.Domain.Services.Tokens;
using RecNet.Infrastructure.Persistence; using RecNet.Infrastructure.Persistence;
using RecNet.Infrastructure.Persistence.Repositories; using RecNet.Infrastructure.Persistence.Repositories;
using RecNet.Infrastructure.Services.Configuration; using RecNet.Infrastructure.Services.Configuration;

View File

@@ -12,6 +12,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\RecNet.Application\RecNet.Application.csproj" />
<ProjectReference Include="..\RecNet.Domain\RecNet.Domain.csproj" /> <ProjectReference Include="..\RecNet.Domain\RecNet.Domain.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -1,6 +1,6 @@
using System.Text.Json; using System.Text.Json;
using RecNet.Application.Common.Interfaces;
using RecNet.Domain.Repositories; using RecNet.Domain.Repositories;
using RecNet.Domain.Services.Configuration;
namespace RecNet.Infrastructure.Services.Configuration; namespace RecNet.Infrastructure.Services.Configuration;

View File

@@ -3,8 +3,9 @@ using System.Security.Claims;
using System.Text; using System.Text;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using RecNet.Application.Common.Interfaces;
using RecNet.Application.Common.Tokens;
using RecNet.Domain.Entities.Profiles; using RecNet.Domain.Entities.Profiles;
using RecNet.Domain.Services.Tokens;
namespace RecNet.Infrastructure.Services.Tokens; namespace RecNet.Infrastructure.Services.Tokens;
@@ -71,8 +72,14 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
try try
{ {
var principal = tokenHandler.ValidateToken(token, validationParameters, out _); var principal = tokenHandler.ValidateToken(token, validationParameters, out _);
var profileIdClaim =
principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ??
principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return TokenVerifyResult.Success(principal.Claims); return Guid.TryParse(profileIdClaim, out var profileId)
? TokenVerifyResult.Success(profileId)
: TokenVerifyResult.Failure();
} }
catch (SecurityTokenException) catch (SecurityTokenException)
{ {