Implement Auth service — login, register, sessions, account properties, OAuth stubs

- auth.proto: add account property CRUD messages + OAuthProvider enum + LoginWithOAuth
  (all OAuth providers disabled via Redis feature flags: oauth_<provider>_enabled)
- SOR.Auth: full AuthGrpcHandler — password auth, session tokens (32-byte random,
  SHA-256 hash in Postgres, raw token in Redis with TTL), ValidateToken with
  Redis fast-path + Postgres slow-path fallback, Logout with dual revocation
- AccountProperty entity: flexible key-value bag per account (snake_case keys,
  string values); upsert semantics; indexed on (AccountId, Key)
- SOR.Auth/ServiceRegistration: registers Identity DbContext + UserManager + roles
- SOR.Host/appsettings.json: add Postgres Default connection string
- AddAccountProperties migration applied to pg-forge-01

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-25 08:07:19 -05:00
co-authored by Claude Happy
parent 6f9ed0668f
commit 1974dffdb6
10 changed files with 923 additions and 122 deletions
+312 -68
View File
@@ -1,98 +1,342 @@
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;
/// <summary>
/// gRPC handler stub for the Auth service.
/// gRPC handler for the Auth service.
///
/// STATUS: Foundation stub only. All methods return placeholder responses.
/// Real business logic (database, password hashing, session management)
/// will be implemented when the Auth service is built out.
/// 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.
///
/// This stub is sufficient for the networking foundation phase:
/// - The Gateway calls ValidateToken — this returns Valid=false for all tokens,
/// meaning no connections will authenticate until the real implementation is in place.
/// - The project compiles and the gRPC route is registered correctly.
///
/// When implementing for real:
/// 1. Add IAuthService injection to the constructor
/// 2. Replace each return statement with the actual service call
/// 3. Map ServiceResult{T} to the Protobuf response message
/// 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.
/// </summary>
public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
{
private readonly UserManager<Account> _userManager;
private readonly SorIdentityDbContext _db;
private readonly IConnectionMultiplexer _redis;
private readonly ILogger<AuthGrpcHandler> _logger;
public AuthGrpcHandler(ILogger<AuthGrpcHandler> logger)
public AuthGrpcHandler(
UserManager<Account> userManager,
SorIdentityDbContext db,
IConnectionMultiplexer redis,
ILogger<AuthGrpcHandler> logger)
{
_logger = logger;
_userManager = userManager;
_db = db;
_redis = redis;
_logger = logger;
}
/// <summary>
/// Validates a session token.
/// STUB: always returns Valid=false until real implementation is added.
/// </summary>
public override Task<ValidateTokenResponse> ValidateToken(
ValidateTokenRequest request,
ServerCallContext context)
{
_logger.LogDebug("ValidateToken called (stub) for token length={Length}",
request.SessionToken.Length);
// ── Login ─────────────────────────────────────────────────────────────────
// STUB: return invalid until real Auth business logic is implemented.
return Task.FromResult(new ValidateTokenResponse
public override async Task<LoginResponse> Login(
LoginRequest request, ServerCallContext context)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
return Fail<LoginResponse>(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<LoginResponse>(r => { r.ErrorCode = "ACCOUNT_LOCKED"; return r; });
var valid = await _userManager.CheckPasswordAsync(user, request.Password);
if (!valid)
{
Valid = false,
UserId = string.Empty,
DisplayName = string.Empty
});
await _userManager.AccessFailedAsync(user);
return Fail<LoginResponse>(r => { r.ErrorCode = "INVALID_PASSWORD"; return r; });
}
await _userManager.ResetAccessFailedCountAsync(user);
user.LastLoginAt = DateTimeOffset.UtcNow;
await _userManager.UpdateAsync(user);
var token = await CreateSessionAsync(user.Id, context);
_logger.LogInformation("Login succeeded for account {AccountId}", user.Id);
return new LoginResponse { Success = true, SessionToken = token };
}
/// <summary>
/// Authenticates a user with email + password.
/// STUB: always returns failure.
/// </summary>
public override Task<LoginResponse> Login(
LoginRequest request,
ServerCallContext context)
{
_logger.LogDebug("Login called (stub) for email={Email}", request.Email);
// ── Register ──────────────────────────────────────────────────────────────
return Task.FromResult(new LoginResponse
public override async Task<RegisterResponse> Register(
RegisterRequest request, ServerCallContext context)
{
if (await _userManager.FindByEmailAsync(request.Email) is not null)
return Fail<RegisterResponse>(r => { r.ErrorCode = "EMAIL_TAKEN"; return r; });
if (await _userManager.Users.AnyAsync(u => u.DisplayName == request.DisplayName))
return Fail<RegisterResponse>(r => { r.ErrorCode = "DISPLAY_NAME_TAKEN"; return r; });
var account = new Account
{
Success = false,
ErrorCode = "NOT_IMPLEMENTED"
});
}
UserName = request.Email,
Email = request.Email,
DisplayName = request.DisplayName,
CreatedAt = DateTimeOffset.UtcNow,
LastLoginAt = DateTimeOffset.UtcNow,
};
/// <summary>
/// Registers a new user account.
/// STUB: always returns failure.
/// </summary>
public override Task<RegisterResponse> Register(
RegisterRequest request,
ServerCallContext context)
{
_logger.LogDebug("Register called (stub)");
return Task.FromResult(new RegisterResponse
var result = await _userManager.CreateAsync(account, request.Password);
if (!result.Succeeded)
{
Success = false,
ErrorCode = "NOT_IMPLEMENTED"
});
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<RegisterResponse>(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 };
}
/// <summary>
/// Revokes a session token.
/// STUB: no-op (returns success — revocation of non-existent tokens is idempotent).
/// </summary>
public override Task<LogoutResponse> Logout(
LogoutRequest request,
ServerCallContext context)
// ── ValidateToken ─────────────────────────────────────────────────────────
public override async Task<ValidateTokenResponse> ValidateToken(
ValidateTokenRequest request, ServerCallContext context)
{
_logger.LogDebug("Logout called (stub)");
return Task.FromResult(new LogoutResponse());
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,
};
}
// 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,
};
}
// ── Logout ────────────────────────────────────────────────────────────────
public override async Task<LogoutResponse> 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();
}
await _redis.GetDatabase().KeyDeleteAsync(RedisKeys.Session(request.SessionToken));
}
return new LogoutResponse();
}
// ── Account Properties ────────────────────────────────────────────────────
public override async Task<GetAccountPropertyResponse> 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<SetAccountPropertyResponse> 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<DeleteAccountPropertyResponse> 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<ListAccountPropertiesResponse> 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<OAuthLoginResponse> 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 ───────────────────────────────────────────────────────────────
/// <summary>
/// Generates a cryptographically random session token, persists the hash to Postgres,
/// and caches the raw token → accountId mapping in Redis.
/// </summary>
private async Task<string> 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();
await _redis.GetDatabase().StringSetAsync(
RedisKeys.Session(token),
accountId.ToString(),
expiry - DateTimeOffset.UtcNow);
return token;
}
private static string ComputeHash(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
/// <summary>Helper to build a failed response with an error code.</summary>
private static T Fail<T>(Func<T, T> configure) where T : new()
=> configure(new T());
}