From b14ae26a4832ec8f41f43df58655e39f6151843d Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Wed, 29 May 2024 04:31:47 +0300 Subject: [PATCH] feat: add pre-auth service --- Security/Services/PreAuthService.cs | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Security/Services/PreAuthService.cs diff --git a/Security/Services/PreAuthService.cs b/Security/Services/PreAuthService.cs new file mode 100644 index 0000000..2a1929c --- /dev/null +++ b/Security/Services/PreAuthService.cs @@ -0,0 +1,42 @@ +using Mirea.Api.Security.Common.Domain; +using Mirea.Api.Security.Common.Dto.Requests; +using Mirea.Api.Security.Common.Dto.Responses; +using Mirea.Api.Security.Common.Interfaces; +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Mirea.Api.Security.Services; + +public class PreAuthService(ICacheService cache) +{ + public TimeSpan Lifetime { private get; init; } + + private static string GenerateFirstAuthToken() => Guid.NewGuid().ToString().Replace("-", ""); + + public async Task CreateLoginTokenAsync(TokenRequest request, string userId, CancellationToken cancellation = default) + { + var firstAuthToken = GenerateFirstAuthToken(); + + var loginStructure = new PreAuthToken + { + Fingerprint = request.Fingerprint, + UserId = userId, + UserAgent = request.UserAgent, + Token = firstAuthToken + }; + + await cache.SetAsync( + request.Fingerprint, + JsonSerializer.SerializeToUtf8Bytes(loginStructure), + Lifetime, + cancellation); + + return new PreAuthTokenResponse + { + Token = firstAuthToken, + ExpiresIn = DateTime.UtcNow.Add(Lifetime) + }; + } +} \ No newline at end of file