start (actual) email auth, add CancellationToken to most async methods
This commit is contained in:
parent
acc54a55bc
commit
344a0071e5
22 changed files with 325 additions and 152 deletions
|
@ -42,11 +42,11 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
|
|||
/// This method does <i>not</i> save the resulting user, the caller must still call <see cref="M:Microsoft.EntityFrameworkCore.DbContext.SaveChanges" />.
|
||||
/// </summary>
|
||||
public async Task<User> CreateUserWithRemoteAuthAsync(string username, AuthType authType, string remoteId,
|
||||
string remoteUsername, FediverseApplication? instance = null)
|
||||
string remoteUsername, FediverseApplication? instance = null, CancellationToken ct = default)
|
||||
{
|
||||
AssertValidAuthType(authType, instance);
|
||||
|
||||
if (await db.Users.AnyAsync(u => u.Username == username))
|
||||
if (await db.Users.AnyAsync(u => u.Username == username, ct))
|
||||
throw new ApiError.BadRequest("Username is already taken", "username", username);
|
||||
|
||||
var user = new User
|
||||
|
@ -76,20 +76,20 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
|
|||
/// <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)
|
||||
public async Task<(User, EmailAuthenticationResult)> AuthenticateUserAsync(string email, string password, CancellationToken ct = default)
|
||||
{
|
||||
var user = await db.Users.FirstOrDefaultAsync(u =>
|
||||
u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email));
|
||||
u.AuthMethods.Any(a => a.AuthType == AuthType.Email && a.RemoteId == email), ct);
|
||||
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));
|
||||
var pwResult = await Task.Run(() => _passwordHasher.VerifyHashedPassword(user, user.Password!, password), ct);
|
||||
if (pwResult == PasswordVerificationResult.Failed)
|
||||
throw new ApiError.NotFound("No user with that email address found, or password is incorrect");
|
||||
if (pwResult == PasswordVerificationResult.SuccessRehashNeeded)
|
||||
{
|
||||
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password));
|
||||
await db.SaveChangesAsync();
|
||||
user.Password = await Task.Run(() => _passwordHasher.HashPassword(user, password), ct);
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
return (user, EmailAuthenticationResult.AuthSuccessful);
|
||||
|
@ -108,17 +108,38 @@ public class AuthService(IClock clock, DatabaseContext db, ISnowflakeGenerator s
|
|||
/// <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>
|
||||
/// <param name="ct">Cancellation token.</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)
|
||||
FediverseApplication? instance = null, CancellationToken ct = default)
|
||||
{
|
||||
AssertValidAuthType(authType, instance);
|
||||
|
||||
return await db.Users.FirstOrDefaultAsync(u =>
|
||||
u.AuthMethods.Any(a =>
|
||||
a.AuthType == authType && a.RemoteId == remoteId && a.FediverseApplication == instance));
|
||||
a.AuthType == authType && a.RemoteId == remoteId && a.FediverseApplication == instance), ct);
|
||||
}
|
||||
|
||||
public async Task<AuthMethod> AddAuthMethodAsync(Snowflake userId, AuthType authType, string remoteId,
|
||||
string? remoteUsername = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
AssertValidAuthType(authType, null);
|
||||
|
||||
var authMethod = new AuthMethod
|
||||
{
|
||||
Id = snowflakeGenerator.GenerateSnowflake(),
|
||||
AuthType = authType,
|
||||
RemoteId = remoteId,
|
||||
RemoteUsername = remoteUsername,
|
||||
UserId = userId
|
||||
};
|
||||
|
||||
db.Add(authMethod);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return authMethod;
|
||||
}
|
||||
|
||||
public (string, Token) GenerateToken(User user, Application application, string[] scopes, Instant expires)
|
||||
|
|
|
@ -11,10 +11,10 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
{
|
||||
private readonly ILogger _logger = logger.ForContext<KeyCacheService>();
|
||||
|
||||
public Task SetKeyAsync(string key, string value, Duration expireAfter) =>
|
||||
SetKeyAsync(key, value, clock.GetCurrentInstant() + expireAfter);
|
||||
public Task SetKeyAsync(string key, string value, Duration expireAfter, CancellationToken ct = default) =>
|
||||
SetKeyAsync(key, value, clock.GetCurrentInstant() + expireAfter, ct);
|
||||
|
||||
public async Task SetKeyAsync(string key, string value, Instant expires)
|
||||
public async Task SetKeyAsync(string key, string value, Instant expires, CancellationToken ct = default)
|
||||
{
|
||||
db.TemporaryKeys.Add(new TemporaryKey
|
||||
{
|
||||
|
@ -22,18 +22,18 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
Key = key,
|
||||
Value = value,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<string?> GetKeyAsync(string key, bool delete = false)
|
||||
public async Task<string?> GetKeyAsync(string key, bool delete = false, CancellationToken ct = default)
|
||||
{
|
||||
var value = await db.TemporaryKeys.FirstOrDefaultAsync(k => k.Key == key);
|
||||
var value = await db.TemporaryKeys.FirstOrDefaultAsync(k => k.Key == key, ct);
|
||||
if (value == null) return null;
|
||||
|
||||
if (delete)
|
||||
{
|
||||
await db.TemporaryKeys.Where(k => k.Key == key).ExecuteDeleteAsync();
|
||||
await db.SaveChangesAsync();
|
||||
await db.TemporaryKeys.Where(k => k.Key == key).ExecuteDeleteAsync(ct);
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
return value.Value;
|
||||
|
@ -45,18 +45,18 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
if (count != 0) _logger.Information("Removed {Count} expired keys from the database", count);
|
||||
}
|
||||
|
||||
public Task SetKeyAsync<T>(string key, T obj, Duration expiresAt) where T : class =>
|
||||
SetKeyAsync(key, obj, clock.GetCurrentInstant() + expiresAt);
|
||||
public Task SetKeyAsync<T>(string key, T obj, Duration expiresAt, CancellationToken ct = default) where T : class =>
|
||||
SetKeyAsync(key, obj, clock.GetCurrentInstant() + expiresAt, ct);
|
||||
|
||||
public async Task SetKeyAsync<T>(string key, T obj, Instant expires) where T : class
|
||||
public async Task SetKeyAsync<T>(string key, T obj, Instant expires, CancellationToken ct = default) where T : class
|
||||
{
|
||||
var value = JsonConvert.SerializeObject(obj);
|
||||
await SetKeyAsync(key, value, expires);
|
||||
await SetKeyAsync(key, value, expires, ct);
|
||||
}
|
||||
|
||||
public async Task<T?> GetKeyAsync<T>(string key, bool delete = false) where T : class
|
||||
public async Task<T?> GetKeyAsync<T>(string key, bool delete = false, CancellationToken ct = default) where T : class
|
||||
{
|
||||
var value = await GetKeyAsync(key, delete: false);
|
||||
var value = await GetKeyAsync(key, delete, ct);
|
||||
return value == null ? default : JsonConvert.DeserializeObject<T>(value);
|
||||
}
|
||||
}
|
24
Foxnouns.Backend/Services/MailService.cs
Normal file
24
Foxnouns.Backend/Services/MailService.cs
Normal file
|
@ -0,0 +1,24 @@
|
|||
using Coravel.Mailer.Mail.Interfaces;
|
||||
using Coravel.Queuing.Interfaces;
|
||||
using Foxnouns.Backend.Mailables;
|
||||
|
||||
namespace Foxnouns.Backend.Services;
|
||||
|
||||
public class MailService(ILogger logger, IMailer mailer, IQueue queue, Config config)
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<MailService>();
|
||||
|
||||
public void QueueAccountCreationEmail(string to, string code)
|
||||
{
|
||||
_logger.Debug("Sending account creation email to {ToEmail}", to);
|
||||
|
||||
queue.QueueAsyncTask(async () =>
|
||||
{
|
||||
await mailer.SendAsync(new AccountCreationMailable(config, new AccountCreationMailableView
|
||||
{
|
||||
To = to,
|
||||
Code = code
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
|
@ -8,12 +8,13 @@ public class ObjectStorageService(ILogger logger, Config config, IMinioClient mi
|
|||
{
|
||||
private readonly ILogger _logger = logger.ForContext<ObjectStorageService>();
|
||||
|
||||
public async Task RemoveObjectAsync(string path)
|
||||
public async Task RemoveObjectAsync(string path, CancellationToken ct = default)
|
||||
{
|
||||
_logger.Debug("Deleting object at path {Path}", path);
|
||||
try
|
||||
{
|
||||
await minio.RemoveObjectAsync(new RemoveObjectArgs().WithBucket(config.Storage.Bucket).WithObject(path));
|
||||
await minio.RemoveObjectAsync(new RemoveObjectArgs().WithBucket(config.Storage.Bucket).WithObject(path),
|
||||
ct);
|
||||
}
|
||||
catch (InvalidObjectNameException)
|
||||
{
|
||||
|
@ -21,17 +22,17 @@ public class ObjectStorageService(ILogger logger, Config config, IMinioClient mi
|
|||
}
|
||||
}
|
||||
|
||||
public async Task PutObjectAsync(string path, Stream data, string contentType)
|
||||
public async Task PutObjectAsync(string path, Stream data, string contentType, CancellationToken ct = default)
|
||||
{
|
||||
_logger.Debug("Putting object at path {Path} with length {Length} and content type {ContentType}", path,
|
||||
data.Length, contentType);
|
||||
|
||||
await minio.PutObjectAsync(new PutObjectArgs()
|
||||
.WithBucket(config.Storage.Bucket)
|
||||
.WithObject(path)
|
||||
.WithObjectSize(data.Length)
|
||||
.WithStreamData(data)
|
||||
.WithContentType(contentType)
|
||||
.WithBucket(config.Storage.Bucket)
|
||||
.WithObject(path)
|
||||
.WithObjectSize(data.Length)
|
||||
.WithStreamData(data)
|
||||
.WithContentType(contentType), ct
|
||||
);
|
||||
}
|
||||
}
|
|
@ -10,7 +10,7 @@ public class RemoteAuthService(Config config)
|
|||
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)
|
||||
public async Task<RemoteUser> RequestDiscordTokenAsync(string code, string state, CancellationToken ct = default)
|
||||
{
|
||||
var redirectUri = $"{config.BaseUrl}/auth/login/discord";
|
||||
var resp = await _httpClient.PostAsync(_discordTokenUri, new FormUrlEncodedContent(
|
||||
|
@ -22,17 +22,17 @@ public class RemoteAuthService(Config config)
|
|||
{ "code", code },
|
||||
{ "redirect_uri", redirectUri }
|
||||
}
|
||||
));
|
||||
), ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
var token = await resp.Content.ReadFromJsonAsync<DiscordTokenResponse>();
|
||||
var token = await resp.Content.ReadFromJsonAsync<DiscordTokenResponse>(ct);
|
||||
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);
|
||||
var resp2 = await _httpClient.SendAsync(req, ct);
|
||||
resp2.EnsureSuccessStatusCode();
|
||||
var user = await resp2.Content.ReadFromJsonAsync<DiscordUserResponse>();
|
||||
var user = await resp2.Content.ReadFromJsonAsync<DiscordUserResponse>(ct);
|
||||
if (user == null) throw new FoxnounsError("Discord user response was null");
|
||||
|
||||
return new RemoteUser(user.id, user.username);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue