62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
public class AuthService : IAuthService
|
|
{
|
|
private readonly AppDbContext _db;
|
|
private readonly JwtOptions _jwtOptions;
|
|
|
|
public AuthService(AppDbContext db, IOptions<JwtOptions> jwtOptions)
|
|
{
|
|
_db = db;
|
|
_jwtOptions = jwtOptions.Value;
|
|
}
|
|
|
|
public async Task<LoginResponse> LoginAsync(LoginRequest req)
|
|
{
|
|
var user = await _db.Users.FirstOrDefaultAsync(u => u.Username == req.Username);
|
|
if (user is null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
|
|
throw new ValidationException("Invalid username or password.", "INVALID_CREDENTIALS");
|
|
|
|
if (!user.IsActive)
|
|
throw new ConflictException("Account is disabled.", "ACCOUNT_DISABLED");
|
|
|
|
var token = GenerateJwt(user);
|
|
return new LoginResponse(token, user.Id, user.Username, user.FullName, user.Role.ToDbString());
|
|
}
|
|
|
|
public async Task<User> GetCurrentUserAsync(Guid userId)
|
|
{
|
|
var user = await _db.Users.FindAsync(userId);
|
|
if (user is null)
|
|
throw new NotFoundException("User not found.", "USER_NOT_FOUND");
|
|
return user;
|
|
}
|
|
|
|
private string GenerateJwt(User user)
|
|
{
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var claims = new[]
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, user.Username),
|
|
new Claim(ClaimTypes.Role, user.Role.ToDbString()),
|
|
new Claim("fullName", user.FullName)
|
|
};
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _jwtOptions.Issuer,
|
|
audience: _jwtOptions.Audience,
|
|
claims: claims,
|
|
expires: DateTime.UtcNow.AddMinutes(_jwtOptions.ExpiryMinutes),
|
|
signingCredentials: creds);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
} |