89 lines
3.1 KiB
C#
89 lines
3.1 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Server.Data;
|
|
|
|
namespace Server.Services.Auth;
|
|
|
|
/// <summary>
|
|
/// Service for validating admin authentication via session tokens
|
|
/// </summary>
|
|
public interface IAdminAuthService
|
|
{
|
|
/// <summary>
|
|
/// Validates a session token and returns the account if authorized for the required role
|
|
/// </summary>
|
|
Task<AdminAuthResult> 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<AdminAuthService> _log;
|
|
|
|
public AdminAuthService(IServiceScopeFactory scopeFactory, ILogger<AdminAuthService> log)
|
|
{
|
|
_scopeFactory = scopeFactory;
|
|
_log = log;
|
|
}
|
|
|
|
public async Task<AdminAuthResult> 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<GameDbContext>();
|
|
|
|
// Hash the token to match against stored hash
|
|
var tokenHash = HashTokenToString(token);
|
|
|
|
_log.LogDebug("Validating token 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.LogDebug("No session found for 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 HashTokenToString(string token)
|
|
{
|
|
using var sha = System.Security.Cryptography.SHA256.Create();
|
|
var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token));
|
|
return Convert.ToHexString(hashBytes).ToLowerInvariant(); // Hex is safer than base64
|
|
}
|
|
}
|