2024-06-12 03:47:20 +02:00
|
|
|
using System.Web;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Extensions;
|
2024-06-12 03:47:20 +02:00
|
|
|
using Foxnouns.Backend.Services;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
using NodaTime;
|
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Controllers.Authentication;
|
|
|
|
|
|
|
|
[Route("/api/v2/auth")]
|
2024-06-12 16:19:49 +02:00
|
|
|
public class AuthController(Config config, KeyCacheService keyCacheSvc, ILogger logger) : ApiControllerBase
|
|
|
|
{
|
2024-09-04 14:25:44 +02:00
|
|
|
private readonly ILogger _logger = logger.ForContext<AuthController>();
|
|
|
|
|
2024-06-12 03:47:20 +02:00
|
|
|
[HttpPost("urls")]
|
2024-06-12 16:19:49 +02:00
|
|
|
[ProducesResponseType<UrlsResponse>(StatusCodes.Status200OK)]
|
2024-09-09 14:37:59 +02:00
|
|
|
public async Task<IActionResult> UrlsAsync(CancellationToken ct = default)
|
2024-06-12 03:47:20 +02:00
|
|
|
{
|
2024-09-04 14:25:44 +02:00
|
|
|
_logger.Debug("Generating auth URLs for Discord: {Discord}, Google: {Google}, Tumblr: {Tumblr}",
|
2024-06-12 16:19:49 +02:00
|
|
|
config.DiscordAuth.Enabled,
|
|
|
|
config.GoogleAuth.Enabled,
|
|
|
|
config.TumblrAuth.Enabled);
|
2024-09-09 14:37:59 +02:00
|
|
|
var state = HttpUtility.UrlEncode(await keyCacheSvc.GenerateAuthStateAsync(ct));
|
2024-06-12 03:47:20 +02:00
|
|
|
string? discord = null;
|
2024-09-03 16:29:51 +02:00
|
|
|
if (config.DiscordAuth is { ClientId: not null, ClientSecret: not null })
|
2024-06-12 03:47:20 +02:00
|
|
|
discord =
|
|
|
|
$"https://discord.com/oauth2/authorize?response_type=code" +
|
|
|
|
$"&client_id={config.DiscordAuth.ClientId}&scope=identify" +
|
|
|
|
$"&prompt=none&state={state}" +
|
|
|
|
$"&redirect_uri={HttpUtility.UrlEncode($"{config.BaseUrl}/auth/login/discord")}";
|
|
|
|
|
|
|
|
return Ok(new UrlsResponse(discord, null, null));
|
|
|
|
}
|
|
|
|
|
|
|
|
private record UrlsResponse(
|
|
|
|
string? Discord,
|
|
|
|
string? Google,
|
|
|
|
string? Tumblr
|
|
|
|
);
|
|
|
|
|
2024-06-13 02:23:55 +02:00
|
|
|
public record AuthResponse(
|
2024-06-12 03:47:20 +02:00
|
|
|
UserRendererService.UserResponse User,
|
|
|
|
string Token,
|
|
|
|
Instant ExpiresAt
|
|
|
|
);
|
2024-06-12 16:19:49 +02:00
|
|
|
|
2024-06-13 02:23:55 +02:00
|
|
|
public record CallbackResponse(
|
|
|
|
bool HasAccount, // If true, user has an account, but it's deleted
|
|
|
|
string Ticket,
|
|
|
|
string? RemoteUsername
|
|
|
|
);
|
|
|
|
|
|
|
|
public record OauthRegisterRequest(string Ticket, string Username);
|
|
|
|
|
2024-06-12 16:19:49 +02:00
|
|
|
public record CallbackRequest(string Code, string State);
|
2024-06-12 03:47:20 +02:00
|
|
|
}
|