feat(backend): add RequestDiscordTokenAsync method

This commit is contained in:
sam 2024-06-12 16:19:49 +02:00
parent 2a7bd746aa
commit 6186eda092
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
12 changed files with 230 additions and 22 deletions

View file

@ -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,11 +35,21 @@ 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)
throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
@ -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)

View file

@ -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");
}
}

View 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);
}