feat(backend): add RequestDiscordTokenAsync method
This commit is contained in:
parent
2a7bd746aa
commit
6186eda092
12 changed files with 230 additions and 22 deletions
|
@ -15,6 +15,8 @@ public class Config
|
|||
|
||||
public DatabaseConfig Database { get; init; } = new();
|
||||
public DiscordAuthConfig DiscordAuth { get; init; } = new();
|
||||
public GoogleAuthConfig GoogleAuth { get; init; } = new();
|
||||
public TumblrAuthConfig TumblrAuth { get; init; } = new();
|
||||
|
||||
public class DatabaseConfig
|
||||
{
|
||||
|
@ -25,6 +27,24 @@ public class Config
|
|||
|
||||
public class DiscordAuthConfig
|
||||
{
|
||||
public bool Enabled => ClientId != null && ClientSecret != null;
|
||||
|
||||
public string? ClientId { get; init; }
|
||||
public string? ClientSecret { get; init; }
|
||||
}
|
||||
|
||||
public class GoogleAuthConfig
|
||||
{
|
||||
public bool Enabled => ClientId != null && ClientSecret != null;
|
||||
|
||||
public string? ClientId { get; init; }
|
||||
public string? ClientSecret { get; init; }
|
||||
}
|
||||
|
||||
public class TumblrAuthConfig
|
||||
{
|
||||
public bool Enabled => ClientId != null && ClientSecret != null;
|
||||
|
||||
public string? ClientId { get; init; }
|
||||
public string? ClientSecret { get; init; }
|
||||
}
|
||||
|
|
|
@ -6,12 +6,16 @@ using NodaTime;
|
|||
namespace Foxnouns.Backend.Controllers.Authentication;
|
||||
|
||||
[Route("/api/v2/auth")]
|
||||
public class AuthController(Config config, KeyCacheService keyCacheSvc) : ApiControllerBase
|
||||
public class AuthController(Config config, KeyCacheService keyCacheSvc, ILogger logger) : ApiControllerBase
|
||||
{
|
||||
[HttpPost("urls")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UrlsResponse))]
|
||||
[ProducesResponseType<UrlsResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> UrlsAsync()
|
||||
{
|
||||
logger.Debug("Generating auth URLs for Discord: {Discord}, Google: {Google}, Tumblr: {Tumblr}",
|
||||
config.DiscordAuth.Enabled,
|
||||
config.GoogleAuth.Enabled,
|
||||
config.TumblrAuth.Enabled);
|
||||
var state = HttpUtility.UrlEncode(await keyCacheSvc.GenerateAuthStateAsync());
|
||||
string? discord = null;
|
||||
if (config.DiscordAuth.ClientId != null && config.DiscordAuth.ClientSecret != null)
|
||||
|
@ -35,4 +39,6 @@ public class AuthController(Config config, KeyCacheService keyCacheSvc) : ApiCon
|
|||
string Token,
|
||||
Instant ExpiresAt
|
||||
);
|
||||
|
||||
public record CallbackRequest(string Code, string State);
|
||||
}
|
|
@ -1,16 +1,61 @@
|
|||
using Foxnouns.Backend.Database;
|
||||
using Foxnouns.Backend.Database.Models;
|
||||
using Foxnouns.Backend.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NodaTime;
|
||||
|
||||
namespace Foxnouns.Backend.Controllers.Authentication;
|
||||
|
||||
[Route("/api/v2/auth/discord")]
|
||||
public class DiscordAuthController(Config config, DatabaseContext db) : ApiControllerBase
|
||||
public class DiscordAuthController(
|
||||
Config config,
|
||||
ILogger logger,
|
||||
IClock clock,
|
||||
DatabaseContext db,
|
||||
KeyCacheService keyCacheSvc,
|
||||
AuthService authSvc,
|
||||
RemoteAuthService remoteAuthSvc,
|
||||
UserRendererService userRendererSvc) : ApiControllerBase
|
||||
{
|
||||
[HttpPost("callback")]
|
||||
public async Task<IActionResult> CallbackAsync([FromBody] AuthController.CallbackRequest req)
|
||||
{
|
||||
CheckRequirements();
|
||||
await keyCacheSvc.ValidateAuthStateAsync(req.State);
|
||||
|
||||
var remoteUser = await remoteAuthSvc.RequestDiscordTokenAsync(req.Code, req.State);
|
||||
var user = await authSvc.AuthenticateUserAsync(AuthType.Discord, remoteUser.Id);
|
||||
if (user != null) return Ok(await GenerateUserTokenAsync(user));
|
||||
|
||||
logger.Debug("Discord user {Username} ({Id}) authenticated with no local account", remoteUser.Username,
|
||||
remoteUser.Id);
|
||||
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private async Task<AuthController.AuthResponse> GenerateUserTokenAsync(User user)
|
||||
{
|
||||
var frontendApp = await db.GetFrontendApplicationAsync();
|
||||
logger.Debug("Logging user {Id} in with Discord", user.Id);
|
||||
|
||||
var (tokenStr, token) =
|
||||
authSvc.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
||||
db.Add(token);
|
||||
|
||||
logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return new AuthController.AuthResponse(
|
||||
await userRendererSvc.RenderUserAsync(user, selfUser: user, renderMembers: false),
|
||||
tokenStr,
|
||||
token.ExpiresAt
|
||||
);
|
||||
}
|
||||
|
||||
private void CheckRequirements()
|
||||
{
|
||||
if (config.DiscordAuth.ClientId == null || config.DiscordAuth.ClientSecret == null)
|
||||
{
|
||||
if (!config.DiscordAuth.Enabled)
|
||||
throw new ApiError.BadRequest("Discord authentication is not enabled on this instance.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,18 +6,31 @@ using NodaTime;
|
|||
namespace Foxnouns.Backend.Controllers.Authentication;
|
||||
|
||||
[Route("/api/v2/auth/email")]
|
||||
public class EmailAuthController(DatabaseContext db, AuthService authSvc, UserRendererService userRendererSvc, IClock clock, ILogger logger) : ApiControllerBase
|
||||
public class EmailAuthController(
|
||||
DatabaseContext db,
|
||||
AuthService authSvc,
|
||||
UserRendererService userRendererSvc,
|
||||
IClock clock,
|
||||
ILogger logger) : ApiControllerBase
|
||||
{
|
||||
[HttpPost("login")]
|
||||
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> LoginAsync([FromBody] LoginRequest req)
|
||||
{
|
||||
var user = await authSvc.AuthenticateUserAsync(req.Email, req.Password);
|
||||
var (user, authenticationResult) = await authSvc.AuthenticateUserAsync(req.Email, req.Password);
|
||||
if (authenticationResult == AuthService.EmailAuthenticationResult.MfaRequired)
|
||||
throw new NotImplementedException("MFA is not implemented yet");
|
||||
|
||||
var frontendApp = await db.GetFrontendApplicationAsync();
|
||||
|
||||
logger.Debug("Logging user {Id} in with email and password", user.Id);
|
||||
|
||||
var (tokenStr, token) =
|
||||
authSvc.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
||||
db.Add(token);
|
||||
|
||||
logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(new AuthController.AuthResponse(
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
using Foxnouns.Backend.Controllers.Authentication;
|
||||
using Foxnouns.Backend.Database;
|
||||
using Foxnouns.Backend.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
@ -6,10 +7,15 @@ using NodaTime;
|
|||
namespace Foxnouns.Backend.Controllers;
|
||||
|
||||
[Route("/api/v2/debug")]
|
||||
public class DebugController(DatabaseContext db, AuthService authSvc, IClock clock, ILogger logger) : ApiControllerBase
|
||||
public class DebugController(
|
||||
DatabaseContext db,
|
||||
AuthService authSvc,
|
||||
UserRendererService userRendererSvc,
|
||||
IClock clock,
|
||||
ILogger logger) : ApiControllerBase
|
||||
{
|
||||
[HttpPost("users")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AuthResponse))]
|
||||
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CreateUserAsync([FromBody] CreateUserRequest req)
|
||||
{
|
||||
logger.Debug("Creating user with username {Username} and email {Email}", req.Username, req.Email);
|
||||
|
@ -23,10 +29,12 @@ public class DebugController(DatabaseContext db, AuthService authSvc, IClock clo
|
|||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return Ok(new AuthResponse(user.Id, user.Username, tokenStr));
|
||||
return Ok(new AuthController.AuthResponse(
|
||||
await userRendererSvc.RenderUserAsync(user, selfUser: user, renderMembers: false),
|
||||
tokenStr,
|
||||
token.ExpiresAt
|
||||
));
|
||||
}
|
||||
|
||||
public record CreateUserRequest(string Username, string Password, string Email);
|
||||
|
||||
private record AuthResponse(Snowflake Id, string Username, string Token);
|
||||
}
|
|
@ -20,6 +20,9 @@ public class MetaController(DatabaseContext db) : ApiControllerBase
|
|||
);
|
||||
}
|
||||
|
||||
[HttpGet("coffee")]
|
||||
public IActionResult BrewCoffee() => Problem("Sorry, I'm a teapot!", statusCode: StatusCodes.Status418ImATeapot);
|
||||
|
||||
private record MetaResponse(string Version, string Hash, int Members, UserInfo Users);
|
||||
|
||||
private record UserInfo(int Total, int ActiveMonth, int ActiveWeek, int ActiveDay);
|
||||
|
|
|
@ -67,7 +67,8 @@ public static class WebApplicationExtensions
|
|||
.AddScoped<UserRendererService>()
|
||||
.AddScoped<MemberRendererService>()
|
||||
.AddScoped<AuthService>()
|
||||
.AddScoped<KeyCacheService>();
|
||||
.AddScoped<KeyCacheService>()
|
||||
.AddScoped<RemoteAuthService>();
|
||||
|
||||
public static IServiceCollection AddCustomMiddleware(this IServiceCollection services) => services
|
||||
.AddScoped<ErrorHandlerMiddleware>()
|
||||
|
|
|
@ -22,7 +22,11 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
|
|||
{
|
||||
Id = snowflakeGenerator.GenerateSnowflake(),
|
||||
Username = username,
|
||||
AuthMethods = { new AuthMethod { Id = snowflakeGenerator.GenerateSnowflake(), AuthType = AuthType.Email, RemoteId = email } }
|
||||
AuthMethods =
|
||||
{
|
||||
new AuthMethod
|
||||
{ Id = snowflakeGenerator.GenerateSnowflake(), AuthType = AuthType.Email, RemoteId = email }
|
||||
}
|
||||
};
|
||||
|
||||
db.Add(user);
|
||||
|
@ -31,10 +35,20 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
|
|||
return user;
|
||||
}
|
||||
|
||||
public async Task<User> AuthenticateUserAsync(string email, string password)
|
||||
/// <summary>
|
||||
/// Authenticates a user with email and password.
|
||||
/// </summary>
|
||||
/// <param name="email">The user's email address</param>
|
||||
/// <param name="password">The user's password, in plain text</param>
|
||||
/// <returns>A tuple of the authenticated user and whether multi-factor authentication is required</returns>
|
||||
/// <exception cref="ApiError.NotFound">Thrown if the email address is not associated with any user
|
||||
/// or if the password is incorrect</exception>
|
||||
public async Task<(User, EmailAuthenticationResult)> AuthenticateUserAsync(string email, string password)
|
||||
{
|
||||
var user = await db.Users.FirstOrDefaultAsync(u => u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email));
|
||||
if (user == null) throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
|
||||
var user = await db.Users.FirstOrDefaultAsync(u =>
|
||||
u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email));
|
||||
if (user == null)
|
||||
throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
|
||||
|
||||
var pwResult = await Task.Run(() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password));
|
||||
if (pwResult == PasswordVerificationResult.Failed)
|
||||
|
@ -45,7 +59,36 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
|
|||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
return user;
|
||||
return (user, EmailAuthenticationResult.AuthSuccessful);
|
||||
}
|
||||
|
||||
public enum EmailAuthenticationResult
|
||||
{
|
||||
AuthSuccessful,
|
||||
MfaRequired,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates a user with a remote authentication provider.
|
||||
/// </summary>
|
||||
/// <param name="authType">The remote authentication provider type</param>
|
||||
/// <param name="remoteId">The remote user ID</param>
|
||||
/// <param name="instance">The Fediverse instance, if authType is Fediverse.
|
||||
/// Will throw an exception if passed with another authType.</param>
|
||||
/// <returns>A user object, or null if the remote account isn't linked to any user.</returns>
|
||||
/// <exception cref="FoxnounsError">Thrown if <c>instance</c> is passed when not required,
|
||||
/// or not passed when required</exception>
|
||||
public async Task<User?> AuthenticateUserAsync(AuthType authType, string remoteId,
|
||||
FediverseApplication? instance = null)
|
||||
{
|
||||
if (authType == AuthType.Fediverse && instance == null)
|
||||
throw new FoxnounsError("Fediverse authentication requires an instance.");
|
||||
if (authType != AuthType.Fediverse && instance != null)
|
||||
throw new FoxnounsError("Non-Fediverse authentication does not require an instance.");
|
||||
|
||||
return await db.Users.FirstOrDefaultAsync(u =>
|
||||
u.AuthMethods.Any(a =>
|
||||
a.AuthType == authType && a.RemoteId == remoteId && a.FediverseApplication == instance));
|
||||
}
|
||||
|
||||
public (string, Token) GenerateToken(User user, Application application, string[] scopes, Instant expires)
|
||||
|
|
|
@ -48,4 +48,10 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
await SetKeyAsync($"oauth_state:{state}", "", Duration.FromMinutes(10));
|
||||
return state;
|
||||
}
|
||||
|
||||
public async Task ValidateAuthStateAsync(string state)
|
||||
{
|
||||
var val = await GetKeyAsync($"oauth_state:{state}", delete: true);
|
||||
if (val == null) throw new ApiError.BadRequest("Invalid OAuth state");
|
||||
}
|
||||
}
|
48
Foxnouns.Backend/Services/RemoteAuthService.cs
Normal file
48
Foxnouns.Backend/Services/RemoteAuthService.cs
Normal file
|
@ -0,0 +1,48 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Web;
|
||||
|
||||
namespace Foxnouns.Backend.Services;
|
||||
|
||||
public class RemoteAuthService(Config config)
|
||||
{
|
||||
private readonly HttpClient _httpClient = new();
|
||||
|
||||
private readonly Uri _discordTokenUri = new("https://discord.com/api/oauth2/token");
|
||||
private readonly Uri _discordUserUri = new("https://discord.com/api/v10/users/@me");
|
||||
|
||||
public async Task<RemoteUser> RequestDiscordTokenAsync(string code, string state)
|
||||
{
|
||||
var redirectUri = $"{config.BaseUrl}/auth/login/discord";
|
||||
var resp = await _httpClient.PostAsync(_discordTokenUri, new FormUrlEncodedContent(
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
{ "client_id", config.DiscordAuth.ClientId! },
|
||||
{ "client_secret", config.DiscordAuth.ClientSecret! },
|
||||
{ "grant_type", "authorization_code" },
|
||||
{ "code", code },
|
||||
{ "redirect_uri", redirectUri }
|
||||
}
|
||||
));
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var token = await resp.Content.ReadFromJsonAsync<DiscordTokenResponse>();
|
||||
if (token == null) throw new FoxnounsError("Discord token response was null");
|
||||
|
||||
var req = new HttpRequestMessage(HttpMethod.Get, _discordUserUri);
|
||||
req.Headers.Add("Authorization", $"{token.token_type} {token.access_token}");
|
||||
|
||||
var resp2 = await _httpClient.SendAsync(req);
|
||||
resp2.EnsureSuccessStatusCode();
|
||||
var user = await resp2.Content.ReadFromJsonAsync<DiscordUserResponse>();
|
||||
if (user == null) throw new FoxnounsError("Discord user response was null");
|
||||
|
||||
return new RemoteUser(user.id, user.username);
|
||||
}
|
||||
|
||||
[SuppressMessage("ReSharper", "InconsistentNaming")]
|
||||
private record DiscordTokenResponse(string access_token, string token_type);
|
||||
|
||||
[SuppressMessage("ReSharper", "InconsistentNaming")]
|
||||
private record DiscordUserResponse(string id, string username);
|
||||
|
||||
public record RemoteUser(string Id, string Username);
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
import { fastRequest } from "$lib/request";
|
||||
|
||||
export const load = async ({ fetch, url }) => {
|
||||
await fastRequest(fetch, "POST", "/auth/discord/callback", {
|
||||
body: {
|
||||
code: url.searchParams.get("code"),
|
||||
state: url.searchParams.get("state"),
|
||||
},
|
||||
});
|
||||
};
|
|
@ -0,0 +1,5 @@
|
|||
<script lang="ts">
|
||||
|
||||
</script>
|
||||
|
||||
<p>omg its a login page</p>
|
Loading…
Reference in a new issue