2024-06-12 03:47:20 +02:00
|
|
|
using Foxnouns.Backend.Database;
|
|
|
|
using Foxnouns.Backend.Services;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
using NodaTime;
|
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Controllers.Authentication;
|
|
|
|
|
|
|
|
[Route("/api/v2/auth/email")]
|
2024-06-12 16:19:49 +02:00
|
|
|
public class EmailAuthController(
|
|
|
|
DatabaseContext db,
|
|
|
|
AuthService authSvc,
|
|
|
|
UserRendererService userRendererSvc,
|
|
|
|
IClock clock,
|
|
|
|
ILogger logger) : ApiControllerBase
|
2024-06-12 03:47:20 +02:00
|
|
|
{
|
|
|
|
[HttpPost("login")]
|
2024-06-12 16:19:49 +02:00
|
|
|
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
2024-06-12 03:47:20 +02:00
|
|
|
public async Task<IActionResult> LoginAsync([FromBody] LoginRequest req)
|
|
|
|
{
|
2024-06-12 16:19:49 +02:00
|
|
|
var (user, authenticationResult) = await authSvc.AuthenticateUserAsync(req.Email, req.Password);
|
|
|
|
if (authenticationResult == AuthService.EmailAuthenticationResult.MfaRequired)
|
|
|
|
throw new NotImplementedException("MFA is not implemented yet");
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
var frontendApp = await db.GetFrontendApplicationAsync();
|
2024-06-12 16:19:49 +02:00
|
|
|
|
|
|
|
logger.Debug("Logging user {Id} in with email and password", user.Id);
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
var (tokenStr, token) =
|
|
|
|
authSvc.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
|
|
|
db.Add(token);
|
|
|
|
|
2024-06-12 16:19:49 +02:00
|
|
|
logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
await db.SaveChangesAsync();
|
|
|
|
|
|
|
|
return Ok(new AuthController.AuthResponse(
|
|
|
|
await userRendererSvc.RenderUserAsync(user, selfUser: user, renderMembers: false),
|
|
|
|
tokenStr,
|
|
|
|
token.ExpiresAt
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
public record LoginRequest(string Email, string Password);
|
|
|
|
}
|