public async Task <BaseApiResponse> ResetPasswordAsync(UserForResetPasswordDto userForResetPasswordDto) { if (userForResetPasswordDto == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { "Invalid request." })); } var user = await _userManager.FindByEmailAsync(userForResetPasswordDto.Email); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { "Could not found any users registered with this email." })); } var decodedToken = WebEncoders.Base64UrlDecode(userForResetPasswordDto.Token); string normalToken = Encoding.UTF8.GetString(decodedToken); var result = await _userManager.ResetPasswordAsync(user, normalToken, userForResetPasswordDto.NewPassword); if (!result.Succeeded) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { "Could not reset password." })); } return(BaseApiResponseHelper.GenerateApiResponse(true, "Reset password", null, null)); }
// Revoke Token public async Task <BaseApiResponse> RevokeTokenAsync(string refreshToken) { // STEP 1: Check if refreshToken match any users var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == refreshToken)); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token did not match any users." })); } // STEP 2: Check if refreshToken is active or not var refreshTokenFromDb = user.RefreshTokens.Single(x => x.Token == refreshToken); if (!refreshTokenFromDb.IsActive) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token is not active." })); } // STEP 3: Revoke the current refresh token refreshTokenFromDb.Revoked = DateTime.UtcNow; // STEP 4: Delete all revoked tokens var revokedTokens = user.RefreshTokens.Where(t => t.IsActive == false).ToList(); _context.RemoveRange(revokedTokens); _context.Update(user); await _context.SaveChangesAsync(); return(BaseApiResponseHelper.GenerateApiResponse(true, "Revoke a token", null, null)); }
public async Task <BaseApiResponse> CreateRole(string roleName) { try { var result = await _roleManager.CreateAsync(new IdentityRole(roleName.ToLower().Trim())); if (!result.Succeeded) { var errs = new List <string>(); foreach (var item in result.Errors) { errs.Add(item.Description); } return(BaseApiResponseHelper.GenerateApiResponse(false, "create a new role", null, errs)); } else { return(BaseApiResponseHelper.GenerateApiResponse(true, "Create a new role", null, null)); } } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "create a new role", null, new List <string> { $"{ex.Message}." })); } }
public async Task <BaseApiResponse> GetByRoleId(string roleId) { try { var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get role", null, new List <string> { $"Role with id {roleId} did not match any roles." })); } var roleDto = _mapper.Map <RoleDto>(role); return(BaseApiResponseHelper.GenerateApiResponse(true, "Get role", new List <RoleDto> { roleDto }, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get role", null, new List <string> { $"{ex.Message}." })); } }
// Remove User public async Task <BaseApiResponse> RemoveUserById(string userId) { var userToRemove = await _userManager.FindByIdAsync(userId); if (userToRemove == null) { return(BaseApiResponseHelper.GenerateApiResponse(true, "remove user", null, new List <string> { $"User ID {userId} did not match any users." })); } var result = await _userManager.DeleteAsync(userToRemove); if (!result.Succeeded) { var errs = new List <string>(); foreach (var err in result.Errors) { errs.Add(err.Description); } return(BaseApiResponseHelper.GenerateApiResponse(true, "remove user", null, errs)); } else { return(BaseApiResponseHelper.GenerateApiResponse(true, "Remove user", null, null)); } }
// Get Specific User public async Task <BaseApiResponse> GetUserById(string userId) { try { var currentUser = await _userManager.FindByIdAsync(userId); var userRoles = await _userManager.GetRolesAsync(currentUser); var userRolesDto = _mapper.Map <IList <string> >(userRoles); var userForListingDto = _mapper.Map <UserForListingDto>(currentUser); userForListingDto.Roles = userRolesDto; return(BaseApiResponseHelper.GenerateApiResponse(true, "Get user", new List <UserForListingDto> { userForListingDto }, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get user", null, new List <string> { $"{ex.Message}." })); } }
// Get All Users public async Task <BaseApiResponse> GetAll(ClaimsPrincipal claimsPrincipal) { try { var currentUser = await _userManager.GetUserAsync(claimsPrincipal); var allUserExceptCurrentUser = await _userManager.Users.Where(u => u.Id != currentUser.Id).ToListAsync(); var users = new List <UserForListingDto>(); foreach (var item in allUserExceptCurrentUser) { var userRoles = await _userManager.GetRolesAsync(item); var userRolesDto = _mapper.Map <IList <string> >(userRoles); var userForListingDto = _mapper.Map <UserForListingDto>(item); userForListingDto.Roles = userRolesDto; users.Add(userForListingDto); } return(BaseApiResponseHelper.GenerateApiResponse(true, "Get all users", users, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get all users", null, new List <string> { $"{ex.Message}." })); } }
// Refresh Token public async Task <BaseApiResponse> RefreshTokenAsync(string refreshToken) { // STEP 1: Check if refreshToken match any users var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == refreshToken)); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token did not match any users." })); } // STEP 2: Check if refreshToken is active or not var refreshTokenFromDb = user.RefreshTokens.Single(x => x.Token == refreshToken); if (!refreshTokenFromDb.IsActive) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token is not active." })); } // STEP 3: Revoke the current refresh token refreshTokenFromDb.Revoked = DateTime.UtcNow; // STEP 4: Generate a new refresh token and save to database var newRefreshToken = CreateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); _context.Update(user); await _context.SaveChangesAsync(); // FINALLY: Generate new JWT Token JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user); var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var userForAuthenticationDto = new UserForAuthenticationDto() { FirstName = user.FirstName, LastName = user.LastName, Username = user.UserName, Email = user.Email, Roles = roles, AccessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), RefreshToken = newRefreshToken.Token, RefreshTokenExpiration = newRefreshToken.Expires }; return(BaseApiResponseHelper.GenerateApiResponse(true, "Get refresh token", new List <UserForAuthenticationDto> { userForAuthenticationDto }, null)); }
public async Task <BaseApiResponse> UpdateUserRoles(UserRolesForEditDto userRolesForEditDto, ClaimsPrincipal claimsPrincipal) { try { if (userRolesForEditDto.UserId == null) { return(BaseApiResponseHelper.GenerateApiResponse(true, "update roles for user", null, new List <string> { $"User ID is null." })); } var user = await _userManager.FindByIdAsync(userRolesForEditDto.UserId); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(true, "update roles for user", null, new List <string> { $"User ID {userRolesForEditDto.UserId} did not match any users." })); } var roles = await _userManager.GetRolesAsync(user); var result = await _userManager.RemoveFromRolesAsync(user, roles); // In case we forgot to select any roles for user, we will add this user to role user by default. var isUserInAnyRoles = userRolesForEditDto.UserRoles.Any(x => x.Selected == true); if (!isUserInAnyRoles) { result = await _userManager.AddToRolesAsync(user, new List <string> { Authorization.DEFAULT_ROLE.ToString() }); } else { result = await _userManager.AddToRolesAsync(user, userRolesForEditDto.UserRoles.Where(x => x.Selected).Select(y => y.RoleName)); } var currentUser = await _userManager.GetUserAsync(claimsPrincipal); await _signInManager.RefreshSignInAsync(currentUser); await ApplicationDbInitializer.SeedAdministratorUser(_userManager, _roleManager); return(BaseApiResponseHelper.GenerateApiResponse(true, "Update roles for user", null, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "update roles for user", null, new List <string> { $"{ex.Message}." })); } }
// Forgot Password public async Task <BaseApiResponse> ForgotPassword(ForgotPasswordDto forgotPasswordDto) { try { if (forgotPasswordDto == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { "Email is null." })); } var user = await _userManager.FindByEmailAsync(forgotPasswordDto.Email); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { "Could not found any users registered with this email." })); } var token = await _userManager.GeneratePasswordResetTokenAsync(user); var encodedToken = Encoding.UTF8.GetBytes(token); var validToken = WebEncoders.Base64UrlEncode(encodedToken); string url = $"{_configuration["ApplicationUrl"]}/reset-password?email={forgotPasswordDto.Email}&token={validToken}"; var mailRequest = new MailRequest { ToEmail = forgotPasswordDto.Email, Subject = "Reset Password Confirmation", Attachments = null, Body = "<h1>Follow the instructions to reset your password</h1>" + $"<p>To reset your password <a href='{url}'>Click here</a></p>" }; await _emailService.SendEmailAsync(mailRequest); return(BaseApiResponseHelper.GenerateApiResponse(true, "Reset password url has been sent to the email", null, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "handle your request.", null, new List <string> { $"{ex.Message}" })); } }
public async Task <BaseApiResponse> ListAllUsersFromRole(string roleId) { try { if (roleId == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "list all users from role", null, new List <string> { $"Role Id is null." })); } var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "list all users from role", null, new List <string> { $"Role with id {roleId} did not match any roles." })); } var users = new List <User>(_userManager.GetUsersInRoleAsync(role.Name).Result); var usersToReturn = new List <UserDto>(); foreach (var item in users) { usersToReturn.Add(_mapper.Map <UserDto>(item)); } var data = new RoleForListingUserDto { Id = role.Id, RoleName = role.Name, Users = usersToReturn }; return(BaseApiResponseHelper.GenerateApiResponse(true, "List all users from role", new List <RoleForListingUserDto> { data }, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "list all users from role", null, new List <string> { $"{ex.Message}." })); } }
// Register public async Task <BaseApiResponse> RegisterAsync(UserForRegisterDto userForRegisterDto) { var newUser = _mapper.Map <User>(userForRegisterDto); var userFromDb = await _userManager.FindByEmailAsync(userForRegisterDto.Email); if (userFromDb != null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "register new user", null, new List <string> { $"Email {newUser.Email} is already registered." })); } var result = await _userManager.CreateAsync(newUser, userForRegisterDto.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(newUser, Authorization.DEFAULT_ROLE.ToString()); } return(BaseApiResponseHelper.GenerateApiResponse(true, "Register new user", null, null)); }
public async Task <BaseApiResponse> GetAll() { try { var rolesDto = new List <RoleDto>(); var roles = await _roleManager.Roles.ToListAsync(); foreach (var item in roles) { rolesDto.Add(_mapper.Map <RoleDto>(item)); } return(BaseApiResponseHelper.GenerateApiResponse(true, "Get all roles", rolesDto, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get all roles", null, new List <string> { $"{ex.Message}." })); } }
public async Task <BaseApiResponse> DeleteRole(string roleId) { try { var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "delete role", null, new List <string> { $"Role with id {roleId} did not match any roles." })); } var result = await _roleManager.DeleteAsync(role); if (!result.Succeeded) { var errs = new List <string>(); foreach (var item in result.Errors) { errs.Add(item.Description); } return(BaseApiResponseHelper.GenerateApiResponse(false, "delete role", null, errs)); } else { return(BaseApiResponseHelper.GenerateApiResponse(true, "Delete role", null, null)); } } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "delete role", null, new List <string> { $"{ex.Message}." })); } }
// Login public async Task <BaseApiResponse> LoginAsync(UserForLoginDto userForLoginDto) { if (userForLoginDto == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Email or password is null." })); } var user = await _userManager.FindByEmailAsync(userForLoginDto.Email); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Could not find any accounts registered with this email." })); } // Checking user password if (await _userManager.CheckPasswordAsync(user, userForLoginDto.Password)) { JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user); var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var refreshToken = string.Empty; var refreshTokenExpiration = new DateTime(); // Check if user has any active refreshToken then give them this refreshToken if (user.RefreshTokens.Any(token => token.IsActive)) { var activeRefreshToken = user.RefreshTokens.Where(token => token.IsActive == true).FirstOrDefault(); refreshToken = activeRefreshToken.Token; refreshTokenExpiration = activeRefreshToken.Expires; } else // Otherwise create new refreshToken then update it to the database { var newRefreshToken = CreateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); refreshToken = newRefreshToken.Token; refreshTokenExpiration = newRefreshToken.Expires; _context.Update(user); _context.SaveChanges(); } var userForAuthenticationDto = new UserForAuthenticationDto() { FirstName = user.FirstName, LastName = user.LastName, Username = user.UserName, Email = user.Email, Roles = roles, AccessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), RefreshToken = refreshToken, RefreshTokenExpiration = refreshTokenExpiration }; return(BaseApiResponseHelper.GenerateApiResponse(true, "Logged in", new List <UserForAuthenticationDto> { userForAuthenticationDto }, null)); } return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Username or password is incorrect." })); }
public async Task <BaseApiResponse> GetUserRoles(string userId) { try { if (userId == null) { return(BaseApiResponseHelper.GenerateApiResponse(true, "get roles for user", null, new List <string> { $"User ID is null." })); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(true, "get roles for user", null, new List <string> { $"User ID {userId} did not match any users." })); } var listUserRolesDto = new List <UserRolesDto>(); foreach (var role in await _roleManager.Roles.ToListAsync()) { var userRolesDto = new UserRolesDto { RoleName = role.Name }; if (await _userManager.IsInRoleAsync(user, role.Name)) { userRolesDto.Selected = true; } else { userRolesDto.Selected = false; } listUserRolesDto.Add(userRolesDto); } var data = new UserRolesForEditDto { UserId = user.Id, Username = user.UserName, Email = user.Email, UserRoles = listUserRolesDto }; return(BaseApiResponseHelper.GenerateApiResponse(true, "Get roles for user", new List <UserRolesForEditDto> { data }, null)); } catch (Exception ex) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get roles for user", null, new List <string> { $"{ex.Message}." })); } }