54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
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);
|
|
}
|
|
} |