Files
laatzen/LaaProductionWeb/LaaProduction.Personalization/AccountManager.cs
T
2023-06-21 15:29:08 +02:00

107 lines
3.8 KiB
C#

namespace LaaProduction.Personalization
{
using LaaProduction.Personalization.Interfaces;
using LaaProduction.Personalization.Models;
using LaaProduction.Personalization.Repositories.Interfaces;
using LaaProductionDI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
public class AccountManager : IAccountManager
{
private static IIdentity anonymous
=> new ClaimsIdentity(
claims: Array.Empty<Claim>(),
authenticationType: string.Empty,
nameType: string.Empty,
roleType: string.Empty);
private readonly IEmployeesRepository employeesRepository;
private readonly ISoftwareRepository softwareRepository;
public AccountManager()
{
this.employeesRepository = LaaServiceProvider.GetService<IEmployeesRepository>();
this.softwareRepository = LaaServiceProvider.GetService<ISoftwareRepository>();
}
public string GetAuthToken(string username, string password, string software)
{
var userId = this.employeesRepository.EmployeeId(username, password);
var token = default(string);
if (userId > 0)
{
var appId = this.softwareRepository.AppId(software);
if (appId > 0)
{
this.employeesRepository.CreateToken(appId, userId);
token = this.employeesRepository.GetToken(appId, userId);
}
}
return token;
}
public IPrincipal GetClaimsPrincipal(string token)
{
var claimsIdentity = anonymous;
var tokenData = this.employeesRepository.GetTokenData(token);
if (tokenData != null)
{
var employee = this.employeesRepository.Find(tokenData.EmployeeId);
var claims = new List<Claim>
{
new Claim(nameof(EmployeeToken.AppId), tokenData.AppId.ToString()),
new Claim(nameof(employee.EmployeeId), employee.EmployeeId.ToString()),
new Claim(nameof(employee.FullName), employee.FullName),
new Claim(nameof(employee.Username), employee.Username),
new Claim(ClaimTypes.NameIdentifier, token),
};
var userRoles = this.employeesRepository
.GetUserRoles(token)
.Intersect(Enum.GetNames(typeof(EmployeesRoles)));
foreach (var role in userRoles)
{
claims.Add(new Claim(nameof(EmployeesRoles), role));
}
var functions = this.softwareRepository
.GetSoftwareFunctions(token)
.Intersect(Enum.GetNames(typeof(SoftwareFunctions)));
foreach (var func in functions)
{
claims.Add(new Claim(nameof(SoftwareFunctions), func));
}
claimsIdentity = new ClaimsIdentity(
claims: claims,
authenticationType: nameof(ClaimsIdentity),
nameType: nameof(employee.EmployeeId),
roleType: nameof(EmployeesRoles));
}
return new ClaimsPrincipal(claimsIdentity);
}
public void ResetPassword(short employeeId)
{
this.employeesRepository.ResetPassword(employeeId);
this.employeesRepository.ResetTokens(employeeId);
}
public void SetPassword(short employeeId, string password)
=> this.employeesRepository.SetPassword(employeeId, password);
}
}