mirror of
https://github.com/azaion/admin.git
synced 2026-04-22 07:06:34 +00:00
add Cache.cs
fix hardware hash stack in the jwt token claims
This commit is contained in:
@@ -11,31 +11,28 @@ namespace Azaion.Services;
|
||||
|
||||
public interface IAuthService
|
||||
{
|
||||
User? CurrentUser { get; }
|
||||
Guid? GetCurrentUserId();
|
||||
Task<User?> GetCurrentUser();
|
||||
string CreateToken(User user);
|
||||
}
|
||||
|
||||
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig) : IAuthService
|
||||
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig, IUserService userService) : IAuthService
|
||||
{
|
||||
public User? CurrentUser
|
||||
|
||||
public Guid? GetCurrentUserId()
|
||||
{
|
||||
get
|
||||
{
|
||||
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
||||
if (claims == null)
|
||||
return null;
|
||||
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
||||
if (claims == null)
|
||||
return null;
|
||||
|
||||
if (!Enum.TryParse(claims[ClaimTypes.Role].Value, out RoleEnum role))
|
||||
throw new ApplicationException("Invalid role");
|
||||
var id = Guid.Parse(claims[ClaimTypes.NameIdentifier].Value);
|
||||
return id;
|
||||
}
|
||||
|
||||
return new User
|
||||
{
|
||||
Id = Guid.Parse(claims[ClaimTypes.NameIdentifier].Value),
|
||||
Email = claims[ClaimTypes.Name].Value,
|
||||
Role = role,
|
||||
HardwareHash = claims[Constants.HARDWARE_ID].Value,
|
||||
};
|
||||
}
|
||||
public async Task<User?> GetCurrentUser()
|
||||
{
|
||||
var id = GetCurrentUserId();
|
||||
return await userService.GetById(id);
|
||||
}
|
||||
|
||||
public string CreateToken(User user)
|
||||
@@ -47,9 +44,7 @@ public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtC
|
||||
{
|
||||
Subject = new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.Email),
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString()),
|
||||
new Claim(Constants.HARDWARE_ID, user.HardwareHash ?? "")
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString())
|
||||
]),
|
||||
Expires = DateTime.UtcNow.AddHours(jwtConfig.Value.TokenLifetimeHours),
|
||||
Issuer = jwtConfig.Value.Issuer,
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LazyCache.AspNetCore" Version="2.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.1.2" />
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using LazyCache;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
public interface ICache
|
||||
{
|
||||
Task<T> GetFromCacheAsync<T>(string key, Func<Task<T>> fetchFunc, TimeSpan? expiration = null);
|
||||
void Invalidate(string key);
|
||||
}
|
||||
|
||||
public class MemoryCache : ICache
|
||||
{
|
||||
private readonly IAppCache _cache = new CachingService();
|
||||
|
||||
public async Task<T> GetFromCacheAsync<T>(string key, Func<Task<T>> fetchFunc, TimeSpan? expiration = null)
|
||||
{
|
||||
expiration ??= TimeSpan.FromHours(4);
|
||||
return await _cache.GetOrAddAsync(key, async entry =>
|
||||
{
|
||||
var result = await fetchFunc();
|
||||
entry.AbsoluteExpirationRelativeToNow = expiration;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
public void Invalidate(string key) => _cache.Remove(key);
|
||||
}
|
||||
@@ -12,12 +12,14 @@ public interface IUserService
|
||||
{
|
||||
Task RegisterUser(RegisterUserRequest request, CancellationToken cancellationToken = default);
|
||||
Task<User> ValidateUser(LoginRequest request, CancellationToken cancellationToken = default);
|
||||
Task<User?> GetById(Guid? id, CancellationToken cancellationToken = default);
|
||||
Task<User?> GetByEmail(string email, CancellationToken cancellationToken = default);
|
||||
Task UpdateHardware(string email, HardwareInfo hardwareInfo, CancellationToken cancellationToken = default);
|
||||
Task<IEnumerable<User>> GetUsers(string? searchEmail, RoleEnum? searchRole, CancellationToken cancellationToken);
|
||||
Task CheckHardware(User user, GetResourceRequest request);
|
||||
}
|
||||
|
||||
public class UserService(IDbFactory dbFactory) : IUserService
|
||||
public class UserService(IDbFactory dbFactory, ICache cache) : IUserService
|
||||
{
|
||||
public async Task RegisterUser(RegisterUserRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -37,6 +39,15 @@ public class UserService(IDbFactory dbFactory) : IUserService
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<User?> GetById(Guid? id, CancellationToken cancellationToken = default) =>
|
||||
await cache.GetFromCacheAsync($"{nameof(User)}.{id}",
|
||||
async () => await dbFactory.Run(async db =>
|
||||
await db.Users.FirstOrDefaultAsync(x => x.Id == id, cancellationToken)), TimeSpan.FromHours(2));
|
||||
|
||||
public async Task<User?> GetByEmail(string email, CancellationToken cancellationToken = default) =>
|
||||
await dbFactory.Run(async db =>
|
||||
await db.Users.FirstOrDefaultAsync(x => x.Email == email, cancellationToken));
|
||||
|
||||
public async Task<User> ValidateUser(LoginRequest request, CancellationToken cancellationToken = default) =>
|
||||
await dbFactory.Run(async db =>
|
||||
{
|
||||
@@ -82,6 +93,14 @@ public class UserService(IDbFactory dbFactory) : IUserService
|
||||
user.HardwareHash = request.Hardware.Hash;
|
||||
}
|
||||
|
||||
var hwHash = await dbFactory.Run(async db =>
|
||||
await db.Users
|
||||
.Where(x => x.Email == user.Email)
|
||||
.Select(x => x.HardwareHash)
|
||||
.FirstOrDefaultAsync());
|
||||
if (hwHash != user.HardwareHash)
|
||||
user.HardwareHash = hwHash;
|
||||
|
||||
if (user.HardwareHash != request.Hardware.Hash)
|
||||
throw new BusinessException(ExceptionEnum.HardwareIdMismatch);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user