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
@@ -12,4 +12,7 @@ public interface ICurrentUser
bool IsAuthenticated { get; }
IReadOnlyList<string> Roles { get; }
}
/// <summary>The caller's remote IP, when there is an HTTP request (session bookkeeping); else null.</summary>
string IpAddress { get; }
}
@@ -0,0 +1,16 @@
#nullable enable
namespace Baya.Application.Contracts.Common;
/// <summary>
/// Seam for outbound SMS delivery — the OTP rail plus later transactional messages. The mock logs the
/// OTP code (never the full phone number); the real implementation swaps to an Iranian gateway
/// (Kavenegar/Ghasedak/SMS.ir) behind the same interface via a registration change only.
/// </summary>
public interface ISmsSender
{
/// <summary>Delivers a one-time login code to the given (normalized) phone number.</summary>
Task SendOtpAsync(string phone, string code, CancellationToken cancellationToken = default);
/// <summary>Delivers a free-form transactional message (booking updates etc., later phases).</summary>
Task SendAsync(string phone, string message, CancellationToken cancellationToken = default);
}
@@ -1,4 +1,4 @@
using System.Security.Claims;
using System.Security.Claims;
using Baya.Application.Models.Jwt;
using Baya.Domain.Entities.User;
@@ -10,4 +10,11 @@ public interface IJwtService
Task<ClaimsPrincipal> GetPrincipalFromExpiredToken(string token);
Task<AccessToken> GenerateByPhoneNumberAsync(string phoneNumber);
Task<AccessToken> RefreshToken(Guid refreshTokenId);
/// <summary>
/// Mints a JWE access token only — no refresh-token bookkeeping. The REST auth flow (b2) pairs it
/// with a <c>user_sessions</c> row; the legacy <see cref="GenerateAsync"/> keeps feeding the gRPC
/// path its <c>UserRefreshTokens</c> row.
/// </summary>
Task<JweAccessToken> GenerateAccessTokenAsync(User user);
}
@@ -1,8 +1,10 @@
namespace Baya.Application.Contracts.Persistence;
namespace Baya.Application.Contracts.Persistence;
public interface IUnitOfWork
{
public IUserRefreshTokenRepository UserRefreshTokenRepository { get; }
public IUserSessionRepository UserSessionRepository { get; }
public IUserAccountRepository UserAccountRepository { get; }
Task CommitAsync();
ValueTask RollBackAsync();
}
@@ -0,0 +1,20 @@
#nullable enable
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.User;
namespace Baya.Application.Contracts.Persistence;
public interface IUserAccountRepository
{
/// <summary>No-tracking projection of the user's account facts + active role names (for `/me`).
/// The phone comes back decrypted and unmasked — masking is the handler's job.</summary>
Task<UserAccountSnapshot?> GetAccountSnapshotAsync(int userId, CancellationToken cancellationToken);
Task<Role?> GetRoleByNameAsync(string roleName, CancellationToken cancellationToken);
/// <summary>Tracked user-role lookup that bypasses the revoked-filter, so a revoked grant can be
/// re-activated instead of violating the composite key.</summary>
Task<UserRole?> GetUserRoleIncludingRevokedAsync(int userId, int roleId, CancellationToken cancellationToken);
Task AddUserRoleAsync(UserRole userRole, CancellationToken cancellationToken);
}
@@ -0,0 +1,20 @@
#nullable enable
using Baya.Domain.Entities.User;
namespace Baya.Application.Contracts.Persistence;
public interface IUserSessionRepository
{
Task AddAsync(UserSession session, CancellationToken cancellationToken);
/// <summary>Tracked lookup by refresh-token hash (with the owning user), regardless of revocation —
/// the refresh flow needs to see revoked sessions to detect stolen-token reuse.</summary>
Task<UserSession?> GetByTokenHashAsync(string refreshTokenHash, CancellationToken cancellationToken);
/// <summary>Tracked lookup of a caller-owned, still-active session (single-device logout).</summary>
Task<UserSession?> GetActiveForUserByTokenHashAsync(int userId, string refreshTokenHash, CancellationToken cancellationToken);
/// <summary>Marks every active session of the user revoked (logout-everywhere / reuse detection).
/// Changes are persisted by the caller's commit.</summary>
Task<int> RevokeAllActiveForUserAsync(int userId, DateTimeOffset revokedAt, CancellationToken cancellationToken);
}
@@ -0,0 +1,47 @@
#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Identity;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.Logout;
internal sealed class LogoutCommandHandler(
ICurrentUser currentUser,
IUnitOfWork unitOfWork,
IAppUserManager userManager,
IFieldEncryptor fieldEncryptor,
IDateTimeProvider clock)
: IRequestHandler<LogoutCommand, OperationResult<bool>>
{
public async ValueTask<OperationResult<bool>> Handle(LogoutCommand request, CancellationToken cancellationToken)
{
if (currentUser.UserId is not { } userId)
return OperationResult<bool>.UnauthorizedResult("Not authenticated.");
var now = clock.UtcNow;
if (request.Everywhere || string.IsNullOrEmpty(request.RefreshToken))
{
await unitOfWork.UserSessionRepository.RevokeAllActiveForUserAsync(userId, now, cancellationToken);
}
else
{
var session = await unitOfWork.UserSessionRepository.GetActiveForUserByTokenHashAsync(
userId, fieldEncryptor.Hash(request.RefreshToken), cancellationToken);
session?.Revoke(now);
}
// The existing RequestLogout mechanism: rotating the security stamp makes the JWE
// OnTokenValidated stamp check reject every outstanding access token server-side.
var user = await userManager.GetUserByIdAsync(userId);
if (user is null)
return OperationResult<bool>.UnauthorizedResult("Not authenticated.");
await userManager.UpdateSecurityStampAsync(user);
await unitOfWork.CommitAsync();
return OperationResult<bool>.SuccessResult(true);
}
}
@@ -0,0 +1,13 @@
#nullable enable
using Baya.Application.Models.Common;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.Logout;
/// <summary>
/// Revokes the session matching <paramref name="RefreshToken"/>; with <paramref name="Everywhere"/>
/// (or no token supplied) every active session goes. The security stamp always rotates, so outstanding
/// access tokens die too.
/// </summary>
public record LogoutCommand(string? RefreshToken = null, bool Everywhere = false)
: IRequest<OperationResult<bool>>;
@@ -0,0 +1,82 @@
#nullable enable
using Baya.Application.Contracts;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Configuration;
using Baya.Application.Contracts.Identity;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
using Microsoft.Extensions.Logging;
namespace Baya.Application.Features.Identity.Commands.RefreshToken;
internal sealed class RefreshTokenCommandHandler(
IUnitOfWork unitOfWork,
IJwtService jwtService,
IAppUserManager userManager,
IPlatformConfig platformConfig,
IFieldEncryptor fieldEncryptor,
IDateTimeProvider clock,
ICurrentUser currentUser,
ILogger<RefreshTokenCommandHandler> logger)
: IRequestHandler<RefreshTokenCommand, OperationResult<AuthTokensResult>>
{
public async ValueTask<OperationResult<AuthTokensResult>> Handle(RefreshTokenCommand request, CancellationToken cancellationToken)
{
var tokenHash = fieldEncryptor.Hash(request.RefreshToken);
var session = await unitOfWork.UserSessionRepository.GetByTokenHashAsync(tokenHash, cancellationToken);
if (session is null)
return OperationResult<AuthTokensResult>.UnauthorizedResult("Invalid refresh token.");
var now = clock.UtcNow;
if (session.IsRevoked)
{
// A token replayed against an already-rotated session is a stolen-token signal:
// log the user out everywhere and refuse.
var revoked = await unitOfWork.UserSessionRepository.RevokeAllActiveForUserAsync(session.UserId, now, cancellationToken);
await unitOfWork.CommitAsync();
logger.LogWarning(
"Refresh-token reuse detected for user {UserId}; revoked {RevokedSessions} active session(s).",
session.UserId, revoked);
return OperationResult<AuthTokensResult>.UnauthorizedResult("Refresh token is no longer valid. Sign in again.");
}
if (session.ExpiresAt <= now)
{
session.Revoke(now);
await unitOfWork.CommitAsync();
return OperationResult<AuthTokensResult>.UnauthorizedResult("Refresh token expired. Sign in again.");
}
var user = session.User;
if (user is null || !user.IsActive)
return OperationResult<AuthTokensResult>.UnauthorizedResult("Invalid refresh token.");
// Rotation: the presented session dies, a fresh pair is issued.
session.Revoke(now);
var roles = await userManager.GetRoleAsync(user);
var accessToken = await jwtService.GenerateAccessTokenAsync(user);
var sessionTtlDays = await platformConfig.GetConfig<int>(IdentityDefaults.SessionTtlDaysKey, cancellationToken);
var (refreshToken, newSession) = IdentityDefaults.MintSession(
fieldEncryptor, user.Id, now, sessionTtlDays,
request.DeviceInfo ?? session.DeviceInfo, currentUser.IpAddress);
await unitOfWork.UserSessionRepository.AddAsync(newSession, cancellationToken);
await unitOfWork.CommitAsync();
return OperationResult<AuthTokensResult>.SuccessResult(new AuthTokensResult(
accessToken.Token,
refreshToken,
accessToken.ExpiresAt,
newSession.ExpiresAt,
IsNewUser: false,
Roles: roles));
}
}
@@ -0,0 +1,16 @@
using FluentValidation;
namespace Baya.Application.Features.Identity.Commands.RefreshToken;
public sealed class RefreshTokenCommandValidator : AbstractValidator<RefreshTokenCommand>
{
public RefreshTokenCommandValidator()
{
RuleFor(x => x.RefreshToken)
.NotEmpty()
.MaximumLength(200);
RuleFor(x => x.DeviceInfo)
.MaximumLength(400);
}
}
@@ -0,0 +1,9 @@
#nullable enable
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.RefreshToken;
public record RefreshTokenCommand(string RefreshToken, string? DeviceInfo = null)
: IRequest<OperationResult<AuthTokensResult>>;
@@ -0,0 +1,69 @@
#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Configuration;
using Baya.Application.Contracts.Identity;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.User;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.RequestOtp;
internal sealed class RequestOtpCommandHandler(
IAppUserManager userManager,
ISmsSender smsSender,
IPlatformConfig platformConfig,
ICacheService cache,
IFieldEncryptor fieldEncryptor,
IDateTimeProvider clock)
: IRequestHandler<RequestOtpCommand, OperationResult<RequestOtpResult>>
{
public async ValueTask<OperationResult<RequestOtpResult>> Handle(RequestOtpCommand request, CancellationToken cancellationToken)
{
var phone = IranianPhone.Normalize(request.Phone);
if (phone is null)
return OperationResult<RequestOtpResult>.FailureResult(nameof(request.Phone), "A valid Iranian mobile number is required.");
var resendSeconds = await platformConfig.GetConfig<int>(IdentityDefaults.OtpResendSecondsKey, cancellationToken);
// Per-phone resend window (the per-IP OTP rate-limit policy guards the endpoint separately).
// Same behaviour whether or not the phone has an account — no enumeration.
var resendKey = IdentityDefaults.OtpResendCacheKey(fieldEncryptor.Hash(phone));
var windowEndsAt = await cache.GetAsync<DateTimeOffset>(resendKey, cancellationToken);
var now = clock.UtcNow;
if (windowEndsAt > now)
return OperationResult<RequestOtpResult>.SuccessResult(
new RequestOtpResult(false, (int)Math.Ceiling((windowEndsAt - now).TotalSeconds)));
var user = await userManager.GetUserByPhoneNumber(phone);
if (user is null)
{
// Inactive-until-verified shell account; no PII beyond the (encrypted) phone. The surrogate
// username keeps the plaintext phone out of Identity's UserName/NormalizedUserName columns.
user = new User
{
UserName = $"u_{Guid.NewGuid():N}",
PhoneNumber = phone,
IsActive = false
};
var createResult = await userManager.CreateUser(user);
if (!createResult.Succeeded)
return OperationResult<RequestOtpResult>.FailureResult("Unable to process the request. Try again.");
}
// A fresh code voids the previous attempt counter; brute force stays bounded by the endpoint's
// per-IP rate limit plus the TOTP window.
await userManager.ResetUserLockoutAsync(user);
var code = user.PhoneNumberConfirmed
? await userManager.GenerateOtpCode(user)
: await userManager.GeneratePhoneNumberConfirmationToken(user, phone);
await smsSender.SendOtpAsync(phone, code, cancellationToken);
await cache.SetAsync(resendKey, now.AddSeconds(resendSeconds), TimeSpan.FromSeconds(resendSeconds), cancellationToken);
return OperationResult<RequestOtpResult>.SuccessResult(new RequestOtpResult(true, resendSeconds));
}
}
@@ -0,0 +1,13 @@
using FluentValidation;
namespace Baya.Application.Features.Identity.Commands.RequestOtp;
public sealed class RequestOtpCommandValidator : AbstractValidator<RequestOtpCommand>
{
public RequestOtpCommandValidator()
{
RuleFor(x => x.Phone)
.NotEmpty()
.Must(IranianPhone.IsValid).WithMessage("A valid Iranian mobile number is required (09xxxxxxxxx).");
}
}
@@ -0,0 +1,8 @@
#nullable enable
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.RequestOtp;
public record RequestOtpCommand(string Phone) : IRequest<OperationResult<RequestOtpResult>>;
@@ -0,0 +1,60 @@
#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.User;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.SelectRole;
internal sealed class SelectRoleCommandHandler(
ICurrentUser currentUser,
IUnitOfWork unitOfWork,
IDateTimeProvider clock)
: IRequestHandler<SelectRoleCommand, OperationResult<MeResult>>
{
public async ValueTask<OperationResult<MeResult>> Handle(SelectRoleCommand request, CancellationToken cancellationToken)
{
if (currentUser.UserId is not { } userId)
return OperationResult<MeResult>.UnauthorizedResult("Not authenticated.");
var roleName = request.Role.Trim().ToLowerInvariant();
if (!RoleNames.SelfAssignable.Contains(roleName))
return OperationResult<MeResult>.ForbiddenResult("Only the customer or nurse role can be self-selected.");
var role = await unitOfWork.UserAccountRepository.GetRoleByNameAsync(roleName, cancellationToken);
if (role is null)
return OperationResult<MeResult>.FailureResult("The requested role is not available.");
var now = clock.UtcNow;
var existing = await unitOfWork.UserAccountRepository.GetUserRoleIncludingRevokedAsync(userId, role.Id, cancellationToken);
if (existing is null)
{
await unitOfWork.UserAccountRepository.AddUserRoleAsync(new UserRole
{
UserId = userId,
RoleId = role.Id,
GrantedById = userId,
GrantedAt = now,
CreatedUserRoleDate = now.UtcDateTime
}, cancellationToken);
}
else if (existing.RevokedAt is not null)
{
// Re-activate the historical grant instead of colliding with the composite key.
existing.RevokedAt = null;
existing.GrantedById = userId;
existing.GrantedAt = now;
}
// else: already held — idempotent success.
await unitOfWork.CommitAsync();
var snapshot = await unitOfWork.UserAccountRepository.GetAccountSnapshotAsync(userId, cancellationToken);
return snapshot is null
? OperationResult<MeResult>.NotFoundResult("User not found.")
: OperationResult<MeResult>.SuccessResult(IdentityDefaults.ToMeResult(snapshot));
}
}
@@ -0,0 +1,13 @@
using FluentValidation;
namespace Baya.Application.Features.Identity.Commands.SelectRole;
public sealed class SelectRoleCommandValidator : AbstractValidator<SelectRoleCommand>
{
public SelectRoleCommandValidator()
{
RuleFor(x => x.Role)
.NotEmpty()
.MaximumLength(50);
}
}
@@ -0,0 +1,11 @@
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.SelectRole;
/// <summary>
/// Self-assigns one of the public actor roles (<c>customer</c> / <c>nurse</c>; a user may hold both).
/// Any admin sub-role is rejected with 403 — admin provisioning is internal-only.
/// </summary>
public record SelectRoleCommand(string Role) : IRequest<OperationResult<MeResult>>;
@@ -0,0 +1,77 @@
#nullable enable
using Baya.Application.Contracts;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Configuration;
using Baya.Application.Contracts.Identity;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.VerifyOtp;
internal sealed class VerifyOtpCommandHandler(
IAppUserManager userManager,
IJwtService jwtService,
IUnitOfWork unitOfWork,
IPlatformConfig platformConfig,
IFieldEncryptor fieldEncryptor,
IDateTimeProvider clock,
ICurrentUser currentUser)
: IRequestHandler<VerifyOtpCommand, OperationResult<AuthTokensResult>>
{
// One safe message for every wrong-phone/wrong-code combination — no account enumeration.
private const string InvalidCodeMessage = "The code is invalid or expired.";
public async ValueTask<OperationResult<AuthTokensResult>> Handle(VerifyOtpCommand request, CancellationToken cancellationToken)
{
var phone = IranianPhone.Normalize(request.Phone);
if (phone is null)
return OperationResult<AuthTokensResult>.FailureResult(nameof(request.Phone), InvalidCodeMessage);
var user = await userManager.GetUserByPhoneNumber(phone);
if (user is null)
return OperationResult<AuthTokensResult>.FailureResult(InvalidCodeMessage);
var maxAttempts = await platformConfig.GetConfig<int>(IdentityDefaults.OtpMaxAttemptsKey, cancellationToken);
if (user.AccessFailedCount >= maxAttempts)
return OperationResult<AuthTokensResult>.FailureResult("Too many failed attempts. Request a new code.");
// First-ever verify confirms the phone (ChangePhoneNumber to the same number); afterwards the
// passwordless TOTP path applies. Both rotate the security stamp, so the token is minted after.
var wasPhoneConfirmed = user.PhoneNumberConfirmed;
var verifyResult = wasPhoneConfirmed
? await userManager.VerifyUserCode(user, request.Code)
: await userManager.ChangePhoneNumber(user, phone, request.Code);
if (!verifyResult.Succeeded)
{
await userManager.IncrementAccessFailedCountAsync(user);
return OperationResult<AuthTokensResult>.FailureResult(InvalidCodeMessage);
}
var now = clock.UtcNow;
user.IsActive = true;
user.PhoneVerifiedAt ??= now;
await userManager.ResetUserLockoutAsync(user);
await userManager.UpdateUserAsync(user);
var roles = await userManager.GetRoleAsync(user);
var accessToken = await jwtService.GenerateAccessTokenAsync(user);
var sessionTtlDays = await platformConfig.GetConfig<int>(IdentityDefaults.SessionTtlDaysKey, cancellationToken);
var (refreshToken, session) = IdentityDefaults.MintSession(
fieldEncryptor, user.Id, now, sessionTtlDays, request.DeviceInfo, currentUser.IpAddress);
await unitOfWork.UserSessionRepository.AddAsync(session, cancellationToken);
await unitOfWork.CommitAsync();
return OperationResult<AuthTokensResult>.SuccessResult(new AuthTokensResult(
accessToken.Token,
refreshToken,
accessToken.ExpiresAt,
session.ExpiresAt,
IsNewUser: !wasPhoneConfirmed,
Roles: roles));
}
}
@@ -0,0 +1,20 @@
using FluentValidation;
namespace Baya.Application.Features.Identity.Commands.VerifyOtp;
public sealed class VerifyOtpCommandValidator : AbstractValidator<VerifyOtpCommand>
{
public VerifyOtpCommandValidator()
{
RuleFor(x => x.Phone)
.NotEmpty()
.Must(IranianPhone.IsValid).WithMessage("A valid Iranian mobile number is required (09xxxxxxxxx).");
RuleFor(x => x.Code)
.NotEmpty()
.MaximumLength(10);
RuleFor(x => x.DeviceInfo)
.MaximumLength(400);
}
}
@@ -0,0 +1,9 @@
#nullable enable
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Commands.VerifyOtp;
public record VerifyOtpCommand(string Phone, string Code, string? DeviceInfo = null)
: IRequest<OperationResult<AuthTokensResult>>;
@@ -0,0 +1,77 @@
#nullable enable
using System.Security.Cryptography;
using Baya.Application.Contracts.Common;
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.User;
namespace Baya.Application.Features.Identity;
/// <summary>
/// Shared vocabulary of the identity slices: the `platform_configs` keys the handlers read at compute
/// time (never hardcode the values), refresh-token minting, and phone masking for `/me`-style payloads.
/// </summary>
internal static class IdentityDefaults
{
/// <summary>Seconds a caller must wait before the same phone can be sent another OTP.</summary>
public const string OtpResendSecondsKey = "auth_otp_resend_seconds";
/// <summary>Wrong-code attempts allowed before verification is refused until a fresh OTP.</summary>
public const string OtpMaxAttemptsKey = "auth_otp_max_attempts";
/// <summary>Refresh-token session lifetime, in days.</summary>
public const string SessionTtlDaysKey = "auth_session_ttl_days";
/// <summary>Cache key of the per-phone resend window (keyed by phone hash, never the raw phone).</summary>
public static string OtpResendCacheKey(string phoneHash) => $"auth:otp:resend:{phoneHash}";
/// <summary>256-bit random opaque refresh token, hex-encoded (URL-safe). Only its keyed hash is stored.</summary>
public static string NewRefreshToken() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
/// <summary>Mints a raw refresh token plus its <c>user_sessions</c> row (hash stored, never the token).</summary>
public static (string RefreshToken, UserSession Session) MintSession(
IFieldEncryptor fieldEncryptor,
int userId,
DateTimeOffset now,
int ttlDays,
string? deviceInfo,
string? ipAddress)
{
var refreshToken = NewRefreshToken();
var session = new UserSession
{
UserId = userId,
RefreshTokenHash = fieldEncryptor.Hash(refreshToken),
DeviceInfo = deviceInfo,
IpAddress = ipAddress,
IsRevoked = false,
ExpiresAt = now.AddDays(ttlDays)
};
return (refreshToken, session);
}
/// <summary>Masks all but the first four and last two digits (e.g. 0912*****89).</summary>
public static string MaskPhone(string? phone)
{
if (string.IsNullOrEmpty(phone))
return string.Empty;
return phone.Length <= 6
? new string('*', phone.Length)
: $"{phone[..4]}{new string('*', phone.Length - 6)}{phone[^2..]}";
}
public static MeResult ToMeResult(UserAccountSnapshot snapshot) =>
new(
snapshot.Id,
MaskPhone(snapshot.Phone),
snapshot.FirstName,
snapshot.LastName,
snapshot.Gender,
snapshot.IsActive,
snapshot.Roles,
HasCustomerProfile: false,
HasNurseProfile: false,
NurseVerificationStatus: MeResult.VerificationNotStarted);
}
@@ -0,0 +1,29 @@
#nullable enable
using System.Text.RegularExpressions;
using Baya.SharedKernel.Extensions;
namespace Baya.Application.Features.Identity;
/// <summary>
/// Normalizes an Iranian mobile number to the canonical <c>09xxxxxxxxx</c> form (Persian digits
/// translated, +98/0098/98 prefixes folded). The canonical form is what gets stored, hashed, and
/// rate-limit-keyed — one identity per phone requires one spelling per phone.
/// </summary>
internal static partial class IranianPhone
{
[GeneratedRegex(@"^(?:\+98|0098|98|0)?(9\d{9})$")]
private static partial Regex MobilePattern();
public static string? Normalize(string? raw)
{
if (string.IsNullOrWhiteSpace(raw))
return null;
var digits = raw.Trim().Fa2En().Replace(" ", string.Empty).Replace("-", string.Empty);
var match = MobilePattern().Match(digits);
return match.Success ? $"0{match.Groups[1].Value}" : null;
}
public static bool IsValid(string? raw) => Normalize(raw) is not null;
}
@@ -0,0 +1,24 @@
#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Queries.GetMe;
internal sealed class GetMeQueryHandler(ICurrentUser currentUser, IUnitOfWork unitOfWork)
: IRequestHandler<GetMeQuery, OperationResult<MeResult>>
{
public async ValueTask<OperationResult<MeResult>> Handle(GetMeQuery request, CancellationToken cancellationToken)
{
if (currentUser.UserId is not { } userId)
return OperationResult<MeResult>.UnauthorizedResult("Not authenticated.");
var snapshot = await unitOfWork.UserAccountRepository.GetAccountSnapshotAsync(userId, cancellationToken);
return snapshot is null
? OperationResult<MeResult>.NotFoundResult("User not found.")
: OperationResult<MeResult>.SuccessResult(IdentityDefaults.ToMeResult(snapshot));
}
}
@@ -0,0 +1,7 @@
using Baya.Application.Models.Common;
using Baya.Application.Models.Identity;
using Mediator;
namespace Baya.Application.Features.Identity.Queries.GetMe;
public record GetMeQuery : IRequest<OperationResult<MeResult>>;
@@ -1,15 +1,15 @@
using Baya.Application.Contracts.Identity;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Identity;
using Baya.Application.Models.Common;
using Baya.Domain.Entities.User;
using MapsterMapper;
using Mediator;
using Microsoft.Extensions.Logging;
namespace Baya.Application.Features.Users.Commands.Create;
internal class UserCreateCommandHandler(
IAppUserManager userManager,
ILogger<UserCreateCommandHandler> logger,
ISmsSender smsSender,
IMapper mapper)
: IRequestHandler<UserCreateCommand, OperationResult<UserCreateCommandResult>>
{
@@ -26,12 +26,10 @@ internal class UserCreateCommandHandler(
if (phoneNumberExist)
return OperationResult<UserCreateCommandResult>.FailureResult("Username already exists");
//var user = new User { UserName = request.UserName, Name = request.FirstName, FamilyName = request.LastName, PhoneNumber = request.PhoneNumber };
var user = mapper.Map<User>(request);
var createResult =string.IsNullOrEmpty(request.Password)?
var createResult =string.IsNullOrEmpty(request.Password)?
await userManager.CreateUser(user)
:await userManager.CreateUser(user, request.Password);
@@ -43,10 +41,7 @@ internal class UserCreateCommandHandler(
var code = await userManager.GeneratePhoneNumberConfirmationToken(user, user.PhoneNumber);
logger.LogWarning($"Generated Code for User ID {user.Id} is {code}");
//TODO Send Code Via Sms Provider
await smsSender.SendOtpAsync(user.PhoneNumber, code, cancellationToken);
return OperationResult<UserCreateCommandResult>.SuccessResult(new UserCreateCommandResult
{ UserGeneratedKey = user.GeneratedCode });
@@ -1,17 +1,17 @@
using Baya.Application.Contracts.Identity;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Identity;
using Baya.Application.Models.Common;
using Mediator;
using Microsoft.Extensions.Logging;
namespace Baya.Application.Features.Users.Queries.TokenRequest;
public class UserTokenRequestQueryHandler(
IAppUserManager userManager,
ILogger<UserTokenRequestQueryHandler> logger)
ISmsSender smsSender)
: IRequestHandler<UserTokenRequestQuery, OperationResult<UserTokenRequestQueryResponse>>
{
public async ValueTask<OperationResult<UserTokenRequestQueryResponse>> Handle(UserTokenRequestQuery request, CancellationToken cancellationToken)
{
var user = await userManager.GetUserByPhoneNumber(request.UserPhoneNumber);
@@ -21,9 +21,7 @@ public class UserTokenRequestQueryHandler(
var code = user.PhoneNumberConfirmed? await userManager.GenerateOtpCode(user) : await userManager.GeneratePhoneNumberConfirmationToken(user,user.PhoneNumber);
logger.LogWarning($"Generated Code for user Id {user.Id} is {code}");
//TODO Send Code Via Sms Provider
await smsSender.SendOtpAsync(user.PhoneNumber, code, cancellationToken);
return OperationResult<UserTokenRequestQueryResponse>.SuccessResult(new UserTokenRequestQueryResponse {UserKey = user.GeneratedCode});
}
@@ -20,6 +20,12 @@ public class OperationResult<TResult> : IOperationResult
public bool IsException { get; set; }
public bool IsNotFound { get; set; }
/// <summary>Maps to HTTP 401 — e.g. a rejected/reused refresh token (backend-phase-2).</summary>
public bool IsUnauthorized { get; set; }
/// <summary>Maps to HTTP 403 — e.g. self-assigning an internal admin role (backend-phase-2).</summary>
public bool IsForbidden { get; set; }
public static OperationResult<TResult> SuccessResult(TResult result)
{
return new OperationResult<TResult> { Result = result, IsSuccess = true };
@@ -50,6 +56,24 @@ public class OperationResult<TResult> : IOperationResult
return operationResult;
}
public static OperationResult<TResult> UnauthorizedResult(string message)
{
var operationResult = new OperationResult<TResult> { IsSuccess = false, IsUnauthorized = true };
operationResult.ErrorMessages.Add(new("GeneralError", message));
return operationResult;
}
public static OperationResult<TResult> ForbiddenResult(string message)
{
var operationResult = new OperationResult<TResult> { IsSuccess = false, IsForbidden = true };
operationResult.ErrorMessages.Add(new("GeneralError", message));
return operationResult;
}
public void AddError(string propertyName, string message)
{
IsSuccess = false;
@@ -0,0 +1,14 @@
#nullable enable
namespace Baya.Application.Models.Identity;
/// <summary>
/// The token pair returned by OTP verification and refresh. <see cref="Roles"/> is empty for a fresh
/// user — the client's role router sends them to role selection.
/// </summary>
public record AuthTokensResult(
string AccessToken,
string RefreshToken,
DateTimeOffset AccessExpiresAt,
DateTimeOffset RefreshExpiresAt,
bool IsNewUser,
IReadOnlyList<string> Roles);
@@ -0,0 +1,22 @@
#nullable enable
namespace Baya.Application.Models.Identity;
/// <summary>
/// The `/me` payload. <see cref="Phone"/> is always masked. The profile-completion flags stay false
/// until the profile tables land (b3); <see cref="NurseVerificationStatus"/> reads
/// <c>nurse_verifications.status</c> once b6 exists — until then it is <c>not_started</c>.
/// </summary>
public record MeResult(
int Id,
string Phone,
string? FirstName,
string? LastName,
string? Gender,
bool IsActive,
IReadOnlyList<string> Roles,
bool HasCustomerProfile,
bool HasNurseProfile,
string NurseVerificationStatus)
{
public const string VerificationNotStarted = "not_started";
}
@@ -0,0 +1,7 @@
namespace Baya.Application.Models.Identity;
/// <summary>
/// Deliberately non-enumerating: the same shape comes back whether or not the phone already had an
/// account. <see cref="OtpSent"/> is false only when the per-phone resend window is still open.
/// </summary>
public record RequestOtpResult(bool OtpSent, int ResendAvailableInSeconds);
@@ -0,0 +1,12 @@
#nullable enable
namespace Baya.Application.Models.Identity;
/// <summary>Raw account projection for the current user (phone unmasked — handlers mask it).</summary>
public record UserAccountSnapshot(
int Id,
string? Phone,
string? FirstName,
string? LastName,
string? Gender,
bool IsActive,
IReadOnlyList<string> Roles);
@@ -0,0 +1,4 @@
namespace Baya.Application.Models.Jwt;
/// <summary>A freshly minted JWE access token and its absolute expiry.</summary>
public record JweAccessToken(string Token, DateTimeOffset ExpiresAt);
@@ -0,0 +1,23 @@
namespace Baya.Domain.Entities.User;
/// <summary>
/// The platform role vocabulary. <see cref="Customer"/> and <see cref="Nurse"/> are the public actor
/// roles a user may self-select (a user can hold both). The admin sub-roles are provisioned internally
/// only and are never self-assignable through any public endpoint.
/// </summary>
public static class RoleNames
{
public const string Customer = "customer";
public const string Nurse = "nurse";
public const string Admin = "admin";
public const string Support = "support";
public const string Finance = "finance";
public const string Moderation = "moderation";
public const string SuperAdmin = "super_admin";
public static readonly IReadOnlyList<string> SelfAssignable = [Customer, Nurse];
public static readonly IReadOnlyList<string> All =
[Customer, Nurse, Admin, Support, Finance, Moderation, SuperAdmin];
}
@@ -1,4 +1,4 @@
using Baya.Domain.Common;
using Baya.Domain.Common;
using Microsoft.AspNetCore.Identity;
namespace Baya.Domain.Entities.User;
@@ -13,10 +13,35 @@ public class User:IdentityUser<int>,IEntity
public string Name { get; set; }
public string FamilyName { get; set; }
public string GeneratedCode { get; set; }
/// <summary>
/// "male" / "female". Load-bearing for same-gender caregiver matching — never defaulted. Not
/// collected at OTP signup; populated later via the profile flow (b3).
/// </summary>
public string Gender { get; set; }
/// <summary>Encrypted at rest. Stays NULL until the KYC pipeline (b6) verifies it — an unverified
/// registration must never look KYC-complete.</summary>
public string NationalId { get; set; }
public DateTimeOffset? NationalIdVerifiedAt { get; set; }
/// <summary>When the phone↔national-id binding was confirmed via Shahkar. Reset to NULL whenever
/// the stored phone changes so b6 re-verifies (enforced centrally on SaveChanges).</summary>
public DateTimeOffset? ShahkarVerifiedAt { get; set; }
/// <summary>Deterministic keyed hash of the (encrypted) phone — carries the UNIQUE index and all
/// equality lookups, since the ciphertext itself is non-deterministic. Synced on SaveChanges.</summary>
public string PhoneHash { get; set; }
public DateTimeOffset? PhoneVerifiedAt { get; set; }
public bool IsActive { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
public ICollection<UserRole> UserRoles { get; set; }
public ICollection<UserLogin> Logins { get; set; }
public ICollection<UserClaim> Claims { get; set; }
public ICollection<UserToken> Tokens { get; set; }
public ICollection<UserRefreshToken> UserRefreshTokens { get; set; }
public ICollection<UserSession> Sessions { get; set; }
}
@@ -1,4 +1,4 @@
using Baya.Domain.Common;
using Baya.Domain.Common;
using Microsoft.AspNetCore.Identity;
namespace Baya.Domain.Entities.User;
@@ -9,4 +9,11 @@ public class UserRole : IdentityUserRole<int>,IEntity
public Role Role { get; set; }
public DateTime CreatedUserRoleDate { get; set; }
/// <summary>Who granted the role — the user themself for the public customer/nurse self-select,
/// an admin for internal RBAC grants. NULL for legacy/seeded rows.</summary>
public int? GrantedById { get; set; }
public DateTimeOffset GrantedAt { get; set; }
/// <summary>A revoked grant is kept as history (global query filter hides it from role reads).</summary>
public DateTimeOffset? RevokedAt { get; set; }
}
@@ -0,0 +1,29 @@
using Baya.Domain.Common;
namespace Baya.Domain.Entities.User;
/// <summary>
/// A revocable refresh-token session. Only the deterministic hash of the refresh token is stored —
/// never the raw token. Each refresh rotates: the presented session is revoked and a new one issued;
/// a token presented against an already-revoked session is treated as a stolen-token signal and all of
/// the user's sessions are revoked.
/// </summary>
public class UserSession : BaseEntity<long>
{
public int UserId { get; set; }
public User User { get; set; }
public string RefreshTokenHash { get; set; }
public string DeviceInfo { get; set; }
public string IpAddress { get; set; }
public bool IsRevoked { get; set; }
public DateTimeOffset? RevokedAt { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
public void Revoke(DateTimeOffset now)
{
IsRevoked = true;
RevokedAt = now;
}
}