AuthService.cs 4.8 KB

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