AuthService.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Options;
  5. using Microsoft.IdentityModel.Tokens;
  6. using MTWorkHR.Application.Exceptions;
  7. using MTWorkHR.Application.Filters;
  8. using MTWorkHR.Application.Identity;
  9. using MTWorkHR.Application.Mapper;
  10. using MTWorkHR.Application.Models;
  11. using MTWorkHR.Application.Services.Interfaces;
  12. using MTWorkHR.Core.Global;
  13. using MTWorkHR.Infrastructure.Entities;
  14. using System.IdentityModel.Tokens.Jwt;
  15. using System.Security.Claims;
  16. using System.Text;
  17. namespace MTWorkHR.Identity.Services
  18. {
  19. public class AuthService : IAuthService
  20. {
  21. private readonly UserManager<ApplicationUser> _userManager;
  22. private readonly SignInManager<ApplicationUser> _signInManager;
  23. private readonly AppSettingsConfiguration _configuration;
  24. private readonly IUserService _userService;
  25. public AuthService(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, AppSettingsConfiguration configuration, IUserService userService)
  26. {
  27. _userManager = userManager;
  28. _signInManager = signInManager;
  29. _configuration = configuration;
  30. _userService = userService;
  31. }
  32. public async Task<AuthResponse> Login(AuthRequest request)
  33. {
  34. var user = await _userManager.FindByEmailAsync(request.Email);
  35. if (user == null)
  36. {
  37. throw new AppException(ExceptionEnum.EmailNotExist);
  38. }
  39. var roles = await _userManager.GetRolesAsync(user);
  40. if (roles.Any(r => r == "Admin"))
  41. {
  42. throw new AppException(ExceptionEnum.NotAuthorized);
  43. }
  44. if (user.IsStopped == true)
  45. {
  46. throw new AppException(ExceptionEnum.AccountLocked);
  47. }
  48. if (user.IsDeleted == true)
  49. {
  50. throw new AppException(ExceptionEnum.UserNotExist);
  51. }
  52. var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  53. if(!result.Succeeded)
  54. {
  55. throw new AppException(ExceptionEnum.WrongCredentials);
  56. }
  57. var userResponse = await _userService.GetById(user.Id);
  58. JwtSecurityToken jwtToken = await GenerateToken(user);
  59. var response = new AuthResponse
  60. {
  61. User = userResponse,
  62. //Id = user.Id,
  63. //Email = user.Email,
  64. //UserName = user.UserName,
  65. //UserTypeId = user.UserType,
  66. Token = new JwtSecurityTokenHandler().WriteToken( jwtToken),
  67. Expiration = jwtToken.ValidTo
  68. };
  69. return response;
  70. }
  71. private async Task<JwtSecurityToken> GenerateToken(ApplicationUser user)
  72. {
  73. var userCalims = await _userManager.GetClaimsAsync(user);
  74. var roles = await _userManager.GetRolesAsync(user);
  75. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  76. var claims = new[]
  77. {
  78. new Claim(JwtRegisteredClaimNames.Name, user.UserName),
  79. new Claim(JwtRegisteredClaimNames.Email, user.Email),
  80. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  81. new Claim("companyId", user.CompanyId+""),
  82. new Claim("uid", user.Id)
  83. }.Union(userCalims)
  84. .Union(roleClaims);
  85. var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.JwtSettings.SecretKey));
  86. var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
  87. var jwtSecurityToken = new JwtSecurityToken(
  88. issuer: _configuration.JwtSettings.Issuer,
  89. audience: _configuration.JwtSettings.Audience,
  90. claims: claims,
  91. expires: DateTime.Now.AddMinutes(_configuration.JwtSettings.DurationInMinutes),
  92. signingCredentials: signingCredentials
  93. );
  94. return jwtSecurityToken;
  95. }
  96. public async Task<AuthResponse> AdminLogin(AuthRequest request)
  97. {
  98. var user = await _userManager.FindByEmailAsync(request.Email);
  99. if (user == null)
  100. {
  101. throw new AppException(ExceptionEnum.EmailNotExist);
  102. }
  103. var roles = await _userManager.GetRolesAsync(user);
  104. if(!roles.Any(r => r == "Admin"))
  105. {
  106. throw new AppException(ExceptionEnum.NotAuthorized);
  107. }
  108. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  109. var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  110. if (!result.Succeeded)
  111. {
  112. throw new AppException(ExceptionEnum.WrongCredentials);
  113. }
  114. var userResponse = await _userService.GetById(user.Id);
  115. JwtSecurityToken jwtToken = await GenerateToken(user);
  116. var response = new AuthResponse
  117. {
  118. User = userResponse,
  119. Token = new JwtSecurityTokenHandler().WriteToken(jwtToken),
  120. Expiration = jwtToken.ValidTo
  121. };
  122. return response;
  123. }
  124. }
  125. }