82 lines
3.1 KiB
C#
82 lines
3.1 KiB
C#
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;
|
|
|
|
namespace API.Controllers.Neutrino;
|
|
|
|
[Route("[controller]")]
|
|
[ApiController]
|
|
public class NeutrinoController(
|
|
IProfileRepository profileRepository,
|
|
ITokenService tokenService) : ControllerBase
|
|
{
|
|
// This route will be kind of abysmal so bare with it.
|
|
[Route("authorize")]
|
|
public async Task<ActionResult<NeutrinoAuthenticateResponse>> AuthorizeNeutrinoAsync()
|
|
{
|
|
// 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();
|
|
|
|
NeutrinoAuthenticateRequest? request;
|
|
|
|
try
|
|
{
|
|
request = JsonSerializer.Deserialize<NeutrinoAuthenticateRequest>(rawText, new JsonSerializerOptions
|
|
{
|
|
IncludeFields = true,
|
|
PropertyNameCaseInsensitive = true
|
|
});
|
|
}
|
|
catch
|
|
{
|
|
return Ok(
|
|
NeutrinoAuthenticateResponse.Failure(
|
|
AuthenticationResultCode.InvalidParameters));
|
|
}
|
|
|
|
// 1. Check if request parameters aren't empty
|
|
if (request is null ||
|
|
request.ProfileId == Guid.Empty ||
|
|
string.IsNullOrWhiteSpace(request.AccessToken))
|
|
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));
|
|
|
|
// 3. Verify that the accountId from the request matches the one from the token
|
|
if (tokenAccountId != request.ProfileId)
|
|
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));
|
|
|
|
return Ok(
|
|
NeutrinoAuthenticateResponse.Success(
|
|
userId: request.ProfileId.ToString(),
|
|
nickname: profile.Name
|
|
)
|
|
);
|
|
}
|
|
|
|
private static bool TryGetProfileId(IEnumerable<Claim> claims, out Guid accountId)
|
|
=> Guid.TryParse(claims.FirstOrDefault(c => c.Type == "sub")?.Value, out accountId);
|
|
} |