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:
@@ -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));
|
||||
}
|
||||
@@ -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<Program></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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
+47
@@ -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>>;
|
||||
+82
@@ -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));
|
||||
}
|
||||
}
|
||||
+16
@@ -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);
|
||||
}
|
||||
}
|
||||
+9
@@ -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>>;
|
||||
+69
@@ -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));
|
||||
}
|
||||
}
|
||||
+13
@@ -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).");
|
||||
}
|
||||
}
|
||||
+8
@@ -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>>;
|
||||
+60
@@ -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));
|
||||
}
|
||||
}
|
||||
+13
@@ -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);
|
||||
}
|
||||
}
|
||||
+11
@@ -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>>;
|
||||
+77
@@ -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));
|
||||
}
|
||||
}
|
||||
+20
@@ -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);
|
||||
}
|
||||
}
|
||||
+9
@@ -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;
|
||||
}
|
||||
+24
@@ -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>>;
|
||||
+6
-11
@@ -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 });
|
||||
|
||||
+6
-8
@@ -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;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -36,7 +36,8 @@ public static class LoggingConfiguration
|
||||
columnOpts.PrimaryKey = columnOpts.Id;
|
||||
columnOpts.Id.DataType = SqlDbType.Int;
|
||||
|
||||
if (!context.HostingEnvironment.IsDevelopment())
|
||||
// Development and Testing (WebApplicationFactory) log locally; the SQL sink is for deployed envs.
|
||||
if (!context.HostingEnvironment.IsDevelopment() && !context.HostingEnvironment.IsEnvironment("Testing"))
|
||||
{
|
||||
configuration.WriteTo
|
||||
.MSSqlServer(
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Baya.Infrastructure.CrossCutting.Seams;
|
||||
|
||||
/// <summary>
|
||||
/// Mock <see cref="ISmsSender"/>: "delivers" by logging. The OTP code is written to the log so a
|
||||
/// developer can complete the login flow; the phone number is never logged in full (PII policy) —
|
||||
/// only its last four digits. The real implementation swaps to an Iranian SMS gateway
|
||||
/// (Kavenegar/Ghasedak/SMS.ir) behind the same interface via a registration change.
|
||||
/// </summary>
|
||||
public sealed class LoggingSmsSender(ILogger<LoggingSmsSender> logger) : ISmsSender
|
||||
{
|
||||
public Task SendOtpAsync(string phone, string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
logger.LogWarning("MOCK SMS — OTP code {OtpCode} for phone ending in {PhoneTail}", code, Tail(phone));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SendAsync(string phone, string message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
logger.LogWarning("MOCK SMS — message to phone ending in {PhoneTail}: {Message}", Tail(phone), message);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static string Tail(string phone) =>
|
||||
string.IsNullOrEmpty(phone) ? "????" : phone[^Math.Min(4, phone.Length)..];
|
||||
}
|
||||
+5
-1
@@ -8,7 +8,7 @@ namespace Baya.Infrastructure.CrossCutting.ServiceConfiguration;
|
||||
public static class ServiceCollectionExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the cross-cutting seams (time, PII encryption, cache, object storage) with their
|
||||
/// Registers the cross-cutting seams (time, PII encryption, cache, object storage, SMS) with their
|
||||
/// in-memory/local mock implementations. Swapping in a real provider later is a registration change
|
||||
/// here — callers depend only on the Application contracts. (The real in-app
|
||||
/// <c>INotificationDispatcher</c> needs the database, so it is registered in the Persistence layer.)
|
||||
@@ -24,6 +24,10 @@ public static class ServiceCollectionExtension
|
||||
services.AddSingleton<ICacheService, MemoryCacheService>();
|
||||
services.AddSingleton<IObjectStorage, LocalDiskObjectStorage>();
|
||||
|
||||
// OTP/SMS delivery rail (backend-phase-2). The mock logs the code; a real gateway client
|
||||
// (Kavenegar/Ghasedak/SMS.ir) replaces this registration only.
|
||||
services.AddSingleton<ISmsSender, LoggingSmsSender>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -27,4 +27,7 @@ public sealed class HttpContextCurrentUser(IHttpContextAccessor httpContextAcces
|
||||
|
||||
public IReadOnlyList<string> Roles =>
|
||||
Principal?.FindAll(ClaimTypes.Role).Select(c => c.Value).ToArray() ?? [];
|
||||
|
||||
public string? IpAddress =>
|
||||
httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
||||
}
|
||||
|
||||
+2
@@ -13,4 +13,6 @@ public sealed class NullCurrentUser : ICurrentUser
|
||||
public bool IsAuthenticated => false;
|
||||
|
||||
public IReadOnlyList<string> Roles => [];
|
||||
|
||||
public string IpAddress => null;
|
||||
}
|
||||
|
||||
+12
-7
@@ -1,4 +1,4 @@
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Identity.Identity.Manager;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -22,13 +22,17 @@ public class SeedDataBase : ISeedDataBase
|
||||
|
||||
public async Task Seed()
|
||||
{
|
||||
if (!_roleManager.Roles.AsNoTracking().Any(r => r.Name.Equals("admin")))
|
||||
// The full role vocabulary: public actor roles (customer/nurse — self-selectable) and the
|
||||
// admin sub-roles (internally provisioned only, never self-assignable).
|
||||
foreach (var roleName in RoleNames.All)
|
||||
{
|
||||
var role=new Role
|
||||
if (!_roleManager.Roles.AsNoTracking().Any(r => r.Name.Equals(roleName)))
|
||||
{
|
||||
Name = "admin",
|
||||
};
|
||||
await _roleManager.CreateAsync(role);
|
||||
await _roleManager.CreateAsync(new Role
|
||||
{
|
||||
Name = roleName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!_userManager.Users.AsNoTracking().Any(u => u.UserName.Equals("admin")))
|
||||
@@ -37,7 +41,8 @@ public class SeedDataBase : ISeedDataBase
|
||||
{
|
||||
UserName = "admin",
|
||||
Email = "admin@site.com",
|
||||
PhoneNumberConfirmed = true
|
||||
PhoneNumberConfirmed = true,
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
await _userManager.CreateAsync(user, "qw123321");
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Baya.Application.Contracts;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Application.Models.Jwt;
|
||||
using Baya.Domain.Entities.User;
|
||||
@@ -19,44 +20,21 @@ public class JwtService : IJwtService
|
||||
private readonly IdentitySettings _siteSetting;
|
||||
private readonly AppUserManager _userManager;
|
||||
private IUserClaimsPrincipalFactory<User> _claimsPrincipal;
|
||||
private readonly IFieldEncryptor _fieldEncryptor;
|
||||
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
//private readonly AppUserClaimsPrincipleFactory claimsPrincipleFactory;
|
||||
|
||||
public JwtService(IOptions<IdentitySettings> siteSetting, AppUserManager userManager, IUserClaimsPrincipalFactory<User> claimsPrincipal, IUnitOfWork unitOfWork)
|
||||
public JwtService(IOptions<IdentitySettings> siteSetting, AppUserManager userManager, IUserClaimsPrincipalFactory<User> claimsPrincipal, IUnitOfWork unitOfWork, IFieldEncryptor fieldEncryptor)
|
||||
{
|
||||
_siteSetting = siteSetting.Value;
|
||||
_userManager = userManager;
|
||||
_claimsPrincipal = claimsPrincipal;
|
||||
_unitOfWork = unitOfWork;
|
||||
_fieldEncryptor = fieldEncryptor;
|
||||
}
|
||||
public async Task<AccessToken> GenerateAsync(User user)
|
||||
{
|
||||
var secretKey = Encoding.UTF8.GetBytes(_siteSetting.SecretKey); // longer that 16 character
|
||||
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);
|
||||
|
||||
var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.Encryptkey); //must be 16 character
|
||||
var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
|
||||
|
||||
|
||||
var claims = await _getClaimsAsync(user);
|
||||
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Issuer = _siteSetting.Issuer,
|
||||
Audience = _siteSetting.Audience,
|
||||
IssuedAt = DateTime.Now,
|
||||
NotBefore = DateTime.Now.AddMinutes(0),
|
||||
Expires = DateTime.Now.AddMinutes(_siteSetting.ExpirationMinutes),
|
||||
SigningCredentials = signingCredentials,
|
||||
EncryptingCredentials = encryptingCredentials,
|
||||
Subject = new ClaimsIdentity(claims)
|
||||
};
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
||||
var securityToken = tokenHandler.CreateJwtSecurityToken(descriptor);
|
||||
|
||||
var securityToken = await _createSecurityTokenAsync(user);
|
||||
|
||||
var refreshToken = await _unitOfWork.UserRefreshTokenRepository.CreateToken(user.Id);
|
||||
await _unitOfWork.CommitAsync();
|
||||
@@ -64,6 +42,19 @@ public class JwtService : IJwtService
|
||||
return new AccessToken(securityToken,refreshToken.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Access token only — no <c>UserRefreshTokens</c> row. The REST auth flow (backend-phase-2)
|
||||
/// pairs this with its own revocable <c>user_sessions</c> refresh token.
|
||||
/// </summary>
|
||||
public async Task<JweAccessToken> GenerateAccessTokenAsync(User user)
|
||||
{
|
||||
var securityToken = await _createSecurityTokenAsync(user);
|
||||
|
||||
return new JweAccessToken(
|
||||
new JwtSecurityTokenHandler().WriteToken(securityToken),
|
||||
new DateTimeOffset(securityToken.ValidTo, TimeSpan.Zero));
|
||||
}
|
||||
|
||||
public Task<ClaimsPrincipal> GetPrincipalFromExpiredToken(string token)
|
||||
{
|
||||
var tokenValidationParameters = new TokenValidationParameters
|
||||
@@ -88,7 +79,9 @@ public class JwtService : IJwtService
|
||||
|
||||
public async Task<AccessToken> GenerateByPhoneNumberAsync(string phoneNumber)
|
||||
{
|
||||
var user = await _userManager.Users.AsNoTracking().FirstOrDefaultAsync(u => u.PhoneNumber == phoneNumber);
|
||||
// The phone column is encrypted (non-deterministic); equality goes through the hash.
|
||||
var phoneHash = _fieldEncryptor.Hash(phoneNumber);
|
||||
var user = await _userManager.Users.AsNoTracking().FirstOrDefaultAsync(u => u.PhoneHash == phoneHash);
|
||||
var result = await this.GenerateAsync(user);
|
||||
return result;
|
||||
}
|
||||
@@ -96,7 +89,7 @@ public class JwtService : IJwtService
|
||||
public async Task<AccessToken> RefreshToken(Guid refreshTokenId)
|
||||
{
|
||||
var refreshToken = await _unitOfWork.UserRefreshTokenRepository.GetTokenWithInvalidation(refreshTokenId);
|
||||
|
||||
|
||||
if (refreshToken is null)
|
||||
return null;
|
||||
|
||||
@@ -114,6 +107,33 @@ public class JwtService : IJwtService
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<JwtSecurityToken> _createSecurityTokenAsync(User user)
|
||||
{
|
||||
var secretKey = Encoding.UTF8.GetBytes(_siteSetting.SecretKey); // longer that 16 character
|
||||
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);
|
||||
|
||||
var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.Encryptkey); //must be 16 character
|
||||
var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
|
||||
|
||||
var claims = await _getClaimsAsync(user);
|
||||
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Issuer = _siteSetting.Issuer,
|
||||
Audience = _siteSetting.Audience,
|
||||
IssuedAt = DateTime.Now,
|
||||
NotBefore = DateTime.Now.AddMinutes(0),
|
||||
Expires = DateTime.Now.AddMinutes(_siteSetting.ExpirationMinutes),
|
||||
SigningCredentials = signingCredentials,
|
||||
EncryptingCredentials = encryptingCredentials,
|
||||
Subject = new ClaimsIdentity(claims)
|
||||
};
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
||||
return tokenHandler.CreateJwtSecurityToken(descriptor);
|
||||
}
|
||||
|
||||
private async Task<IEnumerable<Claim>> _getClaimsAsync(User user)
|
||||
{
|
||||
var result = await _claimsPrincipal.CreateAsync(user);
|
||||
|
||||
+12
-4
@@ -1,4 +1,5 @@
|
||||
using Baya.Application.Contracts.Identity;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Application.Contracts.Identity;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Identity.Identity.Dtos;
|
||||
using Baya.Infrastructure.Identity.Identity.Manager;
|
||||
@@ -10,9 +11,12 @@ namespace Baya.Infrastructure.Identity.UserManager;
|
||||
public class AppUserManagerImplementation : IAppUserManager
|
||||
{
|
||||
private readonly AppUserManager _userManager;
|
||||
public AppUserManagerImplementation(AppUserManager userManager)
|
||||
private readonly IFieldEncryptor _fieldEncryptor;
|
||||
|
||||
public AppUserManagerImplementation(AppUserManager userManager, IFieldEncryptor fieldEncryptor)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_fieldEncryptor = fieldEncryptor;
|
||||
}
|
||||
|
||||
public Task<IdentityResult> CreateUser(User user)
|
||||
@@ -27,7 +31,10 @@ public class AppUserManagerImplementation : IAppUserManager
|
||||
|
||||
public Task<bool> IsExistUser(string phoneNumber)
|
||||
{
|
||||
return _userManager.Users.AnyAsync(c => c.PhoneNumber == phoneNumber);
|
||||
// The phone column is encrypted (non-deterministic ciphertext) — equality goes through the
|
||||
// deterministic hash column.
|
||||
var phoneHash = _fieldEncryptor.Hash(phoneNumber);
|
||||
return _userManager.Users.AnyAsync(c => c.PhoneHash == phoneHash);
|
||||
}
|
||||
|
||||
public Task<bool> IsExistUserName(string userName)
|
||||
@@ -71,7 +78,8 @@ public class AppUserManagerImplementation : IAppUserManager
|
||||
|
||||
public Task<User> GetUserByPhoneNumber(string phoneNumber)
|
||||
{
|
||||
return _userManager.Users.FirstOrDefaultAsync(c => c.PhoneNumber.Equals(phoneNumber));
|
||||
var phoneHash = _fieldEncryptor.Hash(phoneNumber);
|
||||
return _userManager.Users.FirstOrDefaultAsync(c => c.PhoneHash == phoneHash);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.Reflection;
|
||||
using System.Reflection;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Domain.Common;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Persistence.ValueConversion;
|
||||
using Baya.SharedKernel.Extensions;
|
||||
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -9,15 +11,46 @@ namespace Baya.Infrastructure.Persistence;
|
||||
|
||||
public class ApplicationDbContext: IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
|
||||
{
|
||||
public ApplicationDbContext(DbContextOptions options)
|
||||
private readonly IFieldEncryptor _fieldEncryptor;
|
||||
|
||||
// The encryptor ends up captured inside the cached EF model (value converters), so it must be a
|
||||
// process-wide singleton with stable keys — which is how the seam is registered.
|
||||
public ApplicationDbContext(DbContextOptions options, IFieldEncryptor fieldEncryptor)
|
||||
: base(options)
|
||||
{
|
||||
_fieldEncryptor = fieldEncryptor;
|
||||
base.SavingChanges += OnSavingChanges;
|
||||
}
|
||||
|
||||
private void OnSavingChanges(object sender, SavingChangesEventArgs e)
|
||||
{
|
||||
_cleanString();
|
||||
_syncUserPhoneIntegrity();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the deterministic <c>PhoneHash</c> lookup column in step with the encrypted phone, and
|
||||
/// enforces the product rule that a phone change invalidates the Shahkar phone↔national-id binding
|
||||
/// (reset to NULL so b6 re-verifies) — centrally, so no handler can forget it.
|
||||
/// </summary>
|
||||
private void _syncUserPhoneIntegrity()
|
||||
{
|
||||
foreach (var entry in ChangeTracker.Entries<User>())
|
||||
{
|
||||
if (entry.State == EntityState.Added)
|
||||
{
|
||||
entry.Entity.PhoneHash = _fieldEncryptor.Hash(entry.Entity.PhoneNumber);
|
||||
}
|
||||
else if (entry.State == EntityState.Modified)
|
||||
{
|
||||
var phone = entry.Property(u => u.PhoneNumber);
|
||||
if (!string.Equals(phone.OriginalValue, phone.CurrentValue, StringComparison.Ordinal))
|
||||
{
|
||||
entry.Entity.PhoneHash = _fieldEncryptor.Hash(phone.CurrentValue);
|
||||
entry.Entity.ShahkarVerifiedAt = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void _cleanString()
|
||||
@@ -59,6 +92,16 @@ public class ApplicationDbContext: IdentityDbContext<User, Role, int, UserClaim,
|
||||
modelBuilder.AddRestrictDeleteBehaviorConvention();
|
||||
modelBuilder.AddPluralizingTableNameConvention();
|
||||
|
||||
|
||||
// PII encrypted at rest via the seam. These columns are equality-unqueryable by design —
|
||||
// phone lookups use PhoneHash. Applied here (not in UserConfig) because the converter needs
|
||||
// the encryptor instance.
|
||||
var encrypted = new EncryptedStringConverter(_fieldEncryptor);
|
||||
modelBuilder.Entity<User>(builder =>
|
||||
{
|
||||
builder.Property(u => u.PhoneNumber).HasConversion(encrypted);
|
||||
builder.Property(u => u.Email).HasConversion(encrypted);
|
||||
builder.Property(u => u.NormalizedEmail).HasConversion(encrypted);
|
||||
builder.Property(u => u.NationalId).HasConversion(encrypted);
|
||||
});
|
||||
}
|
||||
}
|
||||
+3
@@ -40,6 +40,9 @@ internal sealed class PlatformConfigConfig : IEntityTypeConfiguration<PlatformCo
|
||||
(10, "bnpl_provider_commission_rate", "0.07", ConfigDataType.Decimal, "BNPL provider commission rate (fraction)."),
|
||||
(11, "bnpl_settlement_timing", "immediate", ConfigDataType.String, "When BNPL settles funds to the platform (immediate|deferred)."),
|
||||
(12, "cancellation_tiers", "[{\"min_hours_before\":48,\"refund_percent\":100},{\"min_hours_before\":24,\"refund_percent\":50},{\"min_hours_before\":0,\"refund_percent\":0}]", ConfigDataType.Json, "Tiered cancellation refund policy: refund_percent by hours before the visit."),
|
||||
(13, "auth_otp_resend_seconds", "120", ConfigDataType.Int, "Seconds a phone must wait before another OTP can be requested."),
|
||||
(14, "auth_otp_max_attempts", "5", ConfigDataType.Int, "Wrong-code attempts allowed before OTP verification is refused until a fresh code."),
|
||||
(15, "auth_session_ttl_days", "30", ConfigDataType.Int, "Refresh-token session lifetime in days."),
|
||||
];
|
||||
|
||||
return rows
|
||||
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -9,5 +9,16 @@ internal class UserConfig:IEntityTypeConfiguration<User>
|
||||
public void Configure(EntityTypeBuilder<User> builder)
|
||||
{
|
||||
builder.ToTable("Users","usr").Property(p => p.Id).HasColumnName("UserId");
|
||||
|
||||
builder.Property(u => u.Gender).HasMaxLength(10);
|
||||
builder.Property(u => u.PhoneHash).HasMaxLength(64);
|
||||
builder.Property(u => u.IsActive).HasDefaultValue(false);
|
||||
|
||||
// One identity per phone. The unique index lives on the deterministic hash because the
|
||||
// encrypted phone column itself is non-deterministic ciphertext. Filtered: users without a
|
||||
// phone (internally provisioned admins) don't collide on NULL.
|
||||
builder.HasIndex(u => u.PhoneHash).IsUnique().HasFilter("[PhoneHash] IS NOT NULL");
|
||||
|
||||
builder.HasQueryFilter(u => u.DeletedAt == null);
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -1,4 +1,4 @@
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -11,6 +11,12 @@ internal class UserRoleConfig:IEntityTypeConfiguration<UserRole>
|
||||
|
||||
builder.HasOne(u => u.User).WithMany(u => u.UserRoles).HasForeignKey(u => u.UserId);
|
||||
builder.HasOne(u => u.Role).WithMany(u => u.Users).HasForeignKey(u => u.RoleId);
|
||||
builder.HasOne<User>().WithMany().HasForeignKey(u => u.GrantedById);
|
||||
|
||||
// Revoked grants are history, not membership: hiding them here makes every role read
|
||||
// (Identity's GetRoles, the JWT claims factory, /me) respect revocation automatically.
|
||||
builder.HasQueryFilter(ur => ur.RevokedAt == null);
|
||||
|
||||
builder.ToTable("UserRoles","usr");
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.Configuration.UserConfig;
|
||||
|
||||
internal sealed class UserSessionConfig : IEntityTypeConfiguration<UserSession>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<UserSession> builder)
|
||||
{
|
||||
builder.ToTable("UserSessions", "usr");
|
||||
|
||||
builder.Property(s => s.RefreshTokenHash).HasMaxLength(128).IsRequired();
|
||||
builder.Property(s => s.DeviceInfo).HasMaxLength(400);
|
||||
builder.Property(s => s.IpAddress).HasMaxLength(64);
|
||||
builder.Property(s => s.IsRevoked).HasDefaultValue(false);
|
||||
|
||||
// Rotation looks sessions up by the presented token's hash; revoke-all scans by (user, active).
|
||||
builder.HasIndex(s => s.RefreshTokenHash).IsUnique();
|
||||
builder.HasIndex(s => new { s.UserId, s.IsRevoked });
|
||||
|
||||
builder.HasOne(s => s.User).WithMany(u => u.Sessions).HasForeignKey(s => s.UserId);
|
||||
|
||||
// Mirrors the owner's soft-delete filter so a deleted user's sessions are unreachable.
|
||||
builder.HasQueryFilter(s => s.User.DeletedAt == null);
|
||||
}
|
||||
}
|
||||
+1015
File diff suppressed because it is too large
Load Diff
+280
@@ -0,0 +1,280 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class IdentitySessionsAndUserExtensions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "DeletedAt",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "datetimeoffset",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Gender",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "nvarchar(10)",
|
||||
maxLength: 10,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsActive",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "bit",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "NationalId",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "nvarchar(max)",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "NationalIdVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "datetimeoffset",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "PhoneHash",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "nvarchar(64)",
|
||||
maxLength: 64,
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "PhoneVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "datetimeoffset",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "ShahkarVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
type: "datetimeoffset",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "GrantedAt",
|
||||
schema: "usr",
|
||||
table: "UserRoles",
|
||||
type: "datetimeoffset",
|
||||
nullable: false,
|
||||
defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)));
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles",
|
||||
type: "int",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "RevokedAt",
|
||||
schema: "usr",
|
||||
table: "UserRoles",
|
||||
type: "datetimeoffset",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "UserSessions",
|
||||
schema: "usr",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
UserId = table.Column<int>(type: "int", nullable: false),
|
||||
RefreshTokenHash = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
|
||||
DeviceInfo = table.Column<string>(type: "nvarchar(400)", maxLength: 400, nullable: true),
|
||||
IpAddress = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
|
||||
IsRevoked = table.Column<bool>(type: "bit", nullable: false, defaultValue: false),
|
||||
RevokedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
|
||||
ExpiresAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
|
||||
ModifiedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
|
||||
CreatedById = table.Column<int>(type: "int", nullable: true),
|
||||
ModifiedById = table.Column<int>(type: "int", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_UserSessions", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_UserSessions_Users_UserId",
|
||||
column: x => x.UserId,
|
||||
principalSchema: "usr",
|
||||
principalTable: "Users",
|
||||
principalColumn: "UserId",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
schema: "ops",
|
||||
table: "PlatformConfigs",
|
||||
columns: new[] { "Id", "CreatedAt", "CreatedById", "DataType", "Description", "Key", "ModifiedAt", "ModifiedById", "Value" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ 13L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Seconds a phone must wait before another OTP can be requested.", "auth_otp_resend_seconds", null, null, "120" },
|
||||
{ 14L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Wrong-code attempts allowed before OTP verification is refused until a fresh code.", "auth_otp_max_attempts", null, null, "5" },
|
||||
{ 15L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Refresh-token session lifetime in days.", "auth_session_ttl_days", null, null, "30" }
|
||||
});
|
||||
|
||||
// Phone/email are encrypted at rest from this migration on, and reads now decrypt. Pre-b2
|
||||
// rows hold plaintext the decryptor would choke on — clear them (pre-launch dev/test
|
||||
// accounts only) and keep the seeded admin sign-in-able.
|
||||
migrationBuilder.Sql(
|
||||
"UPDATE [usr].[Users] SET [Email] = NULL, [NormalizedEmail] = NULL, [PhoneNumber] = NULL, [PhoneNumberConfirmed] = 0;");
|
||||
migrationBuilder.Sql(
|
||||
"UPDATE [usr].[Users] SET [IsActive] = 1 WHERE [UserName] = 'admin';");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Users_PhoneHash",
|
||||
schema: "usr",
|
||||
table: "Users",
|
||||
column: "PhoneHash",
|
||||
unique: true,
|
||||
filter: "[PhoneHash] IS NOT NULL");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserRoles_GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles",
|
||||
column: "GrantedById");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserSessions_RefreshTokenHash",
|
||||
schema: "usr",
|
||||
table: "UserSessions",
|
||||
column: "RefreshTokenHash",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserSessions_UserId_IsRevoked",
|
||||
schema: "usr",
|
||||
table: "UserSessions",
|
||||
columns: new[] { "UserId", "IsRevoked" });
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_UserRoles_Users_GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles",
|
||||
column: "GrantedById",
|
||||
principalSchema: "usr",
|
||||
principalTable: "Users",
|
||||
principalColumn: "UserId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_UserRoles_Users_GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "UserSessions",
|
||||
schema: "usr");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Users_PhoneHash",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_UserRoles_GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles");
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
schema: "ops",
|
||||
table: "PlatformConfigs",
|
||||
keyColumn: "Id",
|
||||
keyValue: 13L);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
schema: "ops",
|
||||
table: "PlatformConfigs",
|
||||
keyColumn: "Id",
|
||||
keyValue: 14L);
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
schema: "ops",
|
||||
table: "PlatformConfigs",
|
||||
keyColumn: "Id",
|
||||
keyValue: 15L);
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DeletedAt",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Gender",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsActive",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "NationalId",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "NationalIdVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PhoneHash",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PhoneVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ShahkarVerifiedAt",
|
||||
schema: "usr",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "GrantedAt",
|
||||
schema: "usr",
|
||||
table: "UserRoles");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "GrantedById",
|
||||
schema: "usr",
|
||||
table: "UserRoles");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RevokedAt",
|
||||
schema: "usr",
|
||||
table: "UserRoles");
|
||||
}
|
||||
}
|
||||
}
|
||||
+144
@@ -251,6 +251,33 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
Description = "Tiered cancellation refund policy: refund_percent by hours before the visit.",
|
||||
Key = "cancellation_tiers",
|
||||
Value = "[{\"min_hours_before\":48,\"refund_percent\":100},{\"min_hours_before\":24,\"refund_percent\":50},{\"min_hours_before\":0,\"refund_percent\":0}]"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 13L,
|
||||
CreatedAt = new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)),
|
||||
DataType = "int",
|
||||
Description = "Seconds a phone must wait before another OTP can be requested.",
|
||||
Key = "auth_otp_resend_seconds",
|
||||
Value = "120"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 14L,
|
||||
CreatedAt = new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)),
|
||||
DataType = "int",
|
||||
Description = "Wrong-code attempts allowed before OTP verification is refused until a fresh code.",
|
||||
Key = "auth_otp_max_attempts",
|
||||
Value = "5"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = 15L,
|
||||
CreatedAt = new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)),
|
||||
DataType = "int",
|
||||
Description = "Refresh-token session lifetime in days.",
|
||||
Key = "auth_session_ttl_days",
|
||||
Value = "30"
|
||||
});
|
||||
});
|
||||
|
||||
@@ -558,6 +585,9 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset?>("DeletedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
@@ -568,9 +598,18 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
b.Property<string>("FamilyName")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Gender")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("GeneratedCode")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bit")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
@@ -580,6 +619,12 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("NationalId")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset?>("NationalIdVerifiedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("nvarchar(256)");
|
||||
@@ -591,15 +636,25 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PhoneHash")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("nvarchar(64)");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTimeOffset?>("PhoneVerifiedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<DateTimeOffset?>("ShahkarVerifiedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("bit");
|
||||
|
||||
@@ -617,6 +672,10 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
.HasDatabaseName("UserNameIndex")
|
||||
.HasFilter("[NormalizedUserName] IS NOT NULL");
|
||||
|
||||
b.HasIndex("PhoneHash")
|
||||
.IsUnique()
|
||||
.HasFilter("[PhoneHash] IS NOT NULL");
|
||||
|
||||
b.ToTable("Users", "usr");
|
||||
});
|
||||
|
||||
@@ -710,13 +769,81 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
b.Property<DateTime>("CreatedUserRoleDate")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTimeOffset>("GrantedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<int?>("GrantedById")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.HasKey("UserId", "RoleId");
|
||||
|
||||
b.HasIndex("GrantedById");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.ToTable("UserRoles", "usr");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Baya.Domain.Entities.User.UserSession", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<int?>("CreatedById")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("DeviceInfo")
|
||||
.HasMaxLength(400)
|
||||
.HasColumnType("nvarchar(400)");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("nvarchar(64)");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bit")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<DateTimeOffset?>("ModifiedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<int?>("ModifiedById")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<string>("RefreshTokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("nvarchar(128)");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("datetimeoffset");
|
||||
|
||||
b.Property<int>("UserId")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RefreshTokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserId", "IsRevoked");
|
||||
|
||||
b.ToTable("UserSessions", "usr");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Baya.Domain.Entities.User.UserToken", b =>
|
||||
{
|
||||
b.Property<int>("UserId")
|
||||
@@ -815,6 +942,10 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
|
||||
modelBuilder.Entity("Baya.Domain.Entities.User.UserRole", b =>
|
||||
{
|
||||
b.HasOne("Baya.Domain.Entities.User.User", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("GrantedById");
|
||||
|
||||
b.HasOne("Baya.Domain.Entities.User.Role", "Role")
|
||||
.WithMany("Users")
|
||||
.HasForeignKey("RoleId")
|
||||
@@ -832,6 +963,17 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Baya.Domain.Entities.User.UserSession", b =>
|
||||
{
|
||||
b.HasOne("Baya.Domain.Entities.User.User", "User")
|
||||
.WithMany("Sessions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Baya.Domain.Entities.User.UserToken", b =>
|
||||
{
|
||||
b.HasOne("Baya.Domain.Entities.User.User", "User")
|
||||
@@ -856,6 +998,8 @@ namespace Baya.Infrastructure.Persistence.Migrations
|
||||
|
||||
b.Navigation("Logins");
|
||||
|
||||
b.Navigation("Sessions");
|
||||
|
||||
b.Navigation("Tokens");
|
||||
|
||||
b.Navigation("UserRefreshTokens");
|
||||
|
||||
+6
-2
@@ -1,17 +1,21 @@
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.Repositories.Common;
|
||||
|
||||
public class UnitOfWork : IUnitOfWork
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
|
||||
public IUserRefreshTokenRepository UserRefreshTokenRepository { get; }
|
||||
public IUserSessionRepository UserSessionRepository { get; }
|
||||
public IUserAccountRepository UserAccountRepository { get; }
|
||||
|
||||
public UnitOfWork(ApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
UserRefreshTokenRepository = new UserRefreshTokenRepository(_db);
|
||||
UserSessionRepository = new UserSessionRepository(_db);
|
||||
UserAccountRepository = new UserAccountRepository(_db);
|
||||
}
|
||||
|
||||
public Task CommitAsync()
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Application.Models.Identity;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Persistence.Repositories.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.Repositories;
|
||||
|
||||
internal class UserAccountRepository : BaseAsyncRepository<User>, IUserAccountRepository
|
||||
{
|
||||
public UserAccountRepository(ApplicationDbContext dbContext) : base(dbContext)
|
||||
{
|
||||
}
|
||||
|
||||
public Task<UserAccountSnapshot> GetAccountSnapshotAsync(int userId, CancellationToken cancellationToken)
|
||||
{
|
||||
// UserRoles carries a RevokedAt-is-null global filter, so revoked grants never surface here.
|
||||
return TableNoTracking
|
||||
.Where(u => u.Id == userId)
|
||||
.Select(u => new UserAccountSnapshot(
|
||||
u.Id,
|
||||
u.PhoneNumber,
|
||||
u.Name,
|
||||
u.FamilyName,
|
||||
u.Gender,
|
||||
u.IsActive,
|
||||
u.UserRoles.Select(ur => ur.Role.Name).ToList()))
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public Task<Role> GetRoleByNameAsync(string roleName, CancellationToken cancellationToken)
|
||||
{
|
||||
return DbContext.Set<Role>()
|
||||
.FirstOrDefaultAsync(r => r.Name == roleName, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<UserRole> GetUserRoleIncludingRevokedAsync(int userId, int roleId, CancellationToken cancellationToken)
|
||||
{
|
||||
// Bypasses the revoked-filter on purpose: a revoked grant must be re-activated, not
|
||||
// re-inserted (composite PK).
|
||||
return DbContext.Set<UserRole>()
|
||||
.IgnoreQueryFilters()
|
||||
.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task AddUserRoleAsync(UserRole userRole, CancellationToken cancellationToken)
|
||||
{
|
||||
await DbContext.Set<UserRole>().AddAsync(userRole, cancellationToken);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Persistence.Repositories.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.Repositories;
|
||||
|
||||
internal class UserSessionRepository : BaseAsyncRepository<UserSession>, IUserSessionRepository
|
||||
{
|
||||
public UserSessionRepository(ApplicationDbContext dbContext) : base(dbContext)
|
||||
{
|
||||
}
|
||||
|
||||
public Task AddAsync(UserSession session, CancellationToken cancellationToken)
|
||||
{
|
||||
return base.AddAsync(session);
|
||||
}
|
||||
|
||||
public Task<UserSession> GetByTokenHashAsync(string refreshTokenHash, CancellationToken cancellationToken)
|
||||
{
|
||||
return Table
|
||||
.Include(s => s.User)
|
||||
.FirstOrDefaultAsync(s => s.RefreshTokenHash == refreshTokenHash, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<UserSession> GetActiveForUserByTokenHashAsync(int userId, string refreshTokenHash, CancellationToken cancellationToken)
|
||||
{
|
||||
return Table.FirstOrDefaultAsync(
|
||||
s => s.UserId == userId && s.RefreshTokenHash == refreshTokenHash && !s.IsRevoked,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<int> RevokeAllActiveForUserAsync(int userId, DateTimeOffset revokedAt, CancellationToken cancellationToken)
|
||||
{
|
||||
// Sessions-per-user is small; tracked mutation keeps the revocation inside the caller's
|
||||
// single commit instead of an out-of-band ExecuteUpdate.
|
||||
var activeSessions = await Table
|
||||
.Where(s => s.UserId == userId && !s.IsRevoked)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var session in activeSessions)
|
||||
session.Revoke(revokedAt);
|
||||
|
||||
return activeSessions.Count;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace Baya.Infrastructure.Persistence.ValueConversion;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts a string column at rest through the <see cref="IFieldEncryptor"/> seam. The ciphertext is
|
||||
/// non-deterministic (random IV), so encrypted columns can never be equality-queried — lookups go
|
||||
/// through a deterministic companion hash column (e.g. <c>PhoneHash</c>) instead.
|
||||
/// </summary>
|
||||
internal sealed class EncryptedStringConverter(IFieldEncryptor fieldEncryptor)
|
||||
: ValueConverter<string, string>(
|
||||
plaintext => fieldEncryptor.Encrypt(plaintext),
|
||||
ciphertext => fieldEncryptor.Decrypt(ciphertext));
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Baya.Application.Contracts.Identity;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Shared plumbing for the auth flows: creates users + valid OTP codes through the real Identity
|
||||
/// services (so tests don't scrape logs or burn the OTP endpoint's rate-limit budget on setup), and
|
||||
/// unwraps the ApiResult envelope.
|
||||
/// </summary>
|
||||
internal static class AuthTestClient
|
||||
{
|
||||
public static async Task<string> CreateUserWithOtpCodeAsync(BayaApiFactory factory, string phone)
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var userManager = scope.ServiceProvider.GetRequiredService<IAppUserManager>();
|
||||
|
||||
var user = await userManager.GetUserByPhoneNumber(phone);
|
||||
if (user is null)
|
||||
{
|
||||
user = new User { UserName = $"u_{Guid.NewGuid():N}", PhoneNumber = phone };
|
||||
var created = await userManager.CreateUser(user);
|
||||
Assert.True(created.Succeeded, $"test user creation failed: {string.Join(",", created.Errors.Select(e => e.Description))}");
|
||||
}
|
||||
|
||||
// Same token family the verify endpoint checks: phone-confirmation token before the phone is
|
||||
// confirmed, passwordless TOTP afterwards.
|
||||
return user.PhoneNumberConfirmed
|
||||
? await userManager.GenerateOtpCode(user)
|
||||
: await userManager.GeneratePhoneNumberConfirmationToken(user, phone);
|
||||
}
|
||||
|
||||
/// <summary>Full endpoint login: mints a code, POSTs verify_otp, returns the token payload.</summary>
|
||||
public static async Task<JsonElement> LoginAsync(BayaApiFactory factory, HttpClient client, string phone)
|
||||
{
|
||||
var code = await CreateUserWithOtpCodeAsync(factory, phone);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/auth/verify_otp", new { phone, code });
|
||||
Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
return await ReadDataAsync(response);
|
||||
}
|
||||
|
||||
public static void UseBearer(HttpClient client, string accessToken) =>
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||
|
||||
/// <summary>Unwraps the ApiResult envelope and returns its <c>data</c> element.</summary>
|
||||
public static async Task<JsonElement> ReadDataAsync(HttpResponseMessage response)
|
||||
{
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.GetProperty("data").Clone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\API\Baya.Web.Api\Baya.Web.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,75 @@
|
||||
using Baya.Infrastructure.Identity.Identity.SeedDatabaseService;
|
||||
using Baya.Infrastructure.Persistence;
|
||||
using Baya.Infrastructure.Persistence.Interceptors;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Boots the whole API (Program.cs wiring: envelope filters, JWE auth, rate limiter, Mediator) in the
|
||||
/// "Testing" environment over an isolated in-memory SQLite database. Program skips SQL Server
|
||||
/// migrations/seeding for this environment; the factory does EnsureCreated + the role/admin seed.
|
||||
/// Use one factory per test class — the rate limiter is per-host, so a fresh host keeps each class
|
||||
/// inside the OTP/auth per-IP budgets.
|
||||
/// </summary>
|
||||
public sealed class BayaApiFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
// A named shared-cache in-memory database (kept alive by this connection) instead of a single
|
||||
// shared SqliteConnection instance: request scopes and hosted services open their own
|
||||
// connections, so nothing initializes one connection concurrently.
|
||||
private readonly string _connectionString =
|
||||
$"Data Source={Guid.NewGuid():N};Mode=Memory;Cache=Shared";
|
||||
|
||||
private readonly SqliteConnection _keepAlive;
|
||||
|
||||
public BayaApiFactory()
|
||||
{
|
||||
_keepAlive = new SqliteConnection(_connectionString);
|
||||
_keepAlive.Open();
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseEnvironment("Testing");
|
||||
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Swap the SQL Server DbContext for in-memory SQLite. EF 8+ keeps AddDbContext's
|
||||
// option lambda in IDbContextOptionsConfiguration — it must go too, or both providers
|
||||
// end up configured on the same options.
|
||||
services.RemoveAll(typeof(IDbContextOptionsConfiguration<ApplicationDbContext>));
|
||||
services.RemoveAll(typeof(DbContextOptions<ApplicationDbContext>));
|
||||
|
||||
services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
options
|
||||
.UseSqlite(_connectionString)
|
||||
.AddInterceptors(serviceProvider.GetRequiredService<AuditFieldInterceptor>());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected override IHost CreateHost(IHostBuilder builder)
|
||||
{
|
||||
var host = base.CreateHost(builder);
|
||||
|
||||
using var scope = host.Services.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.EnsureCreated();
|
||||
scope.ServiceProvider.GetRequiredService<ISeedDataBase>().Seed().GetAwaiter().GetResult();
|
||||
|
||||
return host;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
_keepAlive.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
public class OtpRequestTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task RequestOtp_ValidPhone_SendsOtpAndOpensResendWindow()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
|
||||
var first = await client.PostAsJsonAsync("/api/v1/auth/request_otp", new { phone = "09120000001" });
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
|
||||
var firstData = await AuthTestClient.ReadDataAsync(first);
|
||||
Assert.True(firstData.GetProperty("otpSent").GetBoolean());
|
||||
Assert.True(firstData.GetProperty("resendAvailableInSeconds").GetInt32() > 0);
|
||||
|
||||
// Same phone inside the resend window: same non-enumerating shape, otpSent=false.
|
||||
var second = await client.PostAsJsonAsync("/api/v1/auth/request_otp", new { phone = "09120000001" });
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, second.StatusCode);
|
||||
var secondData = await AuthTestClient.ReadDataAsync(second);
|
||||
Assert.False(secondData.GetProperty("otpSent").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestOtp_InvalidPhone_Returns400()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/auth/request_otp", new { phone = "12345" });
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
public class RefreshAndLogoutTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task Refresh_RotatesSession_AndReplayRevokesEverything()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
const string phone = "09120000030";
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, phone);
|
||||
var originalRefreshToken = tokens.GetProperty("refreshToken").GetString()!;
|
||||
|
||||
var rotated = await client.PostAsJsonAsync("/api/v1/auth/refresh", new { refreshToken = originalRefreshToken });
|
||||
Assert.Equal(HttpStatusCode.OK, rotated.StatusCode);
|
||||
var rotatedData = await AuthTestClient.ReadDataAsync(rotated);
|
||||
Assert.NotEqual(originalRefreshToken, rotatedData.GetProperty("refreshToken").GetString());
|
||||
|
||||
// Replaying the rotated-out token is stolen-token reuse: 401 and logout-everywhere.
|
||||
var replay = await client.PostAsJsonAsync("/api/v1/auth/refresh", new { refreshToken = originalRefreshToken });
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, replay.StatusCode);
|
||||
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var phoneHash = scope.ServiceProvider.GetRequiredService<IFieldEncryptor>().Hash(phone);
|
||||
var user = await db.Set<User>().SingleAsync(u => u.PhoneHash == phoneHash);
|
||||
var sessions = await db.Set<UserSession>().Where(s => s.UserId == user.Id).ToListAsync();
|
||||
|
||||
Assert.NotEmpty(sessions);
|
||||
Assert.All(sessions, s => Assert.True(s.IsRevoked));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Logout_RevokesSession_AndKillsAccessToken()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
const string phone = "09120000031";
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, phone);
|
||||
AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
|
||||
|
||||
var logout = await client.PostAsJsonAsync("/api/v1/auth/logout", new { });
|
||||
Assert.Equal(HttpStatusCode.OK, logout.StatusCode);
|
||||
|
||||
// Security-stamp rotation makes the still-unexpired access token fail server-side.
|
||||
var me = await client.GetAsync("/api/v1/me");
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, me.StatusCode);
|
||||
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var phoneHash = scope.ServiceProvider.GetRequiredService<IFieldEncryptor>().Hash(phone);
|
||||
var user = await db.Set<User>().SingleAsync(u => u.PhoneHash == phoneHash);
|
||||
var sessions = await db.Set<UserSession>().Where(s => s.UserId == user.Id).ToListAsync();
|
||||
|
||||
Assert.NotEmpty(sessions);
|
||||
Assert.All(sessions, s => Assert.True(s.IsRevoked));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
public class RoleSelectionTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task SelectRole_PublicRoles_AreGrantedIdempotentlyAndCanCoexist()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, "09120000020");
|
||||
AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
|
||||
|
||||
var customer = await client.PostAsJsonAsync("/api/v1/me/select_role", new { role = "customer" });
|
||||
Assert.Equal(HttpStatusCode.OK, customer.StatusCode);
|
||||
var afterCustomer = await AuthTestClient.ReadDataAsync(customer);
|
||||
Assert.Contains("customer", afterCustomer.GetProperty("roles").EnumerateArray().Select(r => r.GetString()));
|
||||
|
||||
// Selecting the same role again is an idempotent success.
|
||||
var repeat = await client.PostAsJsonAsync("/api/v1/me/select_role", new { role = "customer" });
|
||||
Assert.Equal(HttpStatusCode.OK, repeat.StatusCode);
|
||||
|
||||
// A user may hold customer and nurse at once.
|
||||
var nurse = await client.PostAsJsonAsync("/api/v1/me/select_role", new { role = "nurse" });
|
||||
Assert.Equal(HttpStatusCode.OK, nurse.StatusCode);
|
||||
var afterNurse = await AuthTestClient.ReadDataAsync(nurse);
|
||||
var roles = afterNurse.GetProperty("roles").EnumerateArray().Select(r => r.GetString()).ToList();
|
||||
Assert.Contains("customer", roles);
|
||||
Assert.Contains("nurse", roles);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SelectRole_AdminSubRole_Returns403()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, "09120000021");
|
||||
AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/me/select_role", new { role = "super_admin" });
|
||||
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
global using Xunit;
|
||||
@@ -0,0 +1,80 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Baya.Test.Api;
|
||||
|
||||
public class VerifyOtpAndMeTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task VerifyOtp_ValidCode_MintsTokensAndCreatesSession()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
const string phone = "09120000010";
|
||||
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, phone);
|
||||
|
||||
Assert.False(string.IsNullOrEmpty(tokens.GetProperty("accessToken").GetString()));
|
||||
Assert.False(string.IsNullOrEmpty(tokens.GetProperty("refreshToken").GetString()));
|
||||
Assert.True(tokens.GetProperty("isNewUser").GetBoolean());
|
||||
Assert.Empty(tokens.GetProperty("roles").EnumerateArray());
|
||||
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var phoneHash = scope.ServiceProvider.GetRequiredService<IFieldEncryptor>().Hash(phone);
|
||||
var user = await db.Set<User>().SingleAsync(u => u.PhoneHash == phoneHash);
|
||||
|
||||
Assert.True(user.IsActive);
|
||||
Assert.NotNull(user.PhoneVerifiedAt);
|
||||
var session = await db.Set<UserSession>().SingleAsync(s => s.UserId == user.Id);
|
||||
Assert.False(session.IsRevoked);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyOtp_WrongCode_Returns400()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
const string phone = "09120000011";
|
||||
await AuthTestClient.CreateUserWithOtpCodeAsync(factory, phone);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/auth/verify_otp", new { phone, code = "000000" });
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Me_WithoutToken_Returns401()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/api/v1/me");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Me_WithToken_ReturnsMaskedPhoneAndDefaults()
|
||||
{
|
||||
var client = factory.CreateClient();
|
||||
const string phone = "09120000012";
|
||||
var tokens = await AuthTestClient.LoginAsync(factory, client, phone);
|
||||
AuthTestClient.UseBearer(client, tokens.GetProperty("accessToken").GetString()!);
|
||||
|
||||
var response = await client.GetAsync("/api/v1/me");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var me = await AuthTestClient.ReadDataAsync(response);
|
||||
var maskedPhone = me.GetProperty("phone").GetString()!;
|
||||
Assert.StartsWith("0912", maskedPhone);
|
||||
Assert.Contains('*', maskedPhone);
|
||||
Assert.DoesNotContain(phone, maskedPhone);
|
||||
Assert.Empty(me.GetProperty("roles").EnumerateArray());
|
||||
Assert.False(me.GetProperty("hasCustomerProfile").GetBoolean());
|
||||
Assert.False(me.GetProperty("hasNurseProfile").GetBoolean());
|
||||
Assert.Equal("not_started", me.GetProperty("nurseVerificationStatus").GetString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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.Features.Identity;
|
||||
using Baya.Application.Features.Identity.Commands.RefreshToken;
|
||||
using Baya.Application.Models.Jwt;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
|
||||
namespace Baya.Test.Foundation.Identity;
|
||||
|
||||
public class RefreshTokenCommandHandlerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 7, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
|
||||
private readonly IUserSessionRepository _sessions = Substitute.For<IUserSessionRepository>();
|
||||
private readonly IJwtService _jwtService = Substitute.For<IJwtService>();
|
||||
private readonly IAppUserManager _userManager = Substitute.For<IAppUserManager>();
|
||||
private readonly IPlatformConfig _platformConfig = Substitute.For<IPlatformConfig>();
|
||||
private readonly IFieldEncryptor _fieldEncryptor = Substitute.For<IFieldEncryptor>();
|
||||
private readonly IDateTimeProvider _clock = Substitute.For<IDateTimeProvider>();
|
||||
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
|
||||
|
||||
private RefreshTokenCommandHandler CreateHandler()
|
||||
{
|
||||
_clock.UtcNow.Returns(Now);
|
||||
_unitOfWork.UserSessionRepository.Returns(_sessions);
|
||||
_fieldEncryptor.Hash(Arg.Any<string>()).Returns("TOKEN_HASH");
|
||||
_platformConfig.GetConfig<int>(IdentityDefaults.SessionTtlDaysKey, Arg.Any<CancellationToken>()).Returns(30);
|
||||
_jwtService.GenerateAccessTokenAsync(Arg.Any<User>())
|
||||
.Returns(new JweAccessToken("new-access-token", Now.AddMinutes(15)));
|
||||
|
||||
return new RefreshTokenCommandHandler(
|
||||
_unitOfWork, _jwtService, _userManager, _platformConfig, _fieldEncryptor, _clock, _currentUser,
|
||||
NullLogger<RefreshTokenCommandHandler>.Instance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ActiveSession_RotatesAndReturnsNewPair()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { Id = 7, IsActive = true };
|
||||
var session = new UserSession
|
||||
{
|
||||
UserId = 7,
|
||||
User = user,
|
||||
RefreshTokenHash = "TOKEN_HASH",
|
||||
ExpiresAt = Now.AddDays(10)
|
||||
};
|
||||
_sessions.GetByTokenHashAsync("TOKEN_HASH", Arg.Any<CancellationToken>()).Returns(session);
|
||||
_userManager.GetRoleAsync(user).Returns(["customer"]);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RefreshTokenCommand("raw-refresh-token"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.True(session.IsRevoked);
|
||||
Assert.Equal(Now, session.RevokedAt);
|
||||
Assert.Equal("new-access-token", result.Result.AccessToken);
|
||||
Assert.Contains("customer", result.Result.Roles);
|
||||
await _sessions.Received(1).AddAsync(Arg.Is<UserSession>(s => !s.IsRevoked && s.UserId == 7), Arg.Any<CancellationToken>());
|
||||
await _unitOfWork.Received(1).CommitAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_RevokedSessionReplay_RevokesEverythingAndReturns401()
|
||||
{
|
||||
// Arrange — a token presented against an already-rotated session is a stolen-token signal.
|
||||
var session = new UserSession { UserId = 7, RefreshTokenHash = "TOKEN_HASH", IsRevoked = true, ExpiresAt = Now.AddDays(10) };
|
||||
_sessions.GetByTokenHashAsync("TOKEN_HASH", Arg.Any<CancellationToken>()).Returns(session);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RefreshTokenCommand("raw-refresh-token"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.True(result.IsUnauthorized);
|
||||
await _sessions.Received(1).RevokeAllActiveForUserAsync(7, Now, Arg.Any<CancellationToken>());
|
||||
await _sessions.DidNotReceive().AddAsync(Arg.Any<UserSession>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ExpiredSession_Returns401AndRevokesIt()
|
||||
{
|
||||
// Arrange
|
||||
var session = new UserSession { UserId = 7, RefreshTokenHash = "TOKEN_HASH", ExpiresAt = Now.AddMinutes(-1) };
|
||||
_sessions.GetByTokenHashAsync("TOKEN_HASH", Arg.Any<CancellationToken>()).Returns(session);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RefreshTokenCommand("raw-refresh-token"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsUnauthorized);
|
||||
Assert.True(session.IsRevoked);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_UnknownToken_Returns401()
|
||||
{
|
||||
// Arrange
|
||||
_sessions.GetByTokenHashAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).ReturnsNull();
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RefreshTokenCommand("bogus"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsUnauthorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Application.Contracts.Configuration;
|
||||
using Baya.Application.Contracts.Identity;
|
||||
using Baya.Application.Features.Identity;
|
||||
using Baya.Application.Features.Identity.Commands.RequestOtp;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
|
||||
namespace Baya.Test.Foundation.Identity;
|
||||
|
||||
public class RequestOtpCommandHandlerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 7, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly IAppUserManager _userManager = Substitute.For<IAppUserManager>();
|
||||
private readonly ISmsSender _smsSender = Substitute.For<ISmsSender>();
|
||||
private readonly IPlatformConfig _platformConfig = Substitute.For<IPlatformConfig>();
|
||||
private readonly ICacheService _cache = Substitute.For<ICacheService>();
|
||||
private readonly IFieldEncryptor _fieldEncryptor = Substitute.For<IFieldEncryptor>();
|
||||
private readonly IDateTimeProvider _clock = Substitute.For<IDateTimeProvider>();
|
||||
|
||||
private RequestOtpCommandHandler CreateHandler()
|
||||
{
|
||||
_clock.UtcNow.Returns(Now);
|
||||
_fieldEncryptor.Hash(Arg.Any<string>()).Returns("PHONE_HASH");
|
||||
_platformConfig.GetConfig<int>(IdentityDefaults.OtpResendSecondsKey, Arg.Any<CancellationToken>())
|
||||
.Returns(120);
|
||||
|
||||
return new RequestOtpCommandHandler(_userManager, _smsSender, _platformConfig, _cache, _fieldEncryptor, _clock);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NewPhone_CreatesInactiveUserAndSendsOtp()
|
||||
{
|
||||
// Arrange
|
||||
_userManager.GetUserByPhoneNumber("09123456789").ReturnsNull();
|
||||
_userManager.CreateUser(Arg.Any<User>()).Returns(IdentityResult.Success);
|
||||
_userManager.GeneratePhoneNumberConfirmationToken(Arg.Any<User>(), "09123456789").Returns("123456");
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RequestOtpCommand("09123456789"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.True(result.Result.OtpSent);
|
||||
Assert.Equal(120, result.Result.ResendAvailableInSeconds);
|
||||
await _userManager.Received(1).CreateUser(Arg.Is<User>(u => !u.IsActive && u.PhoneNumber == "09123456789"));
|
||||
await _smsSender.Received(1).SendOtpAsync("09123456789", "123456", Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ResendWindowOpen_DoesNotSendAndReportsRemainingSeconds()
|
||||
{
|
||||
// Arrange
|
||||
_cache.GetAsync<DateTimeOffset>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Now.AddSeconds(60));
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RequestOtpCommand("09123456789"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.False(result.Result.OtpSent);
|
||||
Assert.Equal(60, result.Result.ResendAvailableInSeconds);
|
||||
await _smsSender.DidNotReceive().SendOtpAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ExistingConfirmedUser_UsesPasswordlessOtpAndSameShape()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { PhoneNumber = "09123456789", PhoneNumberConfirmed = true };
|
||||
_userManager.GetUserByPhoneNumber("09123456789").Returns(user);
|
||||
_userManager.GenerateOtpCode(user).Returns("654321");
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new RequestOtpCommand("+989123456789"), CancellationToken.None);
|
||||
|
||||
// Assert — normalized phone, no enumeration (same shape as the new-user path).
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.True(result.Result.OtpSent);
|
||||
await _smsSender.Received(1).SendOtpAsync("09123456789", "654321", Arg.Any<CancellationToken>());
|
||||
await _userManager.DidNotReceive().CreateUser(Arg.Any<User>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Application.Features.Identity.Commands.SelectRole;
|
||||
using Baya.Application.Models.Identity;
|
||||
using Baya.Domain.Entities.User;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
|
||||
namespace Baya.Test.Foundation.Identity;
|
||||
|
||||
public class SelectRoleCommandHandlerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 7, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
|
||||
private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
|
||||
private readonly IUserAccountRepository _accounts = Substitute.For<IUserAccountRepository>();
|
||||
private readonly IDateTimeProvider _clock = Substitute.For<IDateTimeProvider>();
|
||||
|
||||
private SelectRoleCommandHandler CreateHandler()
|
||||
{
|
||||
_clock.UtcNow.Returns(Now);
|
||||
_currentUser.UserId.Returns(7);
|
||||
_unitOfWork.UserAccountRepository.Returns(_accounts);
|
||||
_accounts.GetAccountSnapshotAsync(7, Arg.Any<CancellationToken>())
|
||||
.Returns(new UserAccountSnapshot(7, "09123456789", null, null, null, true, ["customer"]));
|
||||
|
||||
return new SelectRoleCommandHandler(_currentUser, _unitOfWork, _clock);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_AdminSubRole_IsForbidden()
|
||||
{
|
||||
// Arrange
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new SelectRoleCommand("super_admin"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.True(result.IsForbidden);
|
||||
await _accounts.DidNotReceive().AddUserRoleAsync(Arg.Any<UserRole>(), Arg.Any<CancellationToken>());
|
||||
await _unitOfWork.DidNotReceive().CommitAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NewCustomerRole_GrantsWithSelfAudit()
|
||||
{
|
||||
// Arrange
|
||||
_accounts.GetRoleByNameAsync("customer", Arg.Any<CancellationToken>()).Returns(new Role { Id = 3, Name = "customer" });
|
||||
_accounts.GetUserRoleIncludingRevokedAsync(7, 3, Arg.Any<CancellationToken>()).ReturnsNull();
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new SelectRoleCommand("Customer"), CancellationToken.None);
|
||||
|
||||
// Assert — case-insensitive input, granted_by = self, masked phone in the payload.
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Contains("customer", result.Result.Roles);
|
||||
Assert.DoesNotContain("09123456789", result.Result.Phone);
|
||||
await _accounts.Received(1).AddUserRoleAsync(
|
||||
Arg.Is<UserRole>(ur => ur.UserId == 7 && ur.RoleId == 3 && ur.GrantedById == 7 && ur.GrantedAt == Now),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _unitOfWork.Received(1).CommitAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_RoleAlreadyHeld_IsIdempotent()
|
||||
{
|
||||
// Arrange
|
||||
_accounts.GetRoleByNameAsync("customer", Arg.Any<CancellationToken>()).Returns(new Role { Id = 3, Name = "customer" });
|
||||
_accounts.GetUserRoleIncludingRevokedAsync(7, 3, Arg.Any<CancellationToken>())
|
||||
.Returns(new UserRole { UserId = 7, RoleId = 3, GrantedAt = Now.AddDays(-1) });
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new SelectRoleCommand("customer"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
await _accounts.DidNotReceive().AddUserRoleAsync(Arg.Any<UserRole>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_RevokedGrant_IsReactivatedNotDuplicated()
|
||||
{
|
||||
// Arrange
|
||||
var revoked = new UserRole { UserId = 7, RoleId = 3, GrantedAt = Now.AddDays(-10), RevokedAt = Now.AddDays(-5) };
|
||||
_accounts.GetRoleByNameAsync("nurse", Arg.Any<CancellationToken>()).Returns(new Role { Id = 3, Name = "nurse" });
|
||||
_accounts.GetUserRoleIncludingRevokedAsync(7, 3, Arg.Any<CancellationToken>()).Returns(revoked);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new SelectRoleCommand("nurse"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Null(revoked.RevokedAt);
|
||||
Assert.Equal(Now, revoked.GrantedAt);
|
||||
Assert.Equal(7, revoked.GrantedById);
|
||||
await _accounts.DidNotReceive().AddUserRoleAsync(Arg.Any<UserRole>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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.Features.Identity;
|
||||
using Baya.Application.Features.Identity.Commands.VerifyOtp;
|
||||
using Baya.Application.Models.Jwt;
|
||||
using Baya.Domain.Entities.User;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ReturnsExtensions;
|
||||
|
||||
namespace Baya.Test.Foundation.Identity;
|
||||
|
||||
public class VerifyOtpCommandHandlerTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 7, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly IAppUserManager _userManager = Substitute.For<IAppUserManager>();
|
||||
private readonly IJwtService _jwtService = Substitute.For<IJwtService>();
|
||||
private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
|
||||
private readonly IUserSessionRepository _sessions = Substitute.For<IUserSessionRepository>();
|
||||
private readonly IPlatformConfig _platformConfig = Substitute.For<IPlatformConfig>();
|
||||
private readonly IFieldEncryptor _fieldEncryptor = Substitute.For<IFieldEncryptor>();
|
||||
private readonly IDateTimeProvider _clock = Substitute.For<IDateTimeProvider>();
|
||||
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
|
||||
|
||||
private VerifyOtpCommandHandler CreateHandler()
|
||||
{
|
||||
_clock.UtcNow.Returns(Now);
|
||||
_unitOfWork.UserSessionRepository.Returns(_sessions);
|
||||
_fieldEncryptor.Hash(Arg.Any<string>()).Returns("TOKEN_HASH");
|
||||
_platformConfig.GetConfig<int>(IdentityDefaults.OtpMaxAttemptsKey, Arg.Any<CancellationToken>()).Returns(5);
|
||||
_platformConfig.GetConfig<int>(IdentityDefaults.SessionTtlDaysKey, Arg.Any<CancellationToken>()).Returns(30);
|
||||
_jwtService.GenerateAccessTokenAsync(Arg.Any<User>())
|
||||
.Returns(new JweAccessToken("jwe-access-token", Now.AddMinutes(15)));
|
||||
|
||||
return new VerifyOtpCommandHandler(
|
||||
_userManager, _jwtService, _unitOfWork, _platformConfig, _fieldEncryptor, _clock, _currentUser);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ValidCodeForNewUser_ActivatesUserMintsTokensAndSession()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { PhoneNumber = "09123456789", PhoneNumberConfirmed = false };
|
||||
_userManager.GetUserByPhoneNumber("09123456789").Returns(user);
|
||||
_userManager.ChangePhoneNumber(user, "09123456789", "123456").Returns(IdentityResult.Success);
|
||||
_userManager.GetRoleAsync(user).Returns([]);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new VerifyOtpCommand("09123456789", "123456", "test-device"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.True(result.Result.IsNewUser);
|
||||
Assert.Empty(result.Result.Roles);
|
||||
Assert.Equal("jwe-access-token", result.Result.AccessToken);
|
||||
Assert.False(string.IsNullOrEmpty(result.Result.RefreshToken));
|
||||
Assert.Equal(Now.AddDays(30), result.Result.RefreshExpiresAt);
|
||||
Assert.True(user.IsActive);
|
||||
Assert.Equal(Now, user.PhoneVerifiedAt);
|
||||
await _sessions.Received(1).AddAsync(
|
||||
Arg.Is<UserSession>(s => s.RefreshTokenHash == "TOKEN_HASH" && !s.IsRevoked && s.DeviceInfo == "test-device"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _unitOfWork.Received(1).CommitAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WrongCode_IncrementsAttemptsAndFailsSafely()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { PhoneNumber = "09123456789", PhoneNumberConfirmed = true };
|
||||
_userManager.GetUserByPhoneNumber("09123456789").Returns(user);
|
||||
_userManager.VerifyUserCode(user, "999999")
|
||||
.Returns(IdentityResult.Failed(new IdentityError { Description = "Incorrect Code" }));
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new VerifyOtpCommand("09123456789", "999999"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsSuccess);
|
||||
await _userManager.Received(1).IncrementAccessFailedCountAsync(user);
|
||||
await _sessions.DidNotReceive().AddAsync(Arg.Any<UserSession>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_TooManyFailedAttempts_RefusesWithoutCheckingTheCode()
|
||||
{
|
||||
// Arrange
|
||||
var user = new User { PhoneNumber = "09123456789", PhoneNumberConfirmed = true, AccessFailedCount = 5 };
|
||||
_userManager.GetUserByPhoneNumber("09123456789").Returns(user);
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new VerifyOtpCommand("09123456789", "123456"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsSuccess);
|
||||
await _userManager.DidNotReceive().VerifyUserCode(Arg.Any<User>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_UnknownPhone_FailsWithTheSameSafeMessageAsAWrongCode()
|
||||
{
|
||||
// Arrange — no enumeration: unknown phone and wrong code are indistinguishable.
|
||||
_userManager.GetUserByPhoneNumber(Arg.Any<string>()).ReturnsNull();
|
||||
var handler = CreateHandler();
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(new VerifyOtpCommand("09123456789", "123456"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Contains(result.ErrorMessages, e => e.Value.Contains("invalid or expired", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Baya.Domain.Entities.User;
|
||||
using Baya.Infrastructure.CrossCutting.Seams;
|
||||
using Baya.Infrastructure.Persistence;
|
||||
using Baya.Infrastructure.Persistence.Interceptors;
|
||||
using Baya.Tests.Setup.Setups;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
@@ -36,7 +37,7 @@ internal sealed class OpsTestHost : IDisposable
|
||||
.AddInterceptors(interceptor)
|
||||
.Options;
|
||||
|
||||
Db = new ApplicationDbContext(options);
|
||||
Db = new ApplicationDbContext(options, TestFieldEncryptor.Instance);
|
||||
Db.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
@@ -66,4 +67,5 @@ internal sealed class TestCurrentUser : ICurrentUser
|
||||
public int? UserId { get; set; }
|
||||
public bool IsAuthenticated => UserId is not null;
|
||||
public IReadOnlyList<string> Roles { get; set; } = [];
|
||||
public string? IpAddress { get; set; }
|
||||
}
|
||||
|
||||
@@ -18,6 +18,6 @@ public abstract class TestApplicationDbContext
|
||||
.UseSqlite(connection)
|
||||
.Options;
|
||||
|
||||
UnitTestDbContext = new ApplicationDbContext(options);
|
||||
UnitTestDbContext = new ApplicationDbContext(options, TestFieldEncryptor.Instance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Baya.Application.Contracts.Common;
|
||||
|
||||
namespace Baya.Tests.Setup.Setups;
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic-key <see cref="IFieldEncryptor"/> for tests: reversible base64 "encryption" plus an
|
||||
/// HMAC lookup hash. Exposed as a single shared instance because EF caches the model (and therefore
|
||||
/// the value converters built from the encryptor) — every test context must use the same instance,
|
||||
/// mirroring the production singleton registration.
|
||||
/// </summary>
|
||||
public sealed class TestFieldEncryptor : IFieldEncryptor
|
||||
{
|
||||
public static readonly TestFieldEncryptor Instance = new();
|
||||
|
||||
private static readonly byte[] HashKey = "test-field-hash-key"u8.ToArray();
|
||||
|
||||
private TestFieldEncryptor()
|
||||
{
|
||||
}
|
||||
|
||||
public string Encrypt(string plaintext) =>
|
||||
string.IsNullOrEmpty(plaintext) ? plaintext : Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext));
|
||||
|
||||
public string Decrypt(string ciphertext) =>
|
||||
string.IsNullOrEmpty(ciphertext) ? ciphertext : Encoding.UTF8.GetString(Convert.FromBase64String(ciphertext));
|
||||
|
||||
public string Hash(string value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return value;
|
||||
|
||||
using var hmac = new HMACSHA256(HashKey);
|
||||
return Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes(value)));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Baya.Application.Contracts;
|
||||
using Baya.Application.Contracts.Common;
|
||||
using Baya.Application.Contracts.Identity;
|
||||
using Baya.Application.Contracts.Persistence;
|
||||
using Baya.Domain.Entities.User;
|
||||
@@ -33,6 +34,7 @@ public abstract class TestIdentitySetup
|
||||
|
||||
serviceCollection.AddLogging();
|
||||
|
||||
serviceCollection.AddSingleton<IFieldEncryptor>(TestFieldEncryptor.Instance);
|
||||
serviceCollection.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(connection));
|
||||
|
||||
var context = serviceCollection.BuildServiceProvider().GetService<ApplicationDbContext>();
|
||||
|
||||
Reference in New Issue
Block a user