| | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | 2 | | using System.Security.Claims; |
| | 3 | | using System.Text; |
| | 4 | | using LGDXRobotCloud.API.Configurations; |
| | 5 | | using LGDXRobotCloud.API.Exceptions; |
| | 6 | | using LGDXRobotCloud.API.Services.Common; |
| | 7 | | using LGDXRobotCloud.Data.DbContexts; |
| | 8 | | using LGDXRobotCloud.Data.Entities; |
| | 9 | | using LGDXRobotCloud.Data.Models.Business.Identity; |
| | 10 | | using LGDXRobotCloud.Utilities.Helpers; |
| | 11 | | using Microsoft.AspNetCore.Identity; |
| | 12 | | using Microsoft.EntityFrameworkCore; |
| | 13 | | using Microsoft.Extensions.Options; |
| | 14 | | using Microsoft.IdentityModel.Tokens; |
| | 15 | |
|
| | 16 | | namespace LGDXRobotCloud.API.Services.Identity; |
| | 17 | |
|
| | 18 | | public interface IAuthService |
| | 19 | | { |
| | 20 | | Task<LoginResponseBusinessModel> LoginAsync(LoginRequestBusinessModel loginRequestBusinessModel); |
| | 21 | | Task ForgotPasswordAsync(ForgotPasswordRequestBusinessModel forgotPasswordRequestBusinessModel); |
| | 22 | | Task ResetPasswordAsync(ResetPasswordRequestBusinessModel resetPasswordRequestBusinessModel); |
| | 23 | | Task<RefreshTokenResponseBusinessModel> RefreshTokenAsync(RefreshTokenRequestBusinessModel refreshTokenRequestBusiness |
| | 24 | | Task<bool> UpdatePasswordAsync(string userId, UpdatePasswordRequestBusinessModel updatePasswordRequestBusinessModel); |
| | 25 | | } |
| | 26 | |
|
| 0 | 27 | | public class AuthService( |
| 0 | 28 | | LgdxContext context, |
| 0 | 29 | | IEmailService emailService, |
| 0 | 30 | | IOptionsSnapshot<LgdxRobotCloudSecretConfiguration> lgdxRobotCloudSecretConfiguration, |
| 0 | 31 | | UserManager<LgdxUser> userManager |
| 0 | 32 | | ) : IAuthService |
| | 33 | | { |
| 0 | 34 | | private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context)); |
| 0 | 35 | | private readonly IEmailService _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService)); |
| 0 | 36 | | private readonly LgdxRobotCloudSecretConfiguration _lgdxRobotCloudSecretConfiguration = lgdxRobotCloudSecretConfigurat |
| 0 | 37 | | private readonly UserManager<LgdxUser> _userManager = userManager ?? throw new ArgumentNullException(nameof(userManage |
| | 38 | |
|
| | 39 | | private JwtSecurityToken GenerateJwtToken(List<Claim> claims, DateTime notBefore, DateTime expires) |
| 0 | 40 | | { |
| 0 | 41 | | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_lgdxRobotCloudSecretConfiguration.LgdxUserJwtSecr |
| 0 | 42 | | var credentials = new SigningCredentials(securityKey, _lgdxRobotCloudSecretConfiguration.LgdxUserJwtAlgorithm); |
| 0 | 43 | | return new JwtSecurityToken( |
| 0 | 44 | | _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 0 | 45 | | _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 0 | 46 | | claims, |
| 0 | 47 | | notBefore, |
| 0 | 48 | | expires, |
| 0 | 49 | | credentials); |
| 0 | 50 | | } |
| | 51 | |
|
| | 52 | | private async Task<string> GenerateAccessTokenAsync(LgdxUser user, DateTime notBefore, DateTime expires) |
| 0 | 53 | | { |
| 0 | 54 | | var userRoles = await _userManager.GetRolesAsync(user); |
| 0 | 55 | | var Claims = new List<Claim> |
| 0 | 56 | | { |
| 0 | 57 | | new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| 0 | 58 | | new (JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| 0 | 59 | | new (ClaimTypes.Name, user.UserName ?? string.Empty), |
| 0 | 60 | | new (ClaimTypes.Email, user.Email ?? string.Empty), |
| 0 | 61 | | new ("fullname", user.Name ?? string.Empty), |
| 0 | 62 | | }; |
| | 63 | | // Add Roles |
| 0 | 64 | | foreach (var userRole in userRoles) |
| 0 | 65 | | { |
| 0 | 66 | | Claims.Add(new Claim(ClaimTypes.Role, userRole)); |
| 0 | 67 | | } |
| | 68 | | // Add Role Claims |
| 0 | 69 | | { |
| 0 | 70 | | List<string> roleIds = await _context.Roles.AsNoTracking() |
| 0 | 71 | | .Where(r => userRoles.Select(ur => ur.ToUpper()).Contains(r.NormalizedName!)) |
| 0 | 72 | | .Select(r => r.Id ) |
| 0 | 73 | | .ToListAsync(); |
| 0 | 74 | | var roleClaims = await _context.RoleClaims.AsNoTracking() |
| 0 | 75 | | .Where(r => roleIds.Contains(r.RoleId)) |
| 0 | 76 | | .ToListAsync(); |
| 0 | 77 | | foreach (var roleClaim in roleClaims) |
| 0 | 78 | | { |
| 0 | 79 | | Claims.Add(new Claim(roleClaim.ClaimType!, roleClaim.ClaimValue!)); |
| 0 | 80 | | } |
| 0 | 81 | | } |
| 0 | 82 | | var token = GenerateJwtToken(Claims, notBefore, expires); |
| 0 | 83 | | return new JwtSecurityTokenHandler().WriteToken(token); |
| 0 | 84 | | } |
| | 85 | |
|
| | 86 | | private string GenerateRefreshToken(LgdxUser user, DateTime notBefore, DateTime expires) |
| 0 | 87 | | { |
| 0 | 88 | | var Claims = new List<Claim> |
| 0 | 89 | | { |
| 0 | 90 | | new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| 0 | 91 | | new (JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| 0 | 92 | | }; |
| 0 | 93 | | var token = GenerateJwtToken(Claims, notBefore, expires); |
| 0 | 94 | | var tokenStr = new JwtSecurityTokenHandler().WriteToken(token); |
| 0 | 95 | | return tokenStr; |
| 0 | 96 | | } |
| | 97 | |
|
| | 98 | | public async Task<LoginResponseBusinessModel> LoginAsync(LoginRequestBusinessModel loginRequestBusinessModel) |
| 0 | 99 | | { |
| 0 | 100 | | var user = await _userManager.FindByNameAsync(loginRequestBusinessModel.Username) |
| 0 | 101 | | ?? throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The user does not exist."); |
| | 102 | |
|
| 0 | 103 | | if (await _userManager.IsLockedOutAsync(user)) |
| 0 | 104 | | { |
| 0 | 105 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The user is locked out."); |
| | 106 | | } |
| | 107 | |
|
| | 108 | | // Check password and generate token |
| 0 | 109 | | if (await _userManager.CheckPasswordAsync(user, loginRequestBusinessModel.Password)) |
| 0 | 110 | | { |
| 0 | 111 | | var notBefore = DateTime.UtcNow; |
| 0 | 112 | | var accessExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins); |
| 0 | 113 | | var refreshExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserRefreshTokenExpiresMins); |
| 0 | 114 | | var accessToken = await GenerateAccessTokenAsync(user, notBefore, accessExpires); |
| 0 | 115 | | var refreshToken = GenerateRefreshToken(user, notBefore, refreshExpires); |
| 0 | 116 | | user.RefreshTokenHash = LgdxHelper.GenerateSha256Hash(refreshToken); |
| 0 | 117 | | var result = await _userManager.UpdateAsync(user); |
| 0 | 118 | | if (!result.Succeeded) |
| 0 | 119 | | { |
| 0 | 120 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 121 | | } |
| 0 | 122 | | return new LoginResponseBusinessModel |
| 0 | 123 | | { |
| 0 | 124 | | AccessToken = accessToken, |
| 0 | 125 | | RefreshToken = refreshToken, |
| 0 | 126 | | ExpiresMins = _lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins |
| 0 | 127 | | }; |
| | 128 | | } |
| | 129 | | else |
| 0 | 130 | | { |
| | 131 | | // Password is incorrect |
| 0 | 132 | | var incrementLockoutResult = await _userManager.AccessFailedAsync(user); |
| 0 | 133 | | if (!incrementLockoutResult.Succeeded) |
| 0 | 134 | | { |
| | 135 | | // Return the same failure we do when resetting the lockout fails after a correct password. |
| 0 | 136 | | throw new LgdxIdentity400Expection(incrementLockoutResult.Errors); |
| | 137 | | } |
| 0 | 138 | | if (await _userManager.IsLockedOutAsync(user)) |
| 0 | 139 | | { |
| 0 | 140 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The user is locked out."); |
| | 141 | | } |
| 0 | 142 | | } |
| 0 | 143 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "Login failed."); |
| 0 | 144 | | } |
| | 145 | |
|
| | 146 | | public async Task ForgotPasswordAsync(ForgotPasswordRequestBusinessModel forgotPasswordRequestBusinessModel) |
| 0 | 147 | | { |
| 0 | 148 | | var user = await _userManager.FindByEmailAsync(forgotPasswordRequestBusinessModel.Email); |
| 0 | 149 | | if (user != null) |
| 0 | 150 | | { |
| 0 | 151 | | var token = await _userManager.GeneratePasswordResetTokenAsync(user); |
| 0 | 152 | | await _emailService.SendPasswordResetEmailAsync(user.Email!, user.Name!, user.UserName!, token); |
| 0 | 153 | | } |
| | 154 | | // For security reasons, we do not return a 404 status code. |
| 0 | 155 | | } |
| | 156 | |
|
| | 157 | | public async Task ResetPasswordAsync(ResetPasswordRequestBusinessModel resetPasswordRequestBusinessModel) |
| 0 | 158 | | { |
| 0 | 159 | | var user = await _userManager.FindByEmailAsync(resetPasswordRequestBusinessModel.Email) |
| 0 | 160 | | ?? throw new LgdxValidation400Expection(nameof(resetPasswordRequestBusinessModel.Token), ""); |
| | 161 | |
|
| 0 | 162 | | var result = await _userManager.ResetPasswordAsync(user, resetPasswordRequestBusinessModel.Token, resetPasswordReque |
| 0 | 163 | | if (!result.Succeeded) |
| 0 | 164 | | { |
| 0 | 165 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 166 | | } |
| 0 | 167 | | await _emailService.SendPasswordUpdateEmailAsync(user.Email!, user.Name!, user.UserName!); |
| 0 | 168 | | } |
| | 169 | |
|
| | 170 | | public async Task<RefreshTokenResponseBusinessModel> RefreshTokenAsync(RefreshTokenRequestBusinessModel refreshTokenRe |
| 0 | 171 | | { |
| | 172 | | // Validate the refresh token |
| 0 | 173 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| 0 | 174 | | TokenValidationParameters validationParameters = new() |
| 0 | 175 | | { |
| 0 | 176 | | ValidateIssuer = true, |
| 0 | 177 | | ValidateAudience = true, |
| 0 | 178 | | ValidateLifetime = true, |
| 0 | 179 | | ValidateIssuerSigningKey = true, |
| 0 | 180 | | ValidIssuer = _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 0 | 181 | | ValidAudience = _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 0 | 182 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_lgdxRobotCloudSecretConfiguration.LgdxUserJwtS |
| 0 | 183 | | ClockSkew = TimeSpan.Zero |
| 0 | 184 | | }; |
| 0 | 185 | | ClaimsPrincipal principal = tokenHandler.ValidateToken(refreshTokenRequestBusinessModel.RefreshToken, validationPara |
| 0 | 186 | | ?? throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "Invalid refresh to |
| | 187 | |
|
| | 188 | | // The token is valid, check the database |
| 0 | 189 | | var userId = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value |
| 0 | 190 | | ?? throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "The user ID is not |
| 0 | 191 | | var user = await _userManager.FindByIdAsync(userId) |
| 0 | 192 | | ?? throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "User not found."); |
| 0 | 193 | | if (user.RefreshTokenHash != LgdxHelper.GenerateSha256Hash(refreshTokenRequestBusinessModel.RefreshToken)) |
| 0 | 194 | | { |
| 0 | 195 | | throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "The refresh token is |
| | 196 | | } |
| | 197 | |
|
| | 198 | | // Generate new token pair and update the database |
| 0 | 199 | | var notBefore = DateTime.UtcNow; |
| 0 | 200 | | var accessExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins); |
| 0 | 201 | | var refreshExpires = validatedToken.ValidTo; // Reauthenticate to extend the expiration time |
| 0 | 202 | | var accessToken = await GenerateAccessTokenAsync(user, notBefore, accessExpires); |
| 0 | 203 | | var refreshToken = GenerateRefreshToken(user, notBefore, refreshExpires); |
| 0 | 204 | | user.RefreshTokenHash = LgdxHelper.GenerateSha256Hash(refreshToken); |
| 0 | 205 | | var result = await _userManager.UpdateAsync(user); |
| 0 | 206 | | if (!result.Succeeded) |
| 0 | 207 | | { |
| 0 | 208 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 209 | | } |
| | 210 | |
|
| | 211 | | // Generate new token pair |
| 0 | 212 | | return new RefreshTokenResponseBusinessModel() |
| 0 | 213 | | { |
| 0 | 214 | | AccessToken = accessToken, |
| 0 | 215 | | RefreshToken = refreshToken, |
| 0 | 216 | | ExpiresMins = _lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins |
| 0 | 217 | | }; |
| 0 | 218 | | } |
| | 219 | |
|
| | 220 | | public async Task<bool> UpdatePasswordAsync(string userId, UpdatePasswordRequestBusinessModel updatePasswordRequestBus |
| 0 | 221 | | { |
| 0 | 222 | | var user = await userManager.FindByIdAsync(userId) |
| 0 | 223 | | ?? throw new LgdxNotFound404Exception(); |
| | 224 | |
|
| 0 | 225 | | var result = await _userManager.ChangePasswordAsync(user, updatePasswordRequestBusinessModel.CurrentPassword, update |
| 0 | 226 | | if (!result.Succeeded) |
| 0 | 227 | | { |
| 0 | 228 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 229 | | } |
| 0 | 230 | | await _emailService.SendPasswordUpdateEmailAsync(user.Email!, user.Name!, user.UserName!); |
| 0 | 231 | | return true; |
| 0 | 232 | | } |
| | 233 | | } |