namespace LaaProduction.Personalization { using LaaProduction.Personalization.Interfaces; using LaaProduction.Personalization.Models; using LaaProduction.Personalization.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Security.Claims; using System.Security.Principal; public class AccountManager : IAccountManager { private static IIdentity anonymous => new ClaimsIdentity( claims: Array.Empty(), authenticationType: string.Empty, nameType: string.Empty, roleType: string.Empty); private readonly IEmployeesRepository employeesRepository; private readonly ISoftwareRepository softwareRepository; public AccountManager() { this.employeesRepository = ServiceProvider.GetService(); this.softwareRepository = ServiceProvider.GetService(); } 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 { 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(typeof(UsersRoles)); foreach (var role in userRoles) { claims.Add(new Claim(nameof(UsersRoles), role)); } var functions = this.softwareRepository .GetSoftwareFunctions(token) .Intersect(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(UsersRoles)); } 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); } }