using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Server.Data;
using Server.Services.Auth;
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 IPasswordHasher _hasher;
public AdminAuthService(IServiceScopeFactory scopeFactory, IPasswordHasher hasher)
{
_scopeFactory = scopeFactory;
_hasher = hasher;
}
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
var tokenHash = _hasher.HashToken(token);
// Find valid session with this token
var session = await db.Sessions
.Include(s => s.Account)
.Where(s => s.TokenHash == tokenHash.ToString()
&& s.RevokedAt == null
&& s.ExpiresAt > DateTime.UtcNow)
.FirstOrDefaultAsync();
if (session == null)
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}");
return AdminAuthResult.Success(account);
}
}
///
/// Extension methods for IPasswordHasher to support token hashing
///
public static class PasswordHasherExtensions
{
public static byte[] HashToken(this IPasswordHasher hasher, string token)
{
// Use SHA256 for token hashing (deterministic, no salt needed for lookup)
using var sha = System.Security.Cryptography.SHA256.Create();
return sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token));
}
}