shellcoreDB made... n shi
This commit is contained in:
1 parent
244bd918d6
commit
bcc9894062
19 files changed
+493
-22
No files matched your search
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
using Dapper;
|
||||
|
||||
namespace ShellcoreDB;
|
||||
|
||||
public sealed class Sessions(Database database, TimeSpan lifetime)
|
||||
{
|
||||
public async Task<LoginData> Issue(Guid accountId, string username, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
var expiresAt = DateTime.UtcNow.Add(lifetime);
|
||||
await using var connection = await database.Open(cancellationToken);
|
||||
await connection.ExecuteAsync(new CommandDefinition(
|
||||
"INSERT INTO sessions (accountId, tokenHash, expiresAt) VALUES (@accountId, @tokenHash, @expiresAt)",
|
||||
new { accountId, tokenHash = Hash(token), expiresAt }, cancellationToken: cancellationToken));
|
||||
return new(accountId, username, token, expiresAt);
|
||||
}
|
||||
|
||||
public async Task<ValidationData?> Validate(string token, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await database.Open(cancellationToken);
|
||||
return await connection.QuerySingleOrDefaultAsync<ValidationData>(new CommandDefinition(
|
||||
"SELECT s.accountId, s.expiresAt FROM sessions s JOIN accounts a ON a.id = s.accountId WHERE s.tokenHash = @tokenHash AND s.expiresAt > NOW() AND s.revokedAt IS NULL AND a.status = 'active'",
|
||||
new { tokenHash = Hash(token) }, cancellationToken: cancellationToken));
|
||||
}
|
||||
|
||||
public async Task<bool> Revoke(string token, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await database.Open(cancellationToken);
|
||||
return await connection.ExecuteScalarAsync<Guid?>(new CommandDefinition(
|
||||
"UPDATE sessions SET revokedAt = NOW() WHERE tokenHash = @tokenHash AND revokedAt IS NULL RETURNING id",
|
||||
new { tokenHash = Hash(token) }, cancellationToken: cancellationToken)) is not null;
|
||||
}
|
||||
|
||||
private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(token)));
|
||||
}
|
||||
Reference in new issue
Block a user