From 470031af39fb36c4068a36d87b2f46822243e27a Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Wed, 29 May 2024 05:27:49 +0300 Subject: [PATCH] feat: add match token --- Security/Services/PreAuthService.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Security/Services/PreAuthService.cs b/Security/Services/PreAuthService.cs index 2bb5390..1a0443e 100644 --- a/Security/Services/PreAuthService.cs +++ b/Security/Services/PreAuthService.cs @@ -3,6 +3,7 @@ using Mirea.Api.Security.Common.Dto.Requests; using Mirea.Api.Security.Common.Dto.Responses; using Mirea.Api.Security.Common.Interfaces; using System; +using System.Security; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -43,4 +44,21 @@ public class PreAuthService(ICacheService cache) ExpiresIn = DateTime.UtcNow.Add(Lifetime) }; } + public async Task MatchToken(TokenRequest request, string preAuthToken, CancellationToken cancellation = default) + { + var preAuthTokenStruct = await cache.GetAsync(GetPreAuthCacheKey(request.Fingerprint), cancellation) + ?? throw new SecurityException($"The token was not found using fingerprint \"{request.Fingerprint}\""); + + if (preAuthTokenStruct == null || + preAuthTokenStruct.Token != preAuthToken || + (preAuthTokenStruct.UserAgent != request.UserAgent && + preAuthTokenStruct.Ip != request.Ip)) + { + throw new SecurityException("It was not possible to verify the authenticity of the token"); + } + + await cache.RemoveAsync(GetPreAuthCacheKey(request.Fingerprint), cancellation); + + return preAuthTokenStruct.UserId; + } } \ No newline at end of file