diff --git a/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs index 82ad288..177a2db 100644 --- a/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs +++ b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs @@ -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; /// -/// 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. /// public sealed class AuthGrpcHandler : AuthService.AuthServiceBase { + private readonly UserManager _userManager; + private readonly SorIdentityDbContext _db; + private readonly IConnectionMultiplexer _redis; private readonly ILogger _logger; - public AuthGrpcHandler(ILogger logger) + public AuthGrpcHandler( + UserManager userManager, + SorIdentityDbContext db, + IConnectionMultiplexer redis, + ILogger logger) { - _logger = logger; + _userManager = userManager; + _db = db; + _redis = redis; + _logger = logger; } - /// - /// Validates a session token. - /// STUB: always returns Valid=false until real implementation is added. - /// - public override Task 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 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) { - Valid = false, - UserId = string.Empty, - DisplayName = string.Empty - }); + 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); + + var token = await CreateSessionAsync(user.Id, context); + _logger.LogInformation("Login succeeded for account {AccountId}", user.Id); + return new LoginResponse { Success = true, SessionToken = token }; } - /// - /// Authenticates a user with email + password. - /// STUB: always returns failure. - /// - public override Task 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 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 { - Success = false, - ErrorCode = "NOT_IMPLEMENTED" - }); - } + UserName = request.Email, + Email = request.Email, + DisplayName = request.DisplayName, + CreatedAt = DateTimeOffset.UtcNow, + LastLoginAt = DateTimeOffset.UtcNow, + }; - /// - /// Registers a new user account. - /// STUB: always returns failure. - /// - public override Task 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(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 }; } - /// - /// Revokes a session token. - /// STUB: no-op (returns success — revocation of non-existent tokens is idempotent). - /// - public override Task Logout( - LogoutRequest request, - ServerCallContext context) + // ── ValidateToken ───────────────────────────────────────────────────────── + + public override async Task 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 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 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 ─────────────────────────────────────────────────────────────── + + /// + /// 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(); + + 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(); + } + + /// Helper to build a failed response with an error code. + private static T Fail(Func configure) where T : new() + => configure(new T()); } diff --git a/Server/src/SOR.Auth/SOR.Auth.csproj b/Server/src/SOR.Auth/SOR.Auth.csproj index 97acd00..d256124 100644 --- a/Server/src/SOR.Auth/SOR.Auth.csproj +++ b/Server/src/SOR.Auth/SOR.Auth.csproj @@ -6,10 +6,12 @@ - + + + + diff --git a/Server/src/SOR.Auth/ServiceRegistration.cs b/Server/src/SOR.Auth/ServiceRegistration.cs index 3caf789..af2ce08 100644 --- a/Server/src/SOR.Auth/ServiceRegistration.cs +++ b/Server/src/SOR.Auth/ServiceRegistration.cs @@ -1,17 +1,15 @@ namespace SOR.Auth; +using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using SOR.Database; +using SOR.Database.Contexts; +using SOR.Database.Entities.Identity; /// -/// Registers Auth service dependencies in the DI container. -/// -/// STATUS: Foundation stub only. -/// Real registration (DbContext, repositories, IAuthService) will be added -/// when Auth business logic is implemented. -/// -/// Currently only registers the gRPC infrastructure so the handler can be -/// mapped in SOR.Host.Program.cs via app.MapGrpcService{AuthGrpcHandler}(). +/// Registers all Auth service dependencies in the DI container. +/// Called from SOR.Host/Program.cs when ENABLED_SERVICES contains "auth". /// public static class ServiceRegistration { @@ -19,16 +17,27 @@ public static class ServiceRegistration this IServiceCollection services, IConfiguration configuration) { - // AddGrpc() registers the gRPC server infrastructure in ASP.NET Core. - // Required before MapGrpcService{T} can be called in Program.cs. - // Safe to call multiple times — ASP.NET Core deduplicates registrations. + // gRPC server infrastructure — required before MapGrpcService. services.AddGrpc(); - // TODO (when implementing Auth business logic): - // services.Configure(configuration.GetSection("Auth")); - // services.AddDbContext(opts => opts.UseNpgsql(...)); - // services.AddScoped(); - // services.AddScoped(); + // Identity DbContext (identity schema: accounts, sessions, properties, roles…) + services.AddIdentityDatabase(configuration); + + // ASP.NET Core Identity: UserManager, password hashing, lockout, etc. + // SignInManager is not needed here — gRPC handlers validate credentials directly. + services.AddIdentityCore(options => + { + options.Password.RequireDigit = true; + options.Password.RequireUppercase = true; + options.Password.RequireNonAlphanumeric = true; + options.Password.RequiredLength = 12; + options.Lockout.MaxFailedAccessAttempts = 5; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15); + options.Lockout.AllowedForNewUsers = true; + }) + .AddRoles>() + .AddEntityFrameworkStores() + .AddDefaultTokenProviders(); return services; } diff --git a/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs b/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs index ff552b4..70904f6 100644 --- a/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs +++ b/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs @@ -25,6 +25,7 @@ public sealed class SorIdentityDbContext : base(options) { } public DbSet AccountSessions => Set(); + public DbSet AccountProperties => Set(); protected override void OnModelCreating(ModelBuilder builder) { @@ -56,5 +57,14 @@ public sealed class SorIdentityDbContext // Compound index: find all active sessions for an account quickly. e.HasIndex(s => new { s.AccountId, s.ExpiresAt }); }); + + builder.Entity(e => + { + e.ToTable("account_properties"); + e.HasKey(p => p.Id); + // (AccountId, Key) pair is unique — one value per key per account. + e.HasIndex(p => new { p.AccountId, p.Key }).IsUnique(); + e.HasIndex(p => p.AccountId); + }); } } diff --git a/Server/src/SOR.Database/Entities/Identity/AccountProperty.cs b/Server/src/SOR.Database/Entities/Identity/AccountProperty.cs new file mode 100644 index 0000000..f0a8f4a --- /dev/null +++ b/Server/src/SOR.Database/Entities/Identity/AccountProperty.cs @@ -0,0 +1,27 @@ +namespace SOR.Database.Entities.Identity; + +/// +/// A flexible key-value property bag attached to an account. +/// Use for lightweight per-player flags, preferences, and metadata that do not +/// warrant a dedicated column — e.g. tutorial progress, notification prefs, +/// experimental feature opt-ins, admin notes. +/// +/// Cross-cutting conventions: +/// - Key: lowercase, snake_case (e.g. "tutorial_completed", "beta_tester") +/// - Value: stored as string; caller interprets type (bool → "true"/"false", +/// int → decimal string, JSON → serialized object) +/// - Unique index on (AccountId, Key) enforced at DB + EF level. +/// +public sealed class AccountProperty +{ + public Guid Id { get; set; } + + /// Bare Guid reference — no EF navigation to Account (same schema, but simpler). + public Guid AccountId { get; set; } + + public string Key { get; set; } = string.Empty; + public string Value { get; set; } = string.Empty; + + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } +} diff --git a/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.Designer.cs b/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.Designer.cs new file mode 100644 index 0000000..539fc64 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.Designer.cs @@ -0,0 +1,365 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SOR.Database.Contexts; + +#nullable disable + +namespace SOR.Database.Migrations.Identity +{ + [DbContext(typeof(SorIdentityDbContext))] + [Migration("20260225130654_AddAccountProperties")] + partial class AddAccountProperties + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("identity") + .HasAnnotation("ProductVersion", "8.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("account_claims", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("external_logins", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("account_roles", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("account_tokens", "identity"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Identity.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("AvatarCdnUrl") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LastLoginAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("DisplayName"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("accounts", "identity"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Identity.AccountProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("AccountId", "Key") + .IsUnique(); + + b.ToTable("account_properties", "identity"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Identity.AccountSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceId") + .HasColumnType("text"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IpAddress") + .HasColumnType("text"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserAgent") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("AccountId", "ExpiresAt"); + + b.ToTable("account_sessions", "identity"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("SOR.Database.Entities.Identity.Account", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("SOR.Database.Entities.Identity.Account", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SOR.Database.Entities.Identity.Account", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("SOR.Database.Entities.Identity.Account", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.cs b/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.cs new file mode 100644 index 0000000..9528fc5 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Identity/20260225130654_AddAccountProperties.cs @@ -0,0 +1,53 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Identity +{ + /// + public partial class AddAccountProperties : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "account_properties", + schema: "identity", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + AccountId = table.Column(type: "uuid", nullable: false), + Key = table.Column(type: "text", nullable: false), + Value = table.Column(type: "text", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_account_properties", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_account_properties_AccountId", + schema: "identity", + table: "account_properties", + column: "AccountId"); + + migrationBuilder.CreateIndex( + name: "IX_account_properties_AccountId_Key", + schema: "identity", + table: "account_properties", + columns: new[] { "AccountId", "Key" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "account_properties", + schema: "identity"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Identity/SorIdentityDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Identity/SorIdentityDbContextModelSnapshot.cs index bb5fb13..c48fd74 100644 --- a/Server/src/SOR.Database/Migrations/Identity/SorIdentityDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Identity/SorIdentityDbContextModelSnapshot.cs @@ -232,6 +232,39 @@ namespace SOR.Database.Migrations.Identity b.ToTable("accounts", "identity"); }); + modelBuilder.Entity("SOR.Database.Entities.Identity.AccountProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("AccountId", "Key") + .IsUnique(); + + b.ToTable("account_properties", "identity"); + }); + modelBuilder.Entity("SOR.Database.Entities.Identity.AccountSession", b => { b.Property("Id") diff --git a/Server/src/SOR.Host/appsettings.json b/Server/src/SOR.Host/appsettings.json index 19e392b..18cf0ce 100644 --- a/Server/src/SOR.Host/appsettings.json +++ b/Server/src/SOR.Host/appsettings.json @@ -1,6 +1,7 @@ { "ConnectionStrings": { - "Redis": "localhost:6379" + "Redis": "localhost:6379", + "Default": "Host=172.10.1.127;Port=5432;Database=sor;Username=SOR-DBA;Password=G073gxq7VtQaOfnITcxDh3bsibcipe6D" }, "Nats": { "Url": "nats://localhost:4222" diff --git a/Server/src/SOR.Shared.Proto/Protos/auth.proto b/Server/src/SOR.Shared.Proto/Protos/auth.proto index 716779a..7525493 100644 --- a/Server/src/SOR.Shared.Proto/Protos/auth.proto +++ b/Server/src/SOR.Shared.Proto/Protos/auth.proto @@ -1,26 +1,9 @@ -// Protobuf language version 3 — the current standard. -// proto3 differences from proto2: all fields optional by default, -// no required fields, simpler default values. syntax = "proto3"; -// The C# namespace for all generated types from this file. -// Generated classes: AuthService.AuthServiceBase (server), AuthService.AuthServiceClient (client), -// LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse, etc. option csharp_namespace = "SOR.Shared.Proto"; -// Package prevents naming collisions with other .proto files. -// Does not affect the C# namespace (that's controlled by csharp_namespace above). package sor.auth; -// ── Request / Response Messages ─────────────────────────────────────────────── -// -// A 'message' is a structured data type. It compiles to a C# class with properties. -// Each field has: -// type — the data type (string, int32, bool, or another message) -// name — the property name in the generated C# code -// number — the field number used in binary encoding (NEVER change these; -// changing a field number is a breaking change in binary format) - // ── Login ───────────────────────────────────────────────────────────────────── message LoginRequest { @@ -30,25 +13,19 @@ message LoginRequest { message LoginResponse { bool success = 1; - - // Only populated on success. Empty string ("") on failure. string session_token = 2; - - // Only populated on failure. Examples: "USER_NOT_FOUND", "INVALID_PASSWORD", "ACCOUNT_BANNED" + // Failure codes: USER_NOT_FOUND | INVALID_PASSWORD | ACCOUNT_BANNED | ACCOUNT_LOCKED string error_code = 3; } // ── Token Validation ────────────────────────────────────────────────────────── -// Used by Gateway during the auth handshake to validate session tokens. -// Also used by other services that need to verify caller identity. message ValidateTokenRequest { string session_token = 1; } message ValidateTokenResponse { bool valid = 1; - // Only populated when valid = true. string user_id = 2; string display_name = 3; @@ -64,8 +41,9 @@ message RegisterRequest { message RegisterResponse { bool success = 1; - string session_token = 2; // Set on success — user is automatically logged in - string error_code = 3; // e.g., "EMAIL_TAKEN", "DISPLAY_NAME_TAKEN", "WEAK_PASSWORD" + string session_token = 2; + // Failure codes: EMAIL_TAKEN | DISPLAY_NAME_TAKEN | WEAK_PASSWORD | REGISTRATION_FAILED + string error_code = 3; } // ── Logout ──────────────────────────────────────────────────────────────────── @@ -74,25 +52,104 @@ message LogoutRequest { string session_token = 1; } -// Empty response — logout always succeeds (idempotent; revoking a non-existent token is fine) +// Empty response — logout always succeeds (idempotent; revoking a non-existent token is fine). message LogoutResponse {} +// ── Account Properties ──────────────────────────────────────────────────────── +// Flexible key-value bag per account. +// Keys are snake_case strings; values are always strings (caller interprets type). +// Examples: "tutorial_completed" → "true", "selected_language" → "en", "beta_flags" → "[]" + +message GetAccountPropertyRequest { + string account_id = 1; + string key = 2; +} + +message GetAccountPropertyResponse { + bool found = 1; + string value = 2; +} + +message SetAccountPropertyRequest { + string account_id = 1; + string key = 2; + string value = 3; +} + +message SetAccountPropertyResponse { + bool success = 1; +} + +message DeleteAccountPropertyRequest { + string account_id = 1; + string key = 2; +} + +message DeleteAccountPropertyResponse { + bool success = 1; +} + +message ListAccountPropertiesRequest { + string account_id = 1; +} + +message AccountPropertyEntry { + string key = 1; + string value = 2; +} + +message ListAccountPropertiesResponse { + repeated AccountPropertyEntry properties = 1; +} + +// ── OAuth ───────────────────────────────────────────────────────────────────── +// All providers are DISABLED by default, gated by Redis feature flags: +// oauth_google_enabled | oauth_steam_enabled | oauth_apple_enabled | oauth_microsoft_enabled +// Returns FEATURE_DISABLED until the flag is set to "true" in Redis. +// Provider credentials (client_id, client_secret) live in appsettings / k8s secrets. + +enum OAuthProvider { + OAUTH_PROVIDER_UNSPECIFIED = 0; + GOOGLE = 1; + STEAM = 2; + APPLE = 3; + MICROSOFT = 4; +} + +message OAuthLoginRequest { + OAuthProvider provider = 1; + // Provider-issued access token or id_token, depending on provider flow. + string oauth_token = 2; +} + +message OAuthLoginResponse { + bool success = 1; + string session_token = 2; + // Failure codes: FEATURE_DISABLED | INVALID_TOKEN | ACCOUNT_NOT_LINKED | PROVIDER_ERROR + string error_code = 3; +} + // ── Service Definition ──────────────────────────────────────────────────────── -// -// 'service' defines the RPC methods. The Protobuf compiler generates: -// - AuthService.AuthServiceBase: abstract base class for the server handler to inherit -// - AuthService.AuthServiceClient: client stub for other services to call Auth service AuthService { - // Primary login with email + password + // Primary login with email + password. rpc Login(LoginRequest) returns (LoginResponse); - // Validate an opaque session token (called by Gateway on every connection) + // Validate an opaque session token (called by Gateway on every connection). rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse); - // Create a new account + // Create a new account (automatically logged in on success). rpc Register(RegisterRequest) returns (RegisterResponse); - // Revoke a session token (called on explicit logout or ban) + // Revoke a session token (idempotent — revoking a non-existent token is fine). rpc Logout(LogoutRequest) returns (LogoutResponse); + + // Per-account key-value property bag. + rpc GetAccountProperty(GetAccountPropertyRequest) returns (GetAccountPropertyResponse); + rpc SetAccountProperty(SetAccountPropertyRequest) returns (SetAccountPropertyResponse); + rpc DeleteAccountProperty(DeleteAccountPropertyRequest) returns (DeleteAccountPropertyResponse); + rpc ListAccountProperties(ListAccountPropertiesRequest) returns (ListAccountPropertiesResponse); + + // OAuth login — disabled until provider credentials are configured and Redis flag is set. + rpc LoginWithOAuth(OAuthLoginRequest) returns (OAuthLoginResponse); }