namespace SOR.Auth.Handlers; using System.Security.Cryptography; using System.Text; using Grpc.Core; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using StackExchange.Redis; using SOR.Database.Contexts; using SOR.Database.Entities.Identity; using SOR.Shared.Proto; using SOR.Shared.Redis; /// /// gRPC handler for the Auth service. /// /// Session lifecycle: /// - Tokens are 32 random bytes encoded as base64 (44 chars). /// - The raw token is returned to the client and stored in Redis with a TTL. /// - Only the SHA-256 hex hash is persisted in Postgres (AccountSession.TokenHash). /// - ValidateToken checks Redis first (O(1), no DB hit) and falls back to Postgres /// on cache miss (Redis eviction, restart) to re-populate Redis. /// - Logout deletes from both Redis and marks RevokedAt in Postgres. /// /// OAuth: /// - All four providers (Google/Steam/Apple/Microsoft) are stubbed and DISABLED. /// - Each is gated by a Redis feature flag (e.g. "feature:oauth_google_enabled"). /// - When credentials are configured and the flag set to "true", fill in the /// provider-specific token-validation logic in LoginWithOAuth. /// public sealed class AuthGrpcHandler : AuthService.AuthServiceBase { private readonly UserManager _userManager; private readonly SorIdentityDbContext _db; private readonly IConnectionMultiplexer _redis; private readonly ILogger _logger; public AuthGrpcHandler( UserManager userManager, SorIdentityDbContext db, IConnectionMultiplexer redis, ILogger logger) { _userManager = userManager; _db = db; _redis = redis; _logger = logger; } // ── Login ───────────────────────────────────────────────────────────────── public override async Task Login( LoginRequest request, ServerCallContext context) { var user = await _userManager.FindByEmailAsync(request.Email); if (user is null) return Fail(r => { r.ErrorCode = "USER_NOT_FOUND"; return r; }); // Lockout check (bans and brute-force lockouts share the same field). if (user.LockoutEnd.HasValue && user.LockoutEnd > DateTimeOffset.UtcNow) return Fail(r => { r.ErrorCode = "ACCOUNT_LOCKED"; return r; }); var valid = await _userManager.CheckPasswordAsync(user, request.Password); if (!valid) { await _userManager.AccessFailedAsync(user); return Fail(r => { r.ErrorCode = "INVALID_PASSWORD"; return r; }); } await _userManager.ResetAccessFailedCountAsync(user); user.LastLoginAt = DateTimeOffset.UtcNow; await _userManager.UpdateAsync(user); // Single-session policy: revoke all active sessions before issuing a new one. // This ensures only one device is logged in at a time. The old device will // receive an auth failure on its next auth.hello and return to the login screen. await RevokeAllSessionsForUserAsync(user.Id); var token = await CreateSessionAsync(user.Id, context); _logger.LogInformation("Login succeeded for account {AccountId}", user.Id); return new LoginResponse { Success = true, SessionToken = token, NeedsStarterDeck = !user.StarterDeckSelectedAt.HasValue, }; } // ── Register ────────────────────────────────────────────────────────────── public override async Task Register( RegisterRequest request, ServerCallContext context) { if (await _userManager.FindByEmailAsync(request.Email) is not null) return Fail(r => { r.ErrorCode = "EMAIL_TAKEN"; return r; }); if (await _userManager.Users.AnyAsync(u => u.DisplayName == request.DisplayName)) return Fail(r => { r.ErrorCode = "DISPLAY_NAME_TAKEN"; return r; }); var account = new Account { UserName = request.Email, Email = request.Email, DisplayName = request.DisplayName, CreatedAt = DateTimeOffset.UtcNow, LastLoginAt = DateTimeOffset.UtcNow, }; var result = await _userManager.CreateAsync(account, request.Password); if (!result.Succeeded) { var code = result.Errors.FirstOrDefault()?.Code ?? "REGISTRATION_FAILED"; _logger.LogWarning("Registration failed for {Email}: {Errors}", request.Email, string.Join(", ", result.Errors.Select(e => e.Code))); return Fail(r => { r.ErrorCode = code; return r; }); } var token = await CreateSessionAsync(account.Id, context); _logger.LogInformation("Registered new account {AccountId}", account.Id); return new RegisterResponse { Success = true, SessionToken = token, NeedsStarterDeck = true, // new accounts always need to select a starter deck }; } // ── ValidateToken ───────────────────────────────────────────────────────── public override async Task ValidateToken( ValidateTokenRequest request, ServerCallContext context) { if (string.IsNullOrWhiteSpace(request.SessionToken)) return new ValidateTokenResponse { Valid = false }; var cache = _redis.GetDatabase(); // Fast path: Redis stores accountId keyed by raw token with TTL. var cachedId = await cache.StringGetAsync(RedisKeys.Session(request.SessionToken)); if (!cachedId.IsNullOrEmpty && Guid.TryParse(cachedId, out var cachedAccountId)) { var cached = await _userManager.FindByIdAsync(cachedAccountId.ToString()); if (cached is not null) return new ValidateTokenResponse { Valid = true, UserId = cached.Id.ToString(), DisplayName = cached.DisplayName ?? string.Empty, NeedsStarterDeck = !cached.StarterDeckSelectedAt.HasValue, }; } // Slow path: Redis miss (eviction / restart). Verify in Postgres. var hash = ComputeHash(request.SessionToken); var now = DateTimeOffset.UtcNow; var session = await _db.AccountSessions .FirstOrDefaultAsync(s => s.TokenHash == hash && s.RevokedAt == null && s.ExpiresAt > now); if (session is null) return new ValidateTokenResponse { Valid = false }; var account = await _userManager.FindByIdAsync(session.AccountId.ToString()); if (account is null) return new ValidateTokenResponse { Valid = false }; // Re-populate Redis so the next call hits the fast path. var ttl = session.ExpiresAt - now; await cache.StringSetAsync( RedisKeys.Session(request.SessionToken), account.Id.ToString(), ttl > TimeSpan.Zero ? ttl : TimeSpan.FromMinutes(1)); return new ValidateTokenResponse { Valid = true, UserId = account.Id.ToString(), DisplayName = account.DisplayName ?? string.Empty, NeedsStarterDeck = !account.StarterDeckSelectedAt.HasValue, }; } // ── Logout ──────────────────────────────────────────────────────────────── public override async Task Logout( LogoutRequest request, ServerCallContext context) { if (!string.IsNullOrWhiteSpace(request.SessionToken)) { var hash = ComputeHash(request.SessionToken); var session = await _db.AccountSessions .FirstOrDefaultAsync(s => s.TokenHash == hash && s.RevokedAt == null); if (session is not null) { session.RevokedAt = DateTimeOffset.UtcNow; await _db.SaveChangesAsync(); var cache2 = _redis.GetDatabase(); await cache2.SetRemoveAsync( RedisKeys.UserSessions(session.AccountId.ToString()), request.SessionToken); } await _redis.GetDatabase().KeyDeleteAsync(RedisKeys.Session(request.SessionToken)); } return new LogoutResponse(); } // ── RevokeAllSessions ───────────────────────────────────────────────────── public override async Task RevokeAllSessions( RevokeAllSessionsRequest request, ServerCallContext context) { if (!Guid.TryParse(request.AccountId, out var accountId)) return new RevokeAllSessionsResponse { SessionsRevoked = 0 }; var now = DateTimeOffset.UtcNow; var cache = _redis.GetDatabase(); var userKey = RedisKeys.UserSessions(accountId.ToString()); // Grab all raw tokens from the Redis SET, then delete each session key. var members = await cache.SetMembersAsync(userKey); foreach (var member in members) await cache.KeyDeleteAsync(RedisKeys.Session(member!)); await cache.KeyDeleteAsync(userKey); // Revoke all active Postgres sessions for this account. var sessions = await _db.AccountSessions .Where(s => s.AccountId == accountId && s.RevokedAt == null && s.ExpiresAt > now) .ToListAsync(); foreach (var s in sessions) s.RevokedAt = now; await _db.SaveChangesAsync(); _logger.LogInformation("Revoked {Count} sessions for account {AccountId}", sessions.Count, accountId); return new RevokeAllSessionsResponse { SessionsRevoked = sessions.Count }; } // ── Account Properties ──────────────────────────────────────────────────── public override async Task GetAccountProperty( GetAccountPropertyRequest request, ServerCallContext context) { if (!Guid.TryParse(request.AccountId, out var accountId)) return new GetAccountPropertyResponse { Found = false }; var prop = await _db.AccountProperties .FirstOrDefaultAsync(p => p.AccountId == accountId && p.Key == request.Key); return prop is null ? new GetAccountPropertyResponse { Found = false } : new GetAccountPropertyResponse { Found = true, Value = prop.Value }; } public override async Task SetAccountProperty( SetAccountPropertyRequest request, ServerCallContext context) { if (!Guid.TryParse(request.AccountId, out var accountId)) return new SetAccountPropertyResponse { Success = false }; var now = DateTimeOffset.UtcNow; var existing = await _db.AccountProperties .FirstOrDefaultAsync(p => p.AccountId == accountId && p.Key == request.Key); if (existing is not null) { existing.Value = request.Value; existing.UpdatedAt = now; } else { _db.AccountProperties.Add(new AccountProperty { Id = Guid.NewGuid(), AccountId = accountId, Key = request.Key, Value = request.Value, CreatedAt = now, UpdatedAt = now, }); } await _db.SaveChangesAsync(); return new SetAccountPropertyResponse { Success = true }; } public override async Task DeleteAccountProperty( DeleteAccountPropertyRequest request, ServerCallContext context) { if (!Guid.TryParse(request.AccountId, out var accountId)) return new DeleteAccountPropertyResponse { Success = false }; var prop = await _db.AccountProperties .FirstOrDefaultAsync(p => p.AccountId == accountId && p.Key == request.Key); if (prop is not null) { _db.AccountProperties.Remove(prop); await _db.SaveChangesAsync(); } return new DeleteAccountPropertyResponse { Success = true }; } public override async Task ListAccountProperties( ListAccountPropertiesRequest request, ServerCallContext context) { if (!Guid.TryParse(request.AccountId, out var accountId)) return new ListAccountPropertiesResponse(); var props = await _db.AccountProperties .Where(p => p.AccountId == accountId) .OrderBy(p => p.Key) .Select(p => new AccountPropertyEntry { Key = p.Key, Value = p.Value }) .ToListAsync(); var response = new ListAccountPropertiesResponse(); response.Properties.AddRange(props); return response; } // ── OAuth (disabled — feature-flagged) ──────────────────────────────────── public override async Task LoginWithOAuth( OAuthLoginRequest request, ServerCallContext context) { var providerName = request.Provider.ToString().ToLowerInvariant(); var flagKey = RedisKeys.FeatureFlag($"oauth_{providerName}_enabled"); var flagValue = await _redis.GetDatabase().StringGetAsync(flagKey); if (flagValue != "true") { _logger.LogDebug("OAuth login rejected — provider {Provider} feature flag not set", request.Provider); return new OAuthLoginResponse { Success = false, ErrorCode = "FEATURE_DISABLED" }; } // TODO: implement per-provider token validation when credentials are configured. // Google: validate id_token with Google's tokeninfo endpoint or JWKS // Steam: OpenID 2.0 response validation // Apple: validate id_token with Apple's JWKS // Microsoft: validate id_token with Azure AD JWKS // After validation: find or create Account with external login link, // then call CreateSessionAsync and return the token. return new OAuthLoginResponse { Success = false, ErrorCode = "FEATURE_DISABLED" }; } // ── Helpers ─────────────────────────────────────────────────────────────── /// /// Revokes all active sessions for the given account in both Redis and Postgres. /// Called before issuing a new session token so only one device is ever logged in. /// private async Task RevokeAllSessionsForUserAsync(Guid accountId) { var now = DateTimeOffset.UtcNow; var cache = _redis.GetDatabase(); var userKey = RedisKeys.UserSessions(accountId.ToString()); var members = await cache.SetMembersAsync(userKey); foreach (var member in members) await cache.KeyDeleteAsync(RedisKeys.Session(member!)); await cache.KeyDeleteAsync(userKey); var sessions = await _db.AccountSessions .Where(s => s.AccountId == accountId && s.RevokedAt == null && s.ExpiresAt > now) .ToListAsync(); foreach (var s in sessions) s.RevokedAt = now; if (sessions.Count > 0) { await _db.SaveChangesAsync(); _logger.LogInformation( "Revoked {Count} existing session(s) for account {AccountId} on new login", sessions.Count, accountId); } } /// /// Generates a cryptographically random session token, persists the hash to Postgres, /// and caches the raw token → accountId mapping in Redis. /// private async Task CreateSessionAsync(Guid accountId, ServerCallContext context) { var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); var hash = ComputeHash(token); var expiry = DateTimeOffset.UtcNow.AddDays(30); var http = context.GetHttpContext(); _db.AccountSessions.Add(new AccountSession { Id = Guid.NewGuid(), AccountId = accountId, TokenHash = hash, CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = expiry, IpAddress = http.Connection.RemoteIpAddress?.ToString(), UserAgent = http.Request.Headers.UserAgent.ToString(), }); await _db.SaveChangesAsync(); var ttl = expiry - DateTimeOffset.UtcNow; var cache = _redis.GetDatabase(); await cache.StringSetAsync(RedisKeys.Session(token), accountId.ToString(), ttl); await cache.SetAddAsync(RedisKeys.UserSessions(accountId.ToString()), token); return token; } private static string ComputeHash(string token) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token)); return Convert.ToHexString(bytes).ToLowerInvariant(); } /// Helper to build a failed response with an error code. private static T Fail(Func configure) where T : new() => configure(new T()); }