2024-06-12 03:47:20 +02:00
|
|
|
using Foxnouns.Backend.Database;
|
2024-09-09 14:37:59 +02:00
|
|
|
using Foxnouns.Backend.Database.Models;
|
|
|
|
using Foxnouns.Backend.Extensions;
|
2024-10-02 00:15:14 +02:00
|
|
|
using Foxnouns.Backend.Middleware;
|
2024-06-12 03:47:20 +02:00
|
|
|
using Foxnouns.Backend.Services;
|
2024-09-09 14:37:59 +02:00
|
|
|
using Foxnouns.Backend.Utils;
|
2024-09-14 16:37:52 +02:00
|
|
|
using JetBrains.Annotations;
|
2024-06-12 03:47:20 +02:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2024-09-09 14:37:59 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2024-06-12 03:47:20 +02:00
|
|
|
using NodaTime;
|
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Controllers.Authentication;
|
|
|
|
|
2024-10-02 00:15:14 +02:00
|
|
|
[Route("/api/internal/auth/email")]
|
2024-06-12 16:19:49 +02:00
|
|
|
public class EmailAuthController(
|
2024-09-14 16:37:52 +02:00
|
|
|
[UsedImplicitly] Config config,
|
2024-06-12 16:19:49 +02:00
|
|
|
DatabaseContext db,
|
2024-09-09 14:50:00 +02:00
|
|
|
AuthService authService,
|
|
|
|
MailService mailService,
|
|
|
|
KeyCacheService keyCacheService,
|
|
|
|
UserRendererService userRenderer,
|
2024-06-12 16:19:49 +02:00
|
|
|
IClock clock,
|
|
|
|
ILogger logger) : ApiControllerBase
|
2024-06-12 03:47:20 +02:00
|
|
|
{
|
2024-09-04 14:25:44 +02:00
|
|
|
private readonly ILogger _logger = logger.ForContext<EmailAuthController>();
|
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
[HttpPost("register")]
|
|
|
|
public async Task<IActionResult> RegisterAsync([FromBody] RegisterRequest req, CancellationToken ct = default)
|
|
|
|
{
|
2024-09-10 02:39:07 +02:00
|
|
|
CheckRequirements();
|
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
if (!req.Email.Contains('@')) throw new ApiError.BadRequest("Email is invalid", "email", req.Email);
|
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
var state = await keyCacheService.GenerateRegisterEmailStateAsync(req.Email, userId: null, ct);
|
2024-09-11 16:23:45 +02:00
|
|
|
|
2024-09-10 02:39:07 +02:00
|
|
|
// If there's already a user with that email address, pretend we sent an email but actually ignore it
|
2024-09-09 14:37:59 +02:00
|
|
|
if (await db.AuthMethods.AnyAsync(a => a.AuthType == AuthType.Email && a.RemoteId == req.Email, ct))
|
|
|
|
return NoContent();
|
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
mailService.QueueAccountCreationEmail(req.Email, state);
|
2024-09-09 14:37:59 +02:00
|
|
|
return NoContent();
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPost("callback")]
|
2024-09-11 16:23:45 +02:00
|
|
|
public async Task<IActionResult> CallbackAsync([FromBody] CallbackRequest req)
|
2024-09-09 14:37:59 +02:00
|
|
|
{
|
2024-09-10 02:39:07 +02:00
|
|
|
CheckRequirements();
|
|
|
|
|
2024-09-11 16:23:45 +02:00
|
|
|
var state = await keyCacheService.GetRegisterEmailStateAsync(req.State);
|
2024-09-09 14:37:59 +02:00
|
|
|
if (state == null) throw new ApiError.BadRequest("Invalid state", "state", req.State);
|
2024-09-11 16:23:45 +02:00
|
|
|
|
2024-09-10 02:39:07 +02:00
|
|
|
// If this callback is for an existing user, add the email address to their auth methods
|
2024-09-09 14:37:59 +02:00
|
|
|
if (state.ExistingUserId != null)
|
|
|
|
{
|
|
|
|
var authMethod =
|
2024-09-11 16:23:45 +02:00
|
|
|
await authService.AddAuthMethodAsync(state.ExistingUserId.Value, AuthType.Email, state.Email);
|
2024-09-09 14:37:59 +02:00
|
|
|
_logger.Debug("Added email auth {AuthId} for user {UserId}", authMethod.Id, state.ExistingUserId);
|
|
|
|
return NoContent();
|
|
|
|
}
|
|
|
|
|
|
|
|
var ticket = AuthUtils.RandomToken();
|
2024-09-11 16:23:45 +02:00
|
|
|
await keyCacheService.SetKeyAsync($"email:{ticket}", state.Email, Duration.FromMinutes(20));
|
2024-09-09 14:37:59 +02:00
|
|
|
|
2024-09-13 14:56:38 +02:00
|
|
|
return Ok(new AuthController.CallbackResponse(HasAccount: false, Ticket: ticket, RemoteUsername: state.Email,
|
|
|
|
User: null, Token: null, ExpiresAt: null));
|
2024-09-09 14:37:59 +02:00
|
|
|
}
|
|
|
|
|
2024-09-10 02:39:07 +02:00
|
|
|
[HttpPost("complete-registration")]
|
2024-09-11 16:23:45 +02:00
|
|
|
public async Task<IActionResult> CompleteRegistrationAsync([FromBody] CompleteRegistrationRequest req)
|
2024-09-10 02:39:07 +02:00
|
|
|
{
|
2024-09-11 16:23:45 +02:00
|
|
|
var email = await keyCacheService.GetKeyAsync($"email:{req.Ticket}");
|
2024-09-10 02:39:07 +02:00
|
|
|
if (email == null) throw new ApiError.BadRequest("Unknown ticket", "ticket", req.Ticket);
|
|
|
|
|
|
|
|
// Check if username is valid at all
|
|
|
|
ValidationUtils.Validate([("username", ValidationUtils.ValidateUsername(req.Username))]);
|
|
|
|
// Check if username is already taken
|
2024-09-11 16:23:45 +02:00
|
|
|
if (await db.Users.AnyAsync(u => u.Username == req.Username))
|
2024-09-10 02:39:07 +02:00
|
|
|
throw new ApiError.BadRequest("Username is already taken", "username", req.Username);
|
|
|
|
|
2024-09-11 16:23:45 +02:00
|
|
|
var user = await authService.CreateUserWithPasswordAsync(req.Username, email, req.Password);
|
|
|
|
var frontendApp = await db.GetFrontendApplicationAsync();
|
2024-09-10 02:39:07 +02:00
|
|
|
|
|
|
|
var (tokenStr, token) =
|
|
|
|
authService.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
|
|
|
db.Add(token);
|
|
|
|
|
2024-09-11 16:23:45 +02:00
|
|
|
await db.SaveChangesAsync();
|
2024-09-10 02:39:07 +02:00
|
|
|
|
2024-09-11 16:23:45 +02:00
|
|
|
await keyCacheService.DeleteKeyAsync($"email:{req.Ticket}");
|
2024-09-10 02:39:07 +02:00
|
|
|
|
|
|
|
return Ok(new AuthController.AuthResponse(
|
2024-09-11 16:23:45 +02:00
|
|
|
await userRenderer.RenderUserAsync(user, selfUser: user, renderMembers: false),
|
2024-09-10 02:39:07 +02:00
|
|
|
tokenStr,
|
|
|
|
token.ExpiresAt
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
[HttpPost("login")]
|
2024-06-12 16:19:49 +02:00
|
|
|
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
2024-09-09 14:37:59 +02:00
|
|
|
public async Task<IActionResult> LoginAsync([FromBody] LoginRequest req, CancellationToken ct = default)
|
2024-06-12 03:47:20 +02:00
|
|
|
{
|
2024-09-10 02:39:07 +02:00
|
|
|
CheckRequirements();
|
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
var (user, authenticationResult) = await authService.AuthenticateUserAsync(req.Email, req.Password, ct);
|
2024-06-12 16:19:49 +02:00
|
|
|
if (authenticationResult == AuthService.EmailAuthenticationResult.MfaRequired)
|
|
|
|
throw new NotImplementedException("MFA is not implemented yet");
|
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
var frontendApp = await db.GetFrontendApplicationAsync(ct);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-09-04 14:25:44 +02:00
|
|
|
_logger.Debug("Logging user {Id} in with email and password", user.Id);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
var (tokenStr, token) =
|
2024-09-09 14:50:00 +02:00
|
|
|
authService.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
2024-06-12 03:47:20 +02:00
|
|
|
db.Add(token);
|
|
|
|
|
2024-09-04 14:25:44 +02:00
|
|
|
_logger.Debug("Generated token {TokenId} for {UserId}", token.Id, user.Id);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
await db.SaveChangesAsync(ct);
|
2024-06-12 03:47:20 +02:00
|
|
|
|
|
|
|
return Ok(new AuthController.AuthResponse(
|
2024-09-09 14:50:00 +02:00
|
|
|
await userRenderer.RenderUserAsync(user, selfUser: user, renderMembers: false, ct: ct),
|
2024-06-12 03:47:20 +02:00
|
|
|
tokenStr,
|
|
|
|
token.ExpiresAt
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2024-10-02 00:15:14 +02:00
|
|
|
[HttpPost("add")]
|
|
|
|
[Authorize("*")]
|
|
|
|
public async Task<IActionResult> AddEmailAddressAsync()
|
|
|
|
{
|
|
|
|
_logger.Information("beep");
|
|
|
|
|
|
|
|
return NoContent();
|
|
|
|
}
|
|
|
|
|
|
|
|
public record AddEmailAddressRequest(string Email, string Password);
|
|
|
|
|
2024-09-10 02:39:07 +02:00
|
|
|
private void CheckRequirements()
|
|
|
|
{
|
2024-10-01 21:58:13 +02:00
|
|
|
if (!config.EmailAuth.Enabled)
|
2024-09-10 02:39:07 +02:00
|
|
|
throw new ApiError.BadRequest("Email authentication is not enabled on this instance.");
|
|
|
|
}
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
public record LoginRequest(string Email, string Password);
|
2024-09-09 14:37:59 +02:00
|
|
|
|
|
|
|
public record RegisterRequest(string Email);
|
|
|
|
|
2024-09-10 02:39:07 +02:00
|
|
|
public record CompleteRegistrationRequest(string Ticket, string Username, string Password);
|
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
public record CallbackRequest(string State);
|
2024-06-12 03:47:20 +02:00
|
|
|
}
|