69 lines
2.3 KiB
C#
69 lines
2.3 KiB
C#
using System.Security.Claims;
|
|
using DysonNetwork.Drive.Data;
|
|
using DysonNetwork.Drive.Models;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Text;
|
|
|
|
namespace DysonNetwork.Drive.Auth;
|
|
|
|
public interface IAuthService
|
|
{
|
|
Task<string> GenerateJwtToken(Account account);
|
|
Task<Account?> GetAuthenticatedAccountAsync(ClaimsPrincipal user);
|
|
Task<Account?> GetAuthenticatedAccountAsync(HttpContext context);
|
|
}
|
|
|
|
public class AuthService : IAuthService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly AppDatabase _db;
|
|
|
|
public AuthService(IConfiguration configuration, AppDatabase db)
|
|
{
|
|
_configuration = configuration;
|
|
_db = db;
|
|
}
|
|
|
|
public Task<string> GenerateJwtToken(Account account)
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var key = Encoding.ASCII.GetBytes(_configuration["Jwt:Secret"] ?? throw new InvalidOperationException("JWT Secret not configured"));
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(new[]
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, account.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, account.Username),
|
|
new Claim(ClaimTypes.Email, account.Email)
|
|
}),
|
|
Expires = DateTime.UtcNow.AddDays(7),
|
|
SigningCredentials = new SigningCredentials(
|
|
new SymmetricSecurityKey(key),
|
|
SecurityAlgorithms.HmacSha256Signature)
|
|
};
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
return Task.FromResult(tokenHandler.WriteToken(token));
|
|
}
|
|
|
|
public async Task<Account?> GetAuthenticatedAccountAsync(ClaimsPrincipal user)
|
|
{
|
|
var userIdClaim = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
|
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
|
|
return null;
|
|
|
|
return await _db.Set<Account>().FindAsync(userId);
|
|
}
|
|
|
|
public async Task<Account?> GetAuthenticatedAccountAsync(HttpContext context)
|
|
{
|
|
return await GetAuthenticatedAccountAsync(context.User);
|
|
}
|
|
}
|