backend phase 2: identity — phone-OTP auth, sessions & roles (REST)

- six REST endpoints (auth/request_otp, verify_otp, refresh, logout, me,
  me/select_role) wrapping the existing JWE/TOTP/RBAC engine
- usr.UserSessions with refresh-token rotation + stolen-token (replay)
  detection → revoke-all + 401; logout rotates the security stamp
- users extended: gender, national_id (enc, NULL until KYC),
  shahkar_verified_at (auto-reset on phone change), phone_hash UNIQUE,
  is_active, deleted_at + soft-delete filter; phone/email/national_id
  encrypted at rest via IFieldEncryptor value converter
- user_roles grant/revoke audit trail + global revoked filter; 7 roles
  seeded; admin sub-roles never self-assignable (403)
- ISmsSender seam (mock logs the OTP code) replaces the TODO log lines
- OperationResult/BaseController learned enveloped 401/403
- auth knobs as platform_configs rows (resend/attempts/session TTL)
- migration IdentitySessionsAndUserExtensions applied to the dev DB
- 24 new tests incl. Baya.Test.Api (WebApplicationFactory over SQLite);
  47 total green, zero new build warnings; swagger snapshot + contract
  (identity-auth.md), handoff, report, mocks-registry updated

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
hamid
2026-07-02 02:34:11 +03:30
parent 94fdcbe0d1
commit 3a51305343
88 changed files with 4619 additions and 91 deletions
@@ -0,0 +1,50 @@
using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Application.Features.Identity.Commands.Logout;
using Baya.Application.Features.Identity.Commands.RefreshToken;
using Baya.Application.Features.Identity.Commands.RequestOtp;
using Baya.Application.Features.Identity.Commands.VerifyOtp;
using Baya.Application.Models.Identity;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Baya.WebFramework.ServiceConfiguration;
using Baya.WebFramework.Swagger;
using Mediator;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Baya.Web.Api.Controllers.V1;
[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Display(Description = "Phone-OTP login, refresh-token rotation and logout")]
public sealed class AuthController(ISender sender) : BaseController
{
[HttpPost("[action]")]
[EnableRateLimiting(RateLimitingServiceExtension.OtpPolicy)]
[ProducesOkApiResponseType<RequestOtpResult>]
public async Task<IActionResult> RequestOtp(RequestOtpCommand command, CancellationToken cancellationToken)
=> OperationResult(await sender.Send(command, cancellationToken));
[HttpPost("[action]")]
[EnableRateLimiting(RateLimitingServiceExtension.OtpPolicy)]
[ProducesOkApiResponseType<AuthTokensResult>]
public async Task<IActionResult> VerifyOtp(VerifyOtpCommand command, CancellationToken cancellationToken)
=> OperationResult(await sender.Send(command, cancellationToken));
// Runs without a valid access token — the refresh token itself is the credential.
[HttpPost("[action]")]
[EnableRateLimiting(RateLimitingServiceExtension.AuthPolicy)]
[RequireTokenWithoutAuthorization]
[ProducesOkApiResponseType<AuthTokensResult>]
public async Task<IActionResult> Refresh(RefreshTokenCommand command, CancellationToken cancellationToken)
=> OperationResult(await sender.Send(command, cancellationToken));
[HttpPost("[action]")]
[Authorize]
[ProducesOkApiResponseType]
public async Task<IActionResult> Logout(LogoutCommand command, CancellationToken cancellationToken)
=> OperationResult(await sender.Send(command, cancellationToken));
}
@@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Application.Features.Identity.Commands.SelectRole;
using Baya.Application.Features.Identity.Queries.GetMe;
using Baya.Application.Models.Identity;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Mediator;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Baya.Web.Api.Controllers.V1;
[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[Display(Description = "The signed-in user's identity, roles and role selection")]
public sealed class MeController(ISender sender) : BaseController
{
[HttpGet]
[ProducesOkApiResponseType<MeResult>]
public async Task<IActionResult> GetMe(CancellationToken cancellationToken)
=> OperationResult(await sender.Send(new GetMeQuery(), cancellationToken));
/// <remarks>Role claims live inside the access token — after selecting a role the client should
/// refresh its tokens to pick the new role up.</remarks>
[HttpPost("[action]")]
[ProducesOkApiResponseType<MeResult>]
public async Task<IActionResult> SelectRole(SelectRoleCommand command, CancellationToken cancellationToken)
=> OperationResult(await sender.Send(command, cancellationToken));
}
+10 -2
View File
@@ -94,8 +94,13 @@ builder.Services.ConfigureGrpcPluginServices();
var app = builder.Build();
await app.ApplyMigrationsAsync();
await app.SeedDefaultUsersAsync();
// Integration tests (WebApplicationFactory, env "Testing") run on in-memory SQLite — the SQL Server
// migrations can't apply there; the test factory does EnsureCreated + seeding itself.
if (!app.Environment.IsEnvironment("Testing"))
{
await app.ApplyMigrationsAsync();
await app.SeedDefaultUsersAsync();
}
if (app.Environment.IsDevelopment())
{
@@ -121,5 +126,8 @@ app.ConfigureGrpcPipeline();
await app.RunAsync();
/// <summary>Exposes the entry point to <c>WebApplicationFactory&lt;Program&gt;</c>-based integration tests.</summary>
public partial class Program;
@@ -1,7 +1,9 @@
using System.Security.Claims;
using Baya.Application.Models.ApiResult;
using Baya.Application.Models.Common;
using Baya.SharedKernel.Extensions;
using Baya.WebFramework.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Baya.WebFramework.BaseController;
@@ -34,6 +36,16 @@ public class BaseController : ControllerBase
return NotFound(notFoundErrors.Errors);
}
// 401/403 are written as the final envelope directly (mirroring the JWT-event responses) —
// the result filters only translate Ok/NotFound/BadRequest.
if (result.IsUnauthorized)
return new JsonResult(new ApiResult(false, ApiResultStatusCode.UnAuthorized, FirstErrorMessage(result)))
{ StatusCode = StatusCodes.Status401Unauthorized };
if (result.IsForbidden)
return new JsonResult(new ApiResult(false, ApiResultStatusCode.Forbidden, FirstErrorMessage(result)))
{ StatusCode = StatusCodes.Status403Forbidden };
AddErrors(result);
var badRequestErrors = new ValidationProblemDetails(ModelState);
@@ -49,4 +61,7 @@ public class BaseController : ControllerBase
ModelState.AddModelError(error.Key,error.Value);
}
}
private static string FirstErrorMessage<TModel>(OperationResult<TModel> result)
=> result.ErrorMessages.Count > 0 ? result.ErrorMessages[0].Value : null;
}