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;
namespace API.Contracts.Profiles.Responses;
@@ -7,10 +7,10 @@ public class LoginResponse
{
[JsonPropertyName("Profile")]
public required ProfileDTO Profile { get; set; }
[JsonPropertyName("AccessToken")]
public required string AccessToken { get; set; }
[JsonPropertyName("ExpiresIn")]
public required int ExpiresIn { get; set; }
}
}

View File

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

View File

@@ -1,28 +1,23 @@
using System.Security.Claims;
using System.Text.Json;
using API.Contracts.Neutrino.Enums;
using API.Contracts.Neutrino.Requests;
using API.Contracts.Neutrino.Responses;
using Microsoft.AspNetCore.Mvc;
using RecNet.Domain.Repositories;
using RecNet.Domain.Services.Tokens;
using RecNet.Application.Neutrino;
namespace API.Controllers.Neutrino;
[Route("[controller]")]
[ApiController]
public class NeutrinoController(
IProfileRepository profileRepository,
ITokenService tokenService) : ControllerBase
public class NeutrinoController(INeutrinoAuthorizationService authorizationService) : 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")]
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);
string rawText = await reader.ReadToEndAsync();
string rawText = await reader.ReadToEndAsync(ct);
NeutrinoAuthenticateRequest? request;
@@ -41,42 +36,30 @@ public class NeutrinoController(
AuthenticationResultCode.InvalidParameters));
}
// 1. Check if request parameters aren't empty
if (request is null ||
request.ProfileId == Guid.Empty ||
string.IsNullOrWhiteSpace(request.AccessToken))
if (request is null)
return Ok(
NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.InvalidParameters));
// 2. Verify accessToken is valid
var tokenVerifyResult = tokenService.VerifyToken(request.AccessToken);
if (tokenVerifyResult.IsError || !TryGetProfileId(tokenVerifyResult.Claims, out var tokenAccountId))
return Ok(
NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
var result = await authorizationService.AuthorizeAsync(
new AuthorizeNeutrinoCommand(
request.ProfileId,
request.AccessToken),
ct);
// 3. Verify that the accountId from the request matches the one from the token
if (tokenAccountId != request.ProfileId)
if (!result.Succeeded)
return Ok(
NeutrinoAuthenticateResponse.Failure(
AuthenticationResultCode.AuthenticationFailedWrongCredentials));
// 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));
MapFailure(result.Failure)));
return Ok(
NeutrinoAuthenticateResponse.Success(
userId: request.ProfileId.ToString(),
nickname: profile.Name
)
);
result.UserId!,
result.Nickname!));
}
private static bool TryGetProfileId(IEnumerable<Claim> claims, out Guid accountId)
=> Guid.TryParse(claims.FirstOrDefault(c => c.Type == "sub")?.Value, out accountId);
}
private static AuthenticationResultCode MapFailure(NeutrinoAuthorizationFailure? failure)
=> failure == NeutrinoAuthorizationFailure.InvalidParameters
? AuthenticationResultCode.InvalidParameters
: AuthenticationResultCode.AuthenticationFailedWrongCredentials;
}

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
namespace RecNet.Domain.Services.Tokens;
namespace RecNet.Application.Common.Tokens;
public sealed record TokenResult(
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 RecNet.Application.Neutrino;
using RecNet.Application.Profiles;
namespace RecNet.Application;
@@ -7,9 +9,8 @@ public static class DependencyInjection
public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddAutoMapper(_ => { }, typeof(DependencyInjection).Assembly);
// Usually there would be CQRS, but I'm rushing out this server, so I didn't feel like adding it.
// Enjoy a VERY barebones application layer :D
services.AddScoped<IProfileService, ProfileService>();
services.AddScoped<INeutrinoAuthorizationService, NeutrinoAuthorizationService>();
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;
public class ProfileDTO
{
[JsonPropertyName("ProfileId")]
public Guid ProfileId { get; init; }
[JsonPropertyName("Name")]
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);
}
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)
=> !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.Hosting;
using RecNet.Application.Common.Interfaces;
using RecNet.Domain.Repositories;
using RecNet.Domain.Services.Configuration;
using RecNet.Domain.Services.Tokens;
using RecNet.Infrastructure.Persistence;
using RecNet.Infrastructure.Persistence.Repositories;
using RecNet.Infrastructure.Services.Configuration;

View File

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

View File

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

View File

@@ -3,8 +3,9 @@ using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using RecNet.Application.Common.Interfaces;
using RecNet.Application.Common.Tokens;
using RecNet.Domain.Entities.Profiles;
using RecNet.Domain.Services.Tokens;
namespace RecNet.Infrastructure.Services.Tokens;
@@ -71,8 +72,14 @@ public class TokenService(IOptions<JwtOptions> options) : ITokenService
try
{
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)
{