This commit is contained in:
2025-05-12 23:57:05 +08:00
parent 10a344f6d6
commit 4fa451be97
57 changed files with 344 additions and 106 deletions

View File

@@ -2,12 +2,12 @@
{
public record UserLoginCommand(string Name, string Password) : IRequest<UserLoginCommandResponse>;
public record UserLoginCommandResponse(string Token, IdentityInfo Identity);
public record UserLoginCommandResponse(string Token, IdentityInfo Identity, int TokenLifetimeMinutes);
public class UserLoginCommandHandler(BlogDbContext db) : IRequestHandler<UserLoginCommand, UserLoginCommandResponse>
public class UserLoginCommandHandler(BlogDbContext db, IOptionsMonitor<BlogSettings> options) : IRequestHandler<UserLoginCommand, UserLoginCommandResponse>
{
private readonly BlogDbContext _db = db;
private readonly BlogSettings _settings = options.CurrentValue;
public async Task<UserLoginCommandResponse> Handle(UserLoginCommand request, CancellationToken cancellationToken)
{
var user = _db.Users.FirstOrDefault(x => x.Name == request.Name);
@@ -18,12 +18,23 @@
user.CheckPassword(request.Password);
return new UserLoginCommandResponse("", new IdentityInfo
var role = user.IsSystem ? IdentityRoleEnum.Admin : IdentityRoleEnum.User;
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim("Role", role.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = JwtHelper.GenerateToken(claims, _settings.SecretKey, _settings.TokenLifetimeMinutes);
return new UserLoginCommandResponse(token, new IdentityInfo
{
Name = user.Name,
Id = user.Id,
Role = user.IsSystem ? IdentityRoleEnum.Admin : IdentityRoleEnum.User
});
Role = role
}, _settings.TokenLifetimeMinutes);
}
}