gandalf-reborn/Api/Handlers/Security/CreateAuthCodeCommandHandler.cs
2025-03-02 12:51:02 +01:00

38 lines
1.4 KiB
C#

using AutoMapper;
using LanguageExt.Common;
using Microsoft.AspNetCore.Identity;
using W542.GandalfReborn.Commands;
using W542.GandalfReborn.Data.Database.Repositories;
using W542.GandalfReborn.Data.Dto;
using W542.GandalfReborn.Data.Entities.Security;
using W542.GandalfReborn.Handlers.Commands;
namespace W542.GandalfReborn.Handlers.Security;
public class CreateAuthCodeCommandHandler(IPasswordHasher<object> passwordHasher, TimeProvider timeProvider, IAuthCodeRepository authCodeRepository, IMapper mapper) : IGrCommandHandler<CreateAuthCodeCommand, Result<AuthCodeDto>>
{
private static readonly object MicrosoftIsAMeme = new();
public async Task<Result<AuthCodeDto>> Handle(CreateAuthCodeCommand command, CancellationToken cancellationToken)
{
var code = passwordHasher.HashPassword(MicrosoftIsAMeme, command.SubjectId.ToString());
var expiresAt = timeProvider.GetUtcNow().AddMinutes(5);
var authCodeEntity = new AuthCodeEntity
{
SubjectId = command.SubjectId,
Expiration = expiresAt,
IsRevoked = false,
Code = code,
Challenge = command.CodeChallenge,
Algorithm = command.Algorithm,
};
var insertedAuthCodeEntity = await authCodeRepository.Upsert(authCodeEntity);
return insertedAuthCodeEntity.Match(
success => mapper.Map<AuthCodeDto>(success),
fail => new Result<AuthCodeDto>(fail)
);
}
}