2023-02-18 08:52:17 +01:00
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
|
2023-02-19 00:43:43 +01:00
|
|
|
|
using PrivaPub.ClientModels;
|
|
|
|
|
using PrivaPub.ClientModels.User;
|
|
|
|
|
using PrivaPub.Models.User;
|
2023-02-18 08:52:17 +01:00
|
|
|
|
|
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
2023-02-19 00:43:43 +01:00
|
|
|
|
namespace PrivaPub.StaticServices
|
2023-02-18 08:52:17 +01:00
|
|
|
|
{
|
|
|
|
|
public class AuthTokenManager
|
|
|
|
|
{
|
|
|
|
|
readonly IConfiguration Configuration;
|
|
|
|
|
|
|
|
|
|
public AuthTokenManager(IConfiguration configuration)
|
|
|
|
|
{
|
|
|
|
|
Configuration = configuration;
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-19 00:43:43 +01:00
|
|
|
|
public JwtUser GenerateToken(RootUser user, ViewAvatarServer userSettings)
|
2023-02-18 08:52:17 +01:00
|
|
|
|
{
|
|
|
|
|
var expiration = DateTime.UtcNow.AddHours(int.Parse(Configuration["AppConfiguration:Jwt:HoursTimeout"]));
|
|
|
|
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppConfiguration:Jwt:Key"]));
|
|
|
|
|
var jwtUser = new JwtUser
|
|
|
|
|
{
|
|
|
|
|
UserId = user.ID,
|
|
|
|
|
Email = user.Email,
|
|
|
|
|
Username = user.UserName,
|
|
|
|
|
Expiration = expiration.Ticks,
|
|
|
|
|
Policies = user.Policies,
|
|
|
|
|
UserSettings = userSettings
|
|
|
|
|
};
|
|
|
|
|
var claims = new List<Claim>
|
|
|
|
|
{
|
|
|
|
|
new(ClaimTypes.UserData, user.ID),
|
|
|
|
|
new(ClaimTypes.Name, user.UserName)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
claims.Add(new(Policies.IsUser, $"{user.Policies.Contains(Policies.IsUser)}".ToLower()));
|
|
|
|
|
claims.Add(new(Policies.IsModerator, $"{user.Policies.Contains(Policies.IsModerator)}".ToLower()));
|
|
|
|
|
claims.Add(new(Policies.IsAdmin, $"{user.Policies.Contains(Policies.IsAdmin)}".ToLower()));
|
|
|
|
|
|
|
|
|
|
var token = new JwtSecurityToken(issuer: Configuration["AppConfiguration:Jwt:Issuer"], audience: Configuration["AppConfiguration:Jwt:Audience"],
|
|
|
|
|
claims: claims,
|
|
|
|
|
expires: expiration,
|
|
|
|
|
signingCredentials: new(securityKey, SecurityAlgorithms.HmacSha512)
|
|
|
|
|
);
|
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
|
jwtUser.Token = tokenHandler.WriteToken(token);
|
|
|
|
|
return jwtUser;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|