| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Anichron.Core.Data; |
| | | 3 | | using Anichron.Core.Data.Repository; |
| | | 4 | | using System.Security.Cryptography; |
| | | 5 | | |
| | | 6 | | namespace Anichron.API.Services; |
| | | 7 | | |
| | | 8 | | public sealed record AdminUserPasswordReset(string TemporaryPassword); |
| | | 9 | | |
| | | 10 | | public interface IAdminResetService |
| | | 11 | | { |
| | | 12 | | Task<AdminUserPasswordReset?> ResetUserPasswordAsync(Guid userId, CancellationToken ct); |
| | | 13 | | } |
| | | 14 | | |
| | 6 | 15 | | public sealed class AdminResetService( |
| | 6 | 16 | | IUserRepository users, |
| | 6 | 17 | | IUnitOfWork unitOfWork, |
| | 6 | 18 | | IClock clock, |
| | 6 | 19 | | IPasswordHasher passwordHasher, |
| | 6 | 20 | | ITokenService tokenService) : IAdminResetService |
| | | 21 | | { |
| | | 22 | | public async Task<AdminUserPasswordReset?> ResetUserPasswordAsync(Guid userId, CancellationToken ct) |
| | 6 | 23 | | { |
| | 6 | 24 | | var user = await users.FindByIdAsync(userId, ct); |
| | 6 | 25 | | if (user is null) |
| | 1 | 26 | | return null; |
| | | 27 | | |
| | 5 | 28 | | var temporaryPassword = Convert.ToBase64String(RandomNumberGenerator.GetBytes(12)); |
| | 5 | 29 | | user.PasswordHash = passwordHasher.Hash(temporaryPassword); |
| | 5 | 30 | | user.MustChangePassword = true; |
| | 5 | 31 | | var now = clock.GetCurrentInstant(); |
| | | 32 | | |
| | 5 | 33 | | await unitOfWork.ExecuteInTransactionAsync(async () => |
| | 5 | 34 | | { |
| | 5 | 35 | | await tokenService.MarkAllSessionsRevokedAsync(userId, now, ct); |
| | 5 | 36 | | await unitOfWork.SaveChangesAsync(ct); |
| | 5 | 37 | | }, ct); |
| | | 38 | | |
| | 5 | 39 | | return new AdminUserPasswordReset(temporaryPassword); |
| | 6 | 40 | | } |
| | | 41 | | } |