DataService hinzugefügt

This commit is contained in:
hydrant
2019-09-17 23:09:00 +02:00
parent e62ca95f4d
commit 73659cdb9e
13 changed files with 490 additions and 1 deletions

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using ReallifeGamemode.Database;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
namespace ReallifeGamemode.DataService.Logic
{
public class JwtTokenGenerator : LogicBase
{
private ServerConfig config;
public JwtTokenGenerator(IOptions<ServerConfig> config, DatabaseContext dbContext) : base(dbContext)
{
this.config = config.Value;
}
public string GenerateUserToken(User user)
{
if(user == null)
{
return null;
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(config.TokenSecret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.AdminLevel.ToString())
}),
Expires = DateTime.Now.AddDays(1),
IssuedAt = DateTime.Now,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Issuer = "LOGDATASERVICE"
};
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
return token;
}
public string GetDebugToken(byte[] key)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, 1.ToString()),
new Claim(ClaimTypes.Role, (AdminLevel.PROJEKTLEITUNG).ToString())
}),
Expires = DateTime.Now.AddDays(1),
IssuedAt = DateTime.Now,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Issuer = "LOGDATASERVICE"
};
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
return token;
}
}
}