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:
+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));
|
||||
Reference in New Issue
Block a user