AuthService.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using Microsoft.AspNetCore.Identity;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.IdentityModel.Tokens;
  4. using MTWorkHR.Application.Exceptions;
  5. using MTWorkHR.Application.Filters;
  6. using MTWorkHR.Application.Identity;
  7. using MTWorkHR.Application.Models;
  8. using MTWorkHR.Core.Global;
  9. using MTWorkHR.Infrastructure.Entities;
  10. using System.IdentityModel.Tokens.Jwt;
  11. using System.Security.Claims;
  12. using System.Text;
  13. namespace MTWorkHR.Identity.Services
  14. {
  15. public class AuthService : IAuthService
  16. {
  17. private readonly UserManager<ApplicationUser> _userManager;
  18. private readonly SignInManager<ApplicationUser> _signInManager;
  19. private readonly AppSettingsConfiguration _configuration;
  20. public AuthService(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, AppSettingsConfiguration configuration)
  21. {
  22. _userManager = userManager;
  23. _signInManager = signInManager;
  24. _configuration = configuration;
  25. }
  26. public async Task<AuthResponse> Login(AuthRequest request)
  27. {
  28. var user = await _userManager.FindByEmailAsync(request.Email);
  29. if(user == null)
  30. {
  31. throw new AppException(ExceptionEnum.RecordNotExist);
  32. }
  33. var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  34. if(!result.Succeeded)
  35. {
  36. throw new AppException($"Credentials for '{request.Email} are not valid'.");
  37. }
  38. JwtSecurityToken jwtToken = await GenerateToken(user);
  39. var response = new AuthResponse
  40. {
  41. Id = user.Id,
  42. Email = user.Email,
  43. UserName = user.UserName,
  44. UserTypeId = user.UserType,
  45. Token = new JwtSecurityTokenHandler().WriteToken( jwtToken),
  46. Expiration = jwtToken.ValidTo
  47. };
  48. return response;
  49. }
  50. //public async Task<RegistrationResponse> Register(RegistrationRequest request)
  51. //{
  52. // var user = new ApplicationUser {
  53. // Email = request.Email ,
  54. // UserName = request.UserName ,
  55. // FirstName = request.FirstName ,
  56. // LastName = request.LastName ,
  57. // EmailConfirmed = true
  58. // };
  59. // var result = await _userManager.CreateAsync(user, request.Password);
  60. // if (result.Succeeded)
  61. // {
  62. // await _userManager.AddToRoleAsync(user, request.RoleName);
  63. // return new RegistrationResponse(){ UserId = user.Id };
  64. // }
  65. // else
  66. // {
  67. // StringBuilder str = new StringBuilder();
  68. // foreach (var err in result.Errors)
  69. // {
  70. // str.AppendFormat(".{0}\n", err.Description);
  71. // }
  72. // throw new BadRequest($"{str}");
  73. // }
  74. //}
  75. private async Task<JwtSecurityToken> GenerateToken(ApplicationUser user)
  76. {
  77. var userCalims = await _userManager.GetClaimsAsync(user);
  78. var roles = await _userManager.GetRolesAsync(user);
  79. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  80. var claims = new[]
  81. {
  82. new Claim(JwtRegisteredClaimNames.Name, user.UserName),
  83. new Claim(JwtRegisteredClaimNames.Email, user.Email),
  84. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  85. new Claim("companyId", user.CompanyId+""),
  86. new Claim("uid", user.Id)
  87. }.Union(userCalims)
  88. .Union(roleClaims);
  89. var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.JwtSettings.SecretKey));
  90. var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
  91. var jwtSecurityToken = new JwtSecurityToken(
  92. issuer: _configuration.JwtSettings.Issuer,
  93. audience: _configuration.JwtSettings.Audience,
  94. claims: claims,
  95. expires: DateTime.Now.AddMinutes(_configuration.JwtSettings.DurationInMinutes),
  96. signingCredentials: signingCredentials
  97. );
  98. return jwtSecurityToken;
  99. }
  100. }
  101. }