| | 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.Administration; |
| | 7 | | using LGDXRobotCloud.API.Services.Common; |
| | 8 | | using LGDXRobotCloud.Data.DbContexts; |
| | 9 | | using LGDXRobotCloud.Data.Entities; |
| | 10 | | using LGDXRobotCloud.Data.Models.Business.Administration; |
| | 11 | | using LGDXRobotCloud.Data.Models.Business.Identity; |
| | 12 | | using LGDXRobotCloud.Utilities.Enums; |
| | 13 | | using LGDXRobotCloud.Utilities.Helpers; |
| | 14 | | using Microsoft.AspNetCore.Identity; |
| | 15 | | using Microsoft.EntityFrameworkCore; |
| | 16 | | using Microsoft.Extensions.Options; |
| | 17 | | using Microsoft.IdentityModel.Tokens; |
| | 18 | |
|
| | 19 | | namespace LGDXRobotCloud.API.Services.Identity; |
| | 20 | |
|
| | 21 | | public interface IAuthService |
| | 22 | | { |
| | 23 | | Task<LoginResponseBusinessModel> LoginAsync(LoginRequestBusinessModel loginRequestBusinessModel); |
| | 24 | | Task ForgotPasswordAsync(ForgotPasswordRequestBusinessModel forgotPasswordRequestBusinessModel); |
| | 25 | | Task ResetPasswordAsync(ResetPasswordRequestBusinessModel resetPasswordRequestBusinessModel); |
| | 26 | | Task<RefreshTokenResponseBusinessModel> RefreshTokenAsync(RefreshTokenRequestBusinessModel refreshTokenRequestBusiness |
| | 27 | | Task<bool> UpdatePasswordAsync(string userId, UpdatePasswordRequestBusinessModel updatePasswordRequestBusinessModel); |
| | 28 | | } |
| | 29 | |
|
| 22 | 30 | | public class AuthService( |
| 22 | 31 | | IActivityLogService activityLogService, |
| 22 | 32 | | LgdxContext context, |
| 22 | 33 | | IEmailService emailService, |
| 22 | 34 | | IOptionsSnapshot<LgdxRobotCloudSecretConfiguration> lgdxRobotCloudSecretConfiguration, |
| 22 | 35 | | SignInManager<LgdxUser> signInManager, |
| 22 | 36 | | UserManager<LgdxUser> userManager |
| 22 | 37 | | ) : IAuthService |
| | 38 | | { |
| 22 | 39 | | private readonly IActivityLogService _activityLogService = activityLogService ?? throw new ArgumentNullException(nameo |
| 22 | 40 | | private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context)); |
| 22 | 41 | | private readonly IEmailService _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService)); |
| 22 | 42 | | private readonly LgdxRobotCloudSecretConfiguration _lgdxRobotCloudSecretConfiguration = lgdxRobotCloudSecretConfigurat |
| 22 | 43 | | private readonly SignInManager<LgdxUser> _signInManager = signInManager ?? throw new ArgumentNullException(nameof(sign |
| 22 | 44 | | private readonly UserManager<LgdxUser> _userManager = userManager ?? throw new ArgumentNullException(nameof(userManage |
| | 45 | |
|
| | 46 | | private JwtSecurityToken GenerateJwtToken(List<Claim> claims, DateTime notBefore, DateTime expires) |
| 20 | 47 | | { |
| 20 | 48 | | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_lgdxRobotCloudSecretConfiguration.LgdxUserJwtSecr |
| 20 | 49 | | var credentials = new SigningCredentials(securityKey, _lgdxRobotCloudSecretConfiguration.LgdxUserJwtAlgorithm); |
| 20 | 50 | | return new JwtSecurityToken( |
| 20 | 51 | | _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 20 | 52 | | _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 20 | 53 | | claims, |
| 20 | 54 | | notBefore, |
| 20 | 55 | | expires, |
| 20 | 56 | | credentials); |
| 20 | 57 | | } |
| | 58 | |
|
| | 59 | | private async Task<string> GenerateAccessTokenAsync(LgdxUser user, DateTime notBefore, DateTime expires) |
| 10 | 60 | | { |
| 10 | 61 | | var userRoles = await _userManager.GetRolesAsync(user); |
| 10 | 62 | | var Claims = new List<Claim> |
| 10 | 63 | | { |
| 10 | 64 | | new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| 10 | 65 | | new (JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| 10 | 66 | | new (ClaimTypes.Name, user.UserName ?? string.Empty), |
| 10 | 67 | | new (ClaimTypes.Email, user.Email ?? string.Empty), |
| 10 | 68 | | new ("fullname", user.Name ?? string.Empty), |
| 10 | 69 | | }; |
| | 70 | | // Add Roles |
| 70 | 71 | | foreach (var userRole in userRoles) |
| 20 | 72 | | { |
| 20 | 73 | | Claims.Add(new Claim(ClaimTypes.Role, userRole)); |
| 20 | 74 | | } |
| | 75 | | // Add Role Claims |
| 10 | 76 | | { |
| 10 | 77 | | List<string> roleIds = await _context.Roles.AsNoTracking() |
| 10 | 78 | | .Where(r => userRoles.Select(ur => ur.ToUpper()).Contains(r.NormalizedName!)) |
| 10 | 79 | | .Select(r => r.Id ) |
| 10 | 80 | | .ToListAsync(); |
| 10 | 81 | | var roleClaims = await _context.RoleClaims.AsNoTracking() |
| 10 | 82 | | .Where(r => roleIds.Contains(r.RoleId)) |
| 10 | 83 | | .ToListAsync(); |
| 30 | 84 | | foreach (var roleClaim in roleClaims) |
| 0 | 85 | | { |
| 0 | 86 | | Claims.Add(new Claim(roleClaim.ClaimType!, roleClaim.ClaimValue!)); |
| 0 | 87 | | } |
| 10 | 88 | | } |
| 10 | 89 | | var token = GenerateJwtToken(Claims, notBefore, expires); |
| 10 | 90 | | return new JwtSecurityTokenHandler().WriteToken(token); |
| 10 | 91 | | } |
| | 92 | |
|
| | 93 | | private string GenerateRefreshToken(LgdxUser user, DateTime notBefore, DateTime expires) |
| 10 | 94 | | { |
| 10 | 95 | | var Claims = new List<Claim> |
| 10 | 96 | | { |
| 10 | 97 | | new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| 10 | 98 | | new (JwtRegisteredClaimNames.Sub, user.Id.ToString()), |
| 10 | 99 | | }; |
| 10 | 100 | | var token = GenerateJwtToken(Claims, notBefore, expires); |
| 10 | 101 | | var tokenStr = new JwtSecurityTokenHandler().WriteToken(token); |
| 10 | 102 | | return tokenStr; |
| 10 | 103 | | } |
| | 104 | |
|
| | 105 | | public async Task<LoginResponseBusinessModel> LoginAsync(LoginRequestBusinessModel loginRequestBusinessModel) |
| 14 | 106 | | { |
| 14 | 107 | | var user = await _userManager.FindByNameAsync(loginRequestBusinessModel.Username) |
| 14 | 108 | | ?? throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The username or password is i |
| | 109 | |
|
| 13 | 110 | | var loginResult = await _signInManager.PasswordSignInAsync(user, loginRequestBusinessModel.Password, false, true); |
| 13 | 111 | | if (loginResult.RequiresTwoFactor) |
| 5 | 112 | | { |
| 5 | 113 | | if (!string.IsNullOrEmpty(loginRequestBusinessModel.TwoFactorCode)) |
| 2 | 114 | | { |
| 2 | 115 | | loginResult = await _signInManager.TwoFactorAuthenticatorSignInAsync(loginRequestBusinessModel.TwoFactorCode, fa |
| 2 | 116 | | if (!loginResult.Succeeded) |
| 1 | 117 | | { |
| 1 | 118 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The 2FA code is invalid."); |
| | 119 | | } |
| 1 | 120 | | } |
| 3 | 121 | | else if (!string.IsNullOrEmpty(loginRequestBusinessModel.TwoFactorRecoveryCode)) |
| 2 | 122 | | { |
| 2 | 123 | | loginResult = await _signInManager.TwoFactorRecoveryCodeSignInAsync(loginRequestBusinessModel.TwoFactorRecoveryC |
| 2 | 124 | | if (!loginResult.Succeeded) |
| 1 | 125 | | { |
| 1 | 126 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The recovery code is invalid |
| | 127 | | } |
| 1 | 128 | | } |
| | 129 | | else |
| 1 | 130 | | { |
| 1 | 131 | | return new LoginResponseBusinessModel |
| 1 | 132 | | { |
| 1 | 133 | | AccessToken = string.Empty, |
| 1 | 134 | | RefreshToken = string.Empty, |
| 1 | 135 | | ExpiresMins = 0, |
| 1 | 136 | | RequiresTwoFactor = true |
| 1 | 137 | | }; |
| | 138 | | } |
| 2 | 139 | | } |
| 10 | 140 | | if (!loginResult.Succeeded) |
| 2 | 141 | | { |
| 2 | 142 | | if (loginResult.IsLockedOut) |
| 1 | 143 | | { |
| 1 | 144 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 1 | 145 | | { |
| 1 | 146 | | EntityName = nameof(LgdxUser), |
| 1 | 147 | | EntityId = user.Id.ToString(), |
| 1 | 148 | | Action = ActivityAction.LoginFailed, |
| 1 | 149 | | Note = "The account is locked out." |
| 1 | 150 | | }); |
| 1 | 151 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The account is locked out."); |
| | 152 | | } |
| | 153 | | else |
| 1 | 154 | | { |
| 1 | 155 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 1 | 156 | | { |
| 1 | 157 | | EntityName = nameof(LgdxUser), |
| 1 | 158 | | EntityId = user.Id.ToString(), |
| 1 | 159 | | Action = ActivityAction.LoginFailed, |
| 1 | 160 | | Note = "The username or password is invalid." |
| 1 | 161 | | }); |
| 1 | 162 | | throw new LgdxValidation400Expection(nameof(loginRequestBusinessModel.Username), "The username or password is in |
| | 163 | | } |
| | 164 | | } |
| | 165 | |
|
| 8 | 166 | | var notBefore = DateTime.UtcNow; |
| 8 | 167 | | var accessExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins); |
| 8 | 168 | | var refreshExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserRefreshTokenExpiresMins); |
| 8 | 169 | | var accessToken = await GenerateAccessTokenAsync(user, notBefore, accessExpires); |
| 8 | 170 | | var refreshToken = GenerateRefreshToken(user, notBefore, refreshExpires); |
| 8 | 171 | | user.RefreshTokenHash = LgdxHelper.GenerateSha256Hash(refreshToken); |
| 8 | 172 | | var updateTokenResult = await _userManager.UpdateAsync(user); |
| 8 | 173 | | if (!updateTokenResult.Succeeded) |
| 1 | 174 | | { |
| 1 | 175 | | throw new LgdxIdentity400Expection(updateTokenResult.Errors); |
| | 176 | | } |
| 7 | 177 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 7 | 178 | | { |
| 7 | 179 | | EntityName = nameof(LgdxUser), |
| 7 | 180 | | EntityId = user.Id.ToString(), |
| 7 | 181 | | Action = ActivityAction.LoginSuccess, |
| 7 | 182 | | }); |
| 7 | 183 | | return new LoginResponseBusinessModel |
| 7 | 184 | | { |
| 7 | 185 | | AccessToken = accessToken, |
| 7 | 186 | | RefreshToken = refreshToken, |
| 7 | 187 | | ExpiresMins = _lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins, |
| 7 | 188 | | RequiresTwoFactor = false |
| 7 | 189 | | }; |
| 8 | 190 | | } |
| | 191 | |
|
| | 192 | | public async Task ForgotPasswordAsync(ForgotPasswordRequestBusinessModel forgotPasswordRequestBusinessModel) |
| 2 | 193 | | { |
| 2 | 194 | | var user = await _userManager.FindByEmailAsync(forgotPasswordRequestBusinessModel.Email); |
| 2 | 195 | | if (user != null) |
| 1 | 196 | | { |
| 1 | 197 | | var token = await _userManager.GeneratePasswordResetTokenAsync(user); |
| 1 | 198 | | await _emailService.SendPasswordResetEmailAsync(user.Email!, user.Name!, user.UserName!, token); |
| 1 | 199 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 1 | 200 | | { |
| 1 | 201 | | EntityName = nameof(LgdxUser), |
| 1 | 202 | | EntityId = user.Id.ToString(), |
| 1 | 203 | | Action = ActivityAction.UserPasswordReset, |
| 1 | 204 | | }); |
| 1 | 205 | | } |
| | 206 | | // For security reasons, we do not return a 404 status code. |
| 2 | 207 | | } |
| | 208 | |
|
| | 209 | | public async Task ResetPasswordAsync(ResetPasswordRequestBusinessModel resetPasswordRequestBusinessModel) |
| 3 | 210 | | { |
| 3 | 211 | | var user = await _userManager.FindByEmailAsync(resetPasswordRequestBusinessModel.Email) |
| 3 | 212 | | ?? throw new LgdxValidation400Expection(nameof(resetPasswordRequestBusinessModel.Token), ""); |
| | 213 | |
|
| 2 | 214 | | var result = await _userManager.ResetPasswordAsync(user, resetPasswordRequestBusinessModel.Token, resetPasswordReque |
| 2 | 215 | | if (!result.Succeeded) |
| 1 | 216 | | { |
| 1 | 217 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 218 | | } |
| 1 | 219 | | await _emailService.SendPasswordUpdateEmailAsync(user.Email!, user.Name!, user.UserName!); |
| 1 | 220 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 1 | 221 | | { |
| 1 | 222 | | EntityName = nameof(LgdxUser), |
| 1 | 223 | | EntityId = user.Id.ToString(), |
| 1 | 224 | | Action = ActivityAction.UserPasswordUpdated, |
| 1 | 225 | | }); |
| 1 | 226 | | } |
| | 227 | |
|
| | 228 | | public async Task<RefreshTokenResponseBusinessModel> RefreshTokenAsync(RefreshTokenRequestBusinessModel refreshTokenRe |
| 4 | 229 | | { |
| | 230 | | // Validate the refresh token |
| 4 | 231 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| 4 | 232 | | TokenValidationParameters validationParameters = new() |
| 4 | 233 | | { |
| 4 | 234 | | ValidateIssuer = true, |
| 4 | 235 | | ValidateAudience = true, |
| 4 | 236 | | ValidateLifetime = true, |
| 4 | 237 | | ValidateIssuerSigningKey = true, |
| 4 | 238 | | ValidIssuer = _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 4 | 239 | | ValidAudience = _lgdxRobotCloudSecretConfiguration.LgdxUserJwtIssuer, |
| 4 | 240 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_lgdxRobotCloudSecretConfiguration.LgdxUserJwtS |
| 4 | 241 | | ClockSkew = TimeSpan.Zero |
| 4 | 242 | | }; |
| 4 | 243 | | ClaimsPrincipal principal = tokenHandler.ValidateToken(refreshTokenRequestBusinessModel.RefreshToken, validationPara |
| | 244 | |
|
| | 245 | | // The token is valid, check the database |
| 12 | 246 | | var userId = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value |
| 4 | 247 | | ?? throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "The user ID is not |
| 4 | 248 | | var user = await _userManager.FindByIdAsync(userId) |
| 4 | 249 | | ?? throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "User not found."); |
| 3 | 250 | | if (user.RefreshTokenHash != LgdxHelper.GenerateSha256Hash(refreshTokenRequestBusinessModel.RefreshToken)) |
| 1 | 251 | | { |
| 1 | 252 | | throw new LgdxValidation400Expection(nameof(refreshTokenRequestBusinessModel.RefreshToken), "The refresh token is |
| | 253 | | } |
| | 254 | |
|
| | 255 | | // Generate new token pair and update the database |
| 2 | 256 | | var notBefore = DateTime.UtcNow; |
| 2 | 257 | | var accessExpires = notBefore.AddMinutes(_lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins); |
| 2 | 258 | | var refreshExpires = validatedToken.ValidTo; // Reauthenticate to extend the expiration time |
| 2 | 259 | | var accessToken = await GenerateAccessTokenAsync(user, notBefore, accessExpires); |
| 2 | 260 | | var refreshToken = GenerateRefreshToken(user, notBefore, refreshExpires); |
| 2 | 261 | | user.RefreshTokenHash = LgdxHelper.GenerateSha256Hash(refreshToken); |
| 2 | 262 | | var result = await _userManager.UpdateAsync(user); |
| 2 | 263 | | if (!result.Succeeded) |
| 1 | 264 | | { |
| 1 | 265 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 266 | | } |
| | 267 | |
|
| | 268 | | // Generate new token pair |
| 1 | 269 | | return new RefreshTokenResponseBusinessModel() |
| 1 | 270 | | { |
| 1 | 271 | | AccessToken = accessToken, |
| 1 | 272 | | RefreshToken = refreshToken, |
| 1 | 273 | | ExpiresMins = _lgdxRobotCloudSecretConfiguration.LgdxUserAccessTokenExpiresMins |
| 1 | 274 | | }; |
| 1 | 275 | | } |
| | 276 | |
|
| | 277 | | public async Task<bool> UpdatePasswordAsync(string userId, UpdatePasswordRequestBusinessModel updatePasswordRequestBus |
| 3 | 278 | | { |
| 3 | 279 | | var user = await userManager.FindByIdAsync(userId) |
| 3 | 280 | | ?? throw new LgdxNotFound404Exception(); |
| | 281 | |
|
| 2 | 282 | | var result = await _userManager.ChangePasswordAsync(user, updatePasswordRequestBusinessModel.CurrentPassword, update |
| 2 | 283 | | if (!result.Succeeded) |
| 1 | 284 | | { |
| 1 | 285 | | throw new LgdxIdentity400Expection(result.Errors); |
| | 286 | | } |
| 1 | 287 | | await _emailService.SendPasswordUpdateEmailAsync(user.Email!, user.Name!, user.UserName!); |
| 1 | 288 | | await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel |
| 1 | 289 | | { |
| 1 | 290 | | EntityName = nameof(LgdxUser), |
| 1 | 291 | | EntityId = user.Id.ToString(), |
| 1 | 292 | | Action = ActivityAction.UserPasswordUpdated, |
| 1 | 293 | | }); |
| 1 | 294 | | return true; |
| 1 | 295 | | } |
| | 296 | | } |