feat: initial working discord authentication

This commit is contained in:
sam 2024-06-13 02:23:55 +02:00
parent 6186eda092
commit a7950671e1
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
12 changed files with 262 additions and 25 deletions

View file

@ -34,6 +34,37 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
return user;
}
/// <summary>
/// Creates a new user with the given username and remote authentication method.
/// To create a user with email authentication, use <see cref="CreateUserWithPasswordAsync" />
/// 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)
{
AssertValidAuthType(authType, instance);
if (await db.Users.AnyAsync(u => u.Username == username))
throw new ApiError.BadRequest("Username is already taken");
var user = new User
{
Id = snowflakeGenerator.GenerateSnowflake(),
Username = username,
AuthMethods =
{
new AuthMethod
{
Id = snowflakeGenerator.GenerateSnowflake(), AuthType = authType, RemoteId = remoteId,
RemoteUsername = remoteUsername, FediverseApplication = instance
}
}
};
db.Add(user);
return user;
}
/// <summary>
/// Authenticates a user with email and password.
@ -81,10 +112,7 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
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.");
AssertValidAuthType(authType, instance);
return await db.Users.FirstOrDefaultAsync(u =>
u.AuthMethods.Any(a =>
@ -115,4 +143,12 @@ public class AuthService(ILogger logger, DatabaseContext db, ISnowflakeGenerator
return (token, hash);
}
private static void AssertValidAuthType(AuthType authType, FediverseApplication? instance)
{
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.");
}
}

View file

@ -2,6 +2,7 @@ using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Foxnouns.Backend.Utils;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NodaTime;
namespace Foxnouns.Backend.Services;
@ -42,16 +43,18 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
if (count != 0) logger.Information("Removed {Count} expired keys from the database", count);
}
public async Task<string> GenerateAuthStateAsync()
public Task SetKeyAsync<T>(string key, T obj, Duration expiresAt) where T : class =>
SetKeyAsync(key, obj, clock.GetCurrentInstant() + expiresAt);
public async Task SetKeyAsync<T>(string key, T obj, Instant expires) where T : class
{
var state = OauthUtils.RandomToken();
await SetKeyAsync($"oauth_state:{state}", "", Duration.FromMinutes(10));
return state;
var value = JsonConvert.SerializeObject(obj);
await SetKeyAsync(key, value, expires);
}
public async Task ValidateAuthStateAsync(string state)
public async Task<T?> GetKeyAsync<T>(string key, bool delete = false) where T : class
{
var val = await GetKeyAsync($"oauth_state:{state}", delete: true);
if (val == null) throw new ApiError.BadRequest("Invalid OAuth state");
var value = await GetKeyAsync(key, delete: false);
return value == null ? default : JsonConvert.DeserializeObject<T>(value);
}
}