This commit is contained in:
2026-03-25 14:55:34 +08:00
commit 2c44b3a4b2
131 changed files with 7453 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using StopShopping.EF.Models;
using StopShopping.Services.Models;
namespace StopShopping.Services.Implementions;
public class ClaimsService : IClaimsService
{
public ClaimsService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private readonly IHttpContextAccessor _httpContextAccessor;
public ClaimsIdentity BuildIdentity(User user)
{
var claimsIdentity = new ClaimsIdentity(
[
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Name, user.Account),
new Claim(JwtRegisteredClaimNames.Nickname, user.NickName),
new Claim(ClaimTypes.Role, SystemRoles.User.ToString()),
]);
return claimsIdentity;
}
public ClaimsIdentity BuildAdminIdentity(Administrator admin)
{
var claimsIdentity = new ClaimsIdentity(
[
new Claim(JwtRegisteredClaimNames.Sub, admin.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Name, admin.Account),
new Claim(JwtRegisteredClaimNames.Nickname, admin.NickName),
new Claim(ClaimTypes.Role, SystemRoles.Admin.ToString()),
]);
return claimsIdentity;
}
public int GetCurrentUserId()
{
var currUserId = _httpContextAccessor.HttpContext
?.User.FindFirstValue(JwtRegisteredClaimNames.Sub);
if (string.IsNullOrWhiteSpace(currUserId))
throw new InvalidOperationException("在错误的位置获取当前登录用户");
return Convert.ToInt32(currUserId);
}
}