using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Server.Data; namespace Server.Services.Auth; /// /// Service for validating admin authentication via session tokens /// public interface IAdminAuthService { /// /// Validates a session token and returns the account if authorized for the required role /// Task ValidateAsync(string? token, AccountRole requiredRole = AccountRole.Admin); } public sealed class AdminAuthResult { public bool IsAuthorized { get; init; } public Account? Account { get; init; } public string? Error { get; init; } public static AdminAuthResult Success(Account account) => new() { IsAuthorized = true, Account = account }; public static AdminAuthResult Fail(string error) => new() { IsAuthorized = false, Error = error }; } public sealed class AdminAuthService : IAdminAuthService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _log; public AdminAuthService(IServiceScopeFactory scopeFactory, ILogger log) { _scopeFactory = scopeFactory; _log = log; } public async Task ValidateAsync(string? token, AccountRole requiredRole = AccountRole.Admin) { if (string.IsNullOrWhiteSpace(token)) return AdminAuthResult.Fail("Missing authorization token"); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Hash the token to match against stored hash (base64 format) var tokenHash = HashTokenToBase64(token); _log.LogDebug("Validating token, computed hash: {Hash}", tokenHash); // Find valid session with this token var session = await db.Sessions .Include(s => s.Account) .Where(s => s.TokenHash == tokenHash && s.RevokedAt == null && s.ExpiresAt > DateTime.UtcNow) .FirstOrDefaultAsync(); if (session == null) { _log.LogWarning("No session found for token hash: {Hash}", tokenHash); return AdminAuthResult.Fail("Invalid or expired token"); } var account = session.Account; if (account == null) return AdminAuthResult.Fail("Account not found"); if (account.IsBanned) return AdminAuthResult.Fail("Account is banned"); if (account.Role < requiredRole) return AdminAuthResult.Fail($"Insufficient permissions. Required: {requiredRole}, Current: {account.Role}"); _log.LogDebug("Token validated for user {User} with role {Role}", account.Username, account.Role); return AdminAuthResult.Success(account); } private static string HashTokenToBase64(string token) { using var sha = System.Security.Cryptography.SHA256.Create(); var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token)); return Convert.ToBase64String(hashBytes); } }