| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Anichron.API.Settings; |
| | | 3 | | using Anichron.Core.Data; |
| | | 4 | | using Anichron.Core.Data.Repository; |
| | | 5 | | using Anichron.Core.Domain; |
| | | 6 | | using Microsoft.Extensions.Options; |
| | | 7 | | using System.Security.Cryptography; |
| | | 8 | | |
| | | 9 | | namespace Anichron.API.Services; |
| | | 10 | | |
| | | 11 | | public interface ITokenService |
| | | 12 | | { |
| | | 13 | | Task<AuthTokens> IssueAsync(User user, CancellationToken ct); |
| | | 14 | | Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync(string rawToken, CancellationToken ct); |
| | | 15 | | Task RevokeAsync(string rawToken, CancellationToken ct); |
| | | 16 | | Task MarkAllSessionsRevokedAsync(Guid userId, Instant revokedAt, CancellationToken ct); |
| | | 17 | | } |
| | | 18 | | |
| | 29 | 19 | | public sealed class TokenService( |
| | 29 | 20 | | IRefreshTokenRepository tokens, |
| | 29 | 21 | | IUserStorageConfigRepository storageConfigs, |
| | 29 | 22 | | IUnitOfWork unitOfWork, |
| | 29 | 23 | | IClock clock, |
| | 29 | 24 | | IGuidFactory guidFactory, |
| | 29 | 25 | | IOptions<JwtSettings> options, |
| | 29 | 26 | | IJwtFactory jwtFactory) : ITokenService |
| | | 27 | | { |
| | 6 | 28 | | private static Duration JustRotatedWindow => Duration.FromSeconds(30); |
| | | 29 | | |
| | 29 | 30 | | private readonly JwtSettings settings = options.Value; |
| | | 31 | | |
| | | 32 | | public async Task<AuthTokens> IssueAsync(User user, CancellationToken ct) |
| | 7 | 33 | | { |
| | 7 | 34 | | var (stored, issued) = await NewSessionAsync(user, ct); |
| | 7 | 35 | | tokens.Add(stored); |
| | 7 | 36 | | return issued; |
| | 7 | 37 | | } |
| | | 38 | | |
| | | 39 | | public Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync(string rawToken, CancellationToken ct) |
| | 18 | 40 | | => RefreshAsync(HashToken(rawToken), retryALostRotation: true, ct); |
| | | 41 | | |
| | | 42 | | private async Task<ServiceResult<AuthTokens, IRefreshError>> RefreshAsync( |
| | | 43 | | string tokenHash, bool retryALostRotation, CancellationToken ct) |
| | 20 | 44 | | { |
| | 20 | 45 | | var now = clock.GetCurrentInstant(); |
| | | 46 | | |
| | 20 | 47 | | var stored = await tokens.FindByHashWithUserAsync(tokenHash, ct); |
| | | 48 | | |
| | 20 | 49 | | if (stored is null) |
| | 1 | 50 | | return new RefreshTokenInvalid(); |
| | | 51 | | |
| | 19 | 52 | | var rotating = stored.RevokedAt is { } revokedAt ? JustRotatedInto(stored, revokedAt, now) : stored; |
| | 19 | 53 | | if (rotating is null) |
| | 3 | 54 | | return await RevokeEverySessionAsync(stored.UserId, now, ct); |
| | | 55 | | |
| | 16 | 56 | | if (stored.ExpiresAt <= now) |
| | 2 | 57 | | return new RefreshTokenInvalid(); |
| | | 58 | | |
| | 14 | 59 | | if (stored.User.IsDisabled) |
| | 2 | 60 | | return new AccountDisabled(); |
| | | 61 | | |
| | 12 | 62 | | if (stored.User.LockedUntil is { } lockedUntil && lockedUntil > now) |
| | 1 | 63 | | return new AccountLocked(Math.Max(1, (int)Math.Ceiling((lockedUntil - now).TotalSeconds))); |
| | | 64 | | |
| | 11 | 65 | | var (successor, issued) = await NewSessionAsync(stored.User, ct); |
| | 11 | 66 | | if (await tokens.RotateAsync(rotating.Id, successor, ct) == TokenRotation.Rotated) |
| | 6 | 67 | | return issued; |
| | | 68 | | |
| | 4 | 69 | | if (retryALostRotation && rotating == stored) |
| | 2 | 70 | | return await RefreshAsync(tokenHash, retryALostRotation: false, ct); |
| | | 71 | | |
| | 2 | 72 | | return await RevokeEverySessionAsync(stored.UserId, now, ct); |
| | 19 | 73 | | } |
| | | 74 | | |
| | | 75 | | private static RefreshToken? JustRotatedInto(RefreshToken stored, Instant revokedAt, Instant now) |
| | 8 | 76 | | => stored.ReplacedBy is { RevokedAt: null } successor && now - revokedAt <= JustRotatedWindow ? successor : null |
| | | 77 | | |
| | | 78 | | private async Task<ServiceResult<AuthTokens, IRefreshError>> RevokeEverySessionAsync(Guid userId, Instant now, Cance |
| | 5 | 79 | | { |
| | 5 | 80 | | await tokens.RevokeAllActiveByUserIdAsync(userId, now, ct); |
| | 5 | 81 | | return new RefreshTokenInvalid(); |
| | 5 | 82 | | } |
| | | 83 | | |
| | | 84 | | private async Task<(RefreshToken Stored, AuthTokens Issued)> NewSessionAsync(User user, CancellationToken ct) |
| | 18 | 85 | | { |
| | 18 | 86 | | var rawToken = GenerateRefreshToken(); |
| | 18 | 87 | | var now = clock.GetCurrentInstant(); |
| | | 88 | | |
| | 18 | 89 | | var stored = new RefreshToken |
| | 18 | 90 | | { |
| | 18 | 91 | | Id = guidFactory.NewGuid(), |
| | 18 | 92 | | UserId = user.Id, |
| | 18 | 93 | | TokenHash = HashToken(rawToken), |
| | 18 | 94 | | CreatedAt = now, |
| | 18 | 95 | | ExpiresAt = now.Plus(Duration.FromDays(settings.RefreshTokenDays)), |
| | 18 | 96 | | }; |
| | | 97 | | |
| | 18 | 98 | | var hasStorageConfig = await storageConfigs.AnyActiveByUserIdAsync(user.Id, ct); |
| | 18 | 99 | | return (stored, new AuthTokens(jwtFactory.Create(user), rawToken, settings.AccessTokenLifetime, user, hasStorage |
| | 18 | 100 | | } |
| | | 101 | | |
| | | 102 | | public async Task RevokeAsync(string rawToken, CancellationToken ct) |
| | 3 | 103 | | { |
| | 3 | 104 | | var tokenHash = HashToken(rawToken); |
| | 3 | 105 | | var stored = await tokens.FindByHashAsync(tokenHash, ct); |
| | 3 | 106 | | if (stored is null) |
| | 1 | 107 | | return; |
| | 2 | 108 | | if (stored.RevokedAt.HasValue) |
| | 1 | 109 | | return; |
| | | 110 | | |
| | 1 | 111 | | stored.RevokedAt = clock.GetCurrentInstant(); |
| | 1 | 112 | | await unitOfWork.SaveChangesAsync(ct); |
| | 3 | 113 | | } |
| | | 114 | | |
| | | 115 | | public Task MarkAllSessionsRevokedAsync(Guid userId, Instant revokedAt, CancellationToken ct) |
| | 1 | 116 | | => tokens.RevokeAllActiveByUserIdAsync(userId, revokedAt, ct); |
| | | 117 | | |
| | | 118 | | private static string GenerateRefreshToken() |
| | 18 | 119 | | => Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)); |
| | | 120 | | |
| | | 121 | | private static string HashToken(string rawToken) |
| | 39 | 122 | | => Convert.ToBase64String(SHA256.HashData(Convert.FromBase64String(rawToken))); |
| | | 123 | | } |