MireaBackend/Security/Services/AuthService.cs

57 lines
2.1 KiB
C#
Raw Normal View History

2024-05-29 05:50:47 +03:00
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;
2024-05-29 05:51:32 +03:00
using System.Security;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
2024-05-29 05:32:22 +03:00
namespace Mirea.Api.Security.Services;
2024-05-29 05:51:03 +03:00
public class AuthService(ICacheService cache, IAccessToken accessTokenService)
2024-05-29 05:32:22 +03:00
{
public TimeSpan Lifetime { private get; init; }
2024-05-29 05:35:44 +03:00
private static string GenerateRefreshToken() => Guid.NewGuid().ToString().Replace("-", "") +
GeneratorKey.GenerateString(32);
2024-05-29 05:51:03 +03:00
private (string Token, DateTime ExpireIn) GenerateAccessToken(string userId) =>
accessTokenService.GenerateToken(userId);
2024-05-29 05:36:26 +03:00
private static string GetAuthCacheKey(string fingerprint) => $"{fingerprint}_auth_token";
2024-05-29 05:50:47 +03:00
private Task SetAuthTokenDataToCache(string fingerprint, AuthToken data, CancellationToken cancellation) =>
cache.SetAsync(
GetAuthCacheKey(fingerprint),
JsonSerializer.SerializeToUtf8Bytes(data),
slidingExpiration: Lifetime,
cancellationToken: cancellation);
2024-05-29 05:51:32 +03:00
public async Task<AuthTokenResponse> GenerateAuthTokensAsync(TokenRequest request, string preAuthToken, CancellationToken cancellation = default)
{
string userId = await new PreAuthService(cache).MatchToken(request, preAuthToken, cancellation);
var refreshToken = GenerateRefreshToken();
var accessToken = GenerateAccessToken(userId);
var authTokenStruct = new AuthToken
{
CreatedAt = DateTime.UtcNow,
Ip = request.Ip,
RefreshToken = refreshToken,
UserAgent = request.UserAgent,
UserId = userId,
AccessToken = accessToken.Token
};
await SetAuthTokenDataToCache(request.Fingerprint, authTokenStruct, cancellation);
return new AuthTokenResponse
{
AccessToken = accessToken.Token,
ExpiresIn = accessToken.ExpireIn,
RefreshToken = authTokenStruct.RefreshToken
};
}
2024-05-29 05:32:22 +03:00
}