2024-06-10 16:25:49 +02:00
|
|
|
using Foxnouns.Backend.Database;
|
2024-06-12 16:19:49 +02:00
|
|
|
using Foxnouns.Backend.Database.Models;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Extensions;
|
2024-06-12 16:19:49 +02:00
|
|
|
using Foxnouns.Backend.Services;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Utils;
|
2024-09-14 16:37:52 +02:00
|
|
|
using JetBrains.Annotations;
|
2024-06-10 16:25:49 +02:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2024-06-12 16:19:49 +02:00
|
|
|
using NodaTime;
|
2024-06-10 16:25:49 +02:00
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Controllers.Authentication;
|
|
|
|
|
2024-10-02 00:15:14 +02:00
|
|
|
[Route("/api/internal/auth/discord")]
|
2024-06-12 16:19:49 +02:00
|
|
|
public class DiscordAuthController(
|
2024-09-14 16:37:52 +02:00
|
|
|
[UsedImplicitly] Config config,
|
2024-06-12 16:19:49 +02:00
|
|
|
ILogger logger,
|
|
|
|
IClock clock,
|
|
|
|
DatabaseContext db,
|
2024-09-09 14:50:00 +02:00
|
|
|
KeyCacheService keyCacheService,
|
|
|
|
AuthService authService,
|
|
|
|
RemoteAuthService remoteAuthService,
|
2024-10-02 00:28:07 +02:00
|
|
|
UserRendererService userRenderer
|
|
|
|
) : ApiControllerBase
|
2024-06-10 16:25:49 +02:00
|
|
|
{
|
2024-09-04 14:25:44 +02:00
|
|
|
private readonly ILogger _logger = logger.ForContext<DiscordAuthController>();
|
|
|
|
|
2024-06-12 16:19:49 +02:00
|
|
|
[HttpPost("callback")]
|
2024-06-13 02:23:55 +02:00
|
|
|
// TODO: duplicating attribute doesn't work, find another way to mark both as possible response
|
|
|
|
// leaving it here for documentation purposes
|
|
|
|
[ProducesResponseType<AuthController.CallbackResponse>(StatusCodes.Status200OK)]
|
2024-11-02 21:23:49 +01:00
|
|
|
public async Task<IActionResult> CallbackAsync([FromBody] AuthController.CallbackRequest req)
|
2024-06-12 16:19:49 +02:00
|
|
|
{
|
|
|
|
CheckRequirements();
|
2024-11-02 21:23:49 +01:00
|
|
|
await keyCacheService.ValidateAuthStateAsync(req.State);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-11-02 21:23:49 +01:00
|
|
|
var remoteUser = await remoteAuthService.RequestDiscordTokenAsync(req.Code);
|
|
|
|
var user = await authService.AuthenticateUserAsync(AuthType.Discord, remoteUser.Id);
|
2024-10-02 00:28:07 +02:00
|
|
|
if (user != null)
|
2024-11-02 21:23:49 +01:00
|
|
|
return Ok(await GenerateUserTokenAsync(user));
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-10-02 00:28:07 +02:00
|
|
|
_logger.Debug(
|
|
|
|
"Discord user {Username} ({Id}) authenticated with no local account",
|
|
|
|
remoteUser.Username,
|
|
|
|
remoteUser.Id
|
|
|
|
);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-07-08 19:03:04 +02:00
|
|
|
var ticket = AuthUtils.RandomToken();
|
2024-10-02 00:28:07 +02:00
|
|
|
await keyCacheService.SetKeyAsync(
|
|
|
|
$"discord:{ticket}",
|
|
|
|
remoteUser,
|
2024-11-02 21:23:49 +01:00
|
|
|
Duration.FromMinutes(20)
|
2024-10-02 00:28:07 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
return Ok(
|
|
|
|
new AuthController.CallbackResponse(
|
|
|
|
HasAccount: false,
|
|
|
|
Ticket: ticket,
|
|
|
|
RemoteUsername: remoteUser.Username,
|
|
|
|
User: null,
|
|
|
|
Token: null,
|
|
|
|
ExpiresAt: null
|
|
|
|
)
|
|
|
|
);
|
2024-06-13 02:23:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPost("register")]
|
|
|
|
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
2024-10-02 00:28:07 +02:00
|
|
|
public async Task<IActionResult> RegisterAsync(
|
|
|
|
[FromBody] AuthController.OauthRegisterRequest req
|
|
|
|
)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
var remoteUser = await keyCacheService.GetKeyAsync<RemoteAuthService.RemoteUser>(
|
|
|
|
$"discord:{req.Ticket}"
|
|
|
|
);
|
|
|
|
if (remoteUser == null)
|
|
|
|
throw new ApiError.BadRequest("Invalid ticket", "ticket", req.Ticket);
|
|
|
|
if (
|
|
|
|
await db.AuthMethods.AnyAsync(a =>
|
|
|
|
a.AuthType == AuthType.Discord && a.RemoteId == remoteUser.Id
|
|
|
|
)
|
|
|
|
)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
_logger.Error(
|
|
|
|
"Discord user {Id} has valid ticket but is already linked to an existing account",
|
|
|
|
remoteUser.Id
|
|
|
|
);
|
2024-09-14 16:37:52 +02:00
|
|
|
throw new ApiError.BadRequest("Invalid ticket", "ticket", req.Ticket);
|
2024-06-13 02:23:55 +02:00
|
|
|
}
|
|
|
|
|
2024-10-02 00:28:07 +02:00
|
|
|
var user = await authService.CreateUserWithRemoteAuthAsync(
|
|
|
|
req.Username,
|
|
|
|
AuthType.Discord,
|
|
|
|
remoteUser.Id,
|
|
|
|
remoteUser.Username
|
|
|
|
);
|
2024-06-13 02:23:55 +02:00
|
|
|
|
2024-09-14 16:37:52 +02:00
|
|
|
return Ok(await GenerateUserTokenAsync(user));
|
2024-06-12 16:19:49 +02:00
|
|
|
}
|
|
|
|
|
2024-10-02 00:28:07 +02:00
|
|
|
private async Task<AuthController.CallbackResponse> GenerateUserTokenAsync(
|
|
|
|
User user,
|
|
|
|
CancellationToken ct = default
|
|
|
|
)
|
2024-06-12 16:19:49 +02:00
|
|
|
{
|
2024-09-09 14:37:59 +02:00
|
|
|
var frontendApp = await db.GetFrontendApplicationAsync(ct);
|
2024-09-04 14:25:44 +02:00
|
|
|
_logger.Debug("Logging user {Id} in with Discord", user.Id);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-10-02 00:28:07 +02:00
|
|
|
var (tokenStr, token) = authService.GenerateToken(
|
|
|
|
user,
|
|
|
|
frontendApp,
|
|
|
|
["*"],
|
|
|
|
clock.GetCurrentInstant() + Duration.FromDays(365)
|
|
|
|
);
|
2024-06-12 16:19:49 +02:00
|
|
|
db.Add(token);
|
|
|
|
|
2024-09-04 14:25:44 +02:00
|
|
|
_logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-09-09 14:37:59 +02:00
|
|
|
await db.SaveChangesAsync(ct);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-09-13 14:56:38 +02:00
|
|
|
return new AuthController.CallbackResponse(
|
|
|
|
HasAccount: true,
|
|
|
|
Ticket: null,
|
|
|
|
RemoteUsername: null,
|
2024-10-02 00:28:07 +02:00
|
|
|
User: await userRenderer.RenderUserAsync(
|
|
|
|
user,
|
|
|
|
selfUser: user,
|
|
|
|
renderMembers: false,
|
|
|
|
ct: ct
|
|
|
|
),
|
2024-09-13 14:56:38 +02:00
|
|
|
Token: tokenStr,
|
|
|
|
ExpiresAt: token.ExpiresAt
|
2024-06-12 16:19:49 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
private void CheckRequirements()
|
2024-06-10 16:25:49 +02:00
|
|
|
{
|
2024-06-12 16:19:49 +02:00
|
|
|
if (!config.DiscordAuth.Enabled)
|
2024-10-02 00:28:07 +02:00
|
|
|
throw new ApiError.BadRequest(
|
|
|
|
"Discord authentication is not enabled on this instance."
|
|
|
|
);
|
2024-06-10 16:25:49 +02:00
|
|
|
}
|
2024-10-02 00:28:07 +02:00
|
|
|
}
|