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());
}
+4 -2
View File
@@ -6,10 +6,12 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<!-- Grpc.AspNetCore provides the server base classes (AuthService.AuthServiceBase)
that the handler inherits from. -->
<PackageReference Include="Grpc.AspNetCore" />
<!-- IConnectionMultiplexer for Redis-backed session store (fast token validation) -->
<PackageReference Include="StackExchange.Redis" />
<!-- DB entities, DbContexts, and Identity EF stores -->
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
<ProjectReference Include="..\SOR.Shared.Proto\SOR.Shared.Proto.csproj" />
</ItemGroup>
+25 -16
View File
@@ -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;
/// <summary>
/// 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".
/// </summary>
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<AuthGrpcHandler>.
services.AddGrpc();
// TODO (when implementing Auth business logic):
// services.Configure<AuthOptions>(configuration.GetSection("Auth"));
// services.AddDbContext<AuthDbContext>(opts => opts.UseNpgsql(...));
// services.AddScoped<IAuthRepository, AuthRepository>();
// services.AddScoped<IAuthService, AuthService>();
// Identity DbContext (identity schema: accounts, sessions, properties, roles…)
services.AddIdentityDatabase(configuration);
// ASP.NET Core Identity: UserManager<Account>, password hashing, lockout, etc.
// SignInManager is not needed here — gRPC handlers validate credentials directly.
services.AddIdentityCore<Account>(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<IdentityRole<Guid>>()
.AddEntityFrameworkStores<SorIdentityDbContext>()
.AddDefaultTokenProviders();
return services;
}
@@ -25,6 +25,7 @@ public sealed class SorIdentityDbContext
: base(options) { }
public DbSet<AccountSession> AccountSessions => Set<AccountSession>();
public DbSet<AccountProperty> AccountProperties => Set<AccountProperty>();
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<AccountProperty>(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);
});
}
}
@@ -0,0 +1,27 @@
namespace SOR.Database.Entities.Identity;
/// <summary>
/// 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.
/// </summary>
public sealed class AccountProperty
{
public Guid Id { get; set; }
/// <summary>Bare Guid reference — no EF navigation to Account (same schema, but simpler).</summary>
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; }
}
@@ -0,0 +1,365 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<System.Guid>", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("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<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("role_claims", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("account_claims", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("external_logins", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("account_roles", "identity");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("account_tokens", "identity");
});
modelBuilder.Entity("SOR.Database.Entities.Identity.Account", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("AvatarCdnUrl")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DeviceId")
.HasColumnType("text");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("IpAddress")
.HasColumnType("text");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("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<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", 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<System.Guid>", b =>
{
b.HasOne("SOR.Database.Entities.Identity.Account", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,53 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Identity
{
/// <inheritdoc />
public partial class AddAccountProperties : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "account_properties",
schema: "identity",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
AccountId = table.Column<Guid>(type: "uuid", nullable: false),
Key = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(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);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "account_properties",
schema: "identity");
}
}
}
@@ -232,6 +232,39 @@ namespace SOR.Database.Migrations.Identity
b.ToTable("accounts", "identity");
});
modelBuilder.Entity("SOR.Database.Entities.Identity.AccountProperty", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Key")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("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<Guid>("Id")
+2 -1
View File
@@ -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"
+92 -35
View File
@@ -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);
}