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 GenerateJwtToken(Account account); Task GetAuthenticatedAccountAsync(ClaimsPrincipal user); Task 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 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 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().FindAsync(userId); } public async Task GetAuthenticatedAccountAsync(HttpContext context) { return await GetAuthenticatedAccountAsync(context.User); } }