AuthService.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  40. if(!result.Succeeded)
  41. {
  42. throw new AppException(ExceptionEnum.WrongCredentials);
  43. }
  44. var userResponse = await _userService.GetById(user.Id);
  45. JwtSecurityToken jwtToken = await GenerateToken(user);
  46. var response = new AuthResponse
  47. {
  48. User = userResponse,
  49. //Id = user.Id,
  50. //Email = user.Email,
  51. //UserName = user.UserName,
  52. //UserTypeId = user.UserType,
  53. Token = new JwtSecurityTokenHandler().WriteToken( jwtToken),
  54. Expiration = jwtToken.ValidTo
  55. };
  56. return response;
  57. }
  58. private async Task<JwtSecurityToken> GenerateToken(ApplicationUser user)
  59. {
  60. var userCalims = await _userManager.GetClaimsAsync(user);
  61. var roles = await _userManager.GetRolesAsync(user);
  62. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  63. var claims = new[]
  64. {
  65. new Claim(JwtRegisteredClaimNames.Name, user.UserName),
  66. new Claim(JwtRegisteredClaimNames.Email, user.Email),
  67. new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  68. new Claim("companyId", user.CompanyId+""),
  69. new Claim("uid", user.Id)
  70. }.Union(userCalims)
  71. .Union(roleClaims);
  72. var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.JwtSettings.SecretKey));
  73. var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
  74. var jwtSecurityToken = new JwtSecurityToken(
  75. issuer: _configuration.JwtSettings.Issuer,
  76. audience: _configuration.JwtSettings.Audience,
  77. claims: claims,
  78. expires: DateTime.Now.AddMinutes(_configuration.JwtSettings.DurationInMinutes),
  79. signingCredentials: signingCredentials
  80. );
  81. return jwtSecurityToken;
  82. }
  83. public async Task<AuthResponse> AdminLogin(AuthRequest request)
  84. {
  85. var user = await _userManager.FindByEmailAsync(request.Email);
  86. if (user == null)
  87. {
  88. throw new AppException(ExceptionEnum.EmailNotExist);
  89. }
  90. var roles = await _userManager.GetRolesAsync(user);
  91. if(!roles.Any(r => r == "Admin"))
  92. {
  93. throw new AppException(ExceptionEnum.NotAuthorized);
  94. }
  95. var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();
  96. var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
  97. if (!result.Succeeded)
  98. {
  99. throw new AppException(ExceptionEnum.WrongCredentials);
  100. }
  101. var userResponse = await _userService.GetById(user.Id);
  102. JwtSecurityToken jwtToken = await GenerateToken(user);
  103. var response = new AuthResponse
  104. {
  105. User = userResponse,
  106. Token = new JwtSecurityTokenHandler().WriteToken(jwtToken),
  107. Expiration = jwtToken.ValidTo
  108. };
  109. return response;
  110. }
  111. }
  112. }