private AuthTokenSM GenerateAccessToken(UserSM user, string securityKey, int expiryHours, string issuer) { var now = DateTime.Now; var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = now.AddHours(expiryHours); var token = new JwtSecurityToken( issuer, issuer, claims, expires: expires, signingCredentials: creds ); string tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(new AuthTokenSM { Token = tokenString, Expiry = expires, Issued = now }); }
public void GetUserById_Test() { //Arrange MockRepository mocks = new MockRepository(); IUserLogic logic = mocks.Stub <IUserLogic>(); //UserSM user = new UserSM(); //user.UserId = 1; //user.UserName = "******"; int id = 1; int idDos = 2; UserSM user = new UserSM(); user.UserId = 1; user.SecLev = "Admin"; UserSM userDos = new UserSM(); userDos.UserId = 2; userDos.SecLev = "Power User"; using (mocks.Record()) { SetupResult.For(logic.GetUserById(id)).Return(user); SetupResult.For(logic.GetUserById(idDos)).Return(userDos); } //Act(execute) UserSM testUser = logic.GetUserById(id); //Assert(check) Assert.AreEqual("Admin", testUser.SecLev); logic.VerifyAllExpectations(); }
public async Task <UserSM> AddUser(UserSM user, string password) { var currentUser = await _userManager.FindByNameAsync(user.Email); if (currentUser != null) { AddBusinessError(BusinessErrorCodes.DataAlreadyExists, "User already exists"); return(null); } var appUser = Mapper.Map <TAppUser>(user); var result = await _userManager.CreateAsync(appUser, password); if (result.Succeeded) { var newUser = await _userManager.FindByNameAsync(user.Email); user.Id = newUser.ApplicationId; return(user); } foreach (var e in result.Errors) { AddBusinessError(BusinessErrorCodes.Generic, e.Description); } return(null); }
public async Task <AuthResultSM> RegisterUserAsync(UserSM user, string password) { var appUser = Mapper.Map <TAppUser>(user); var result = await _userManager.CreateAsync(appUser, password); return(AuthResultFactory.CreateResultFromIdentityResult(result)); }
public async Task DeleteUser(UserSM user) { var dbUser = await _userManager.FindByNameAsync(user.Email); if (dbUser == null) { AddBusinessError(BusinessErrorCodes.DataNotFound, "User cannot be found"); return; } if (dbUser.Email == _sessionInfo.User?.Email) { AddBusinessError(BusinessErrorCodes.CouldNotUpdate, "CannotDeleteCurrentUser"); } if (BusinessStateValid) { var result = await _userManager.DeleteAsync(dbUser); if (result.Succeeded) { return; } AddBusinessError(BusinessErrorCodes.Generic, "User could not be removed"); } }
public async Task <InteractionResultSM> ChangePasswordAsync(UserSM user, string oldPassword, string newPassword) { var applicationUser = await _userManager.FindByIdAsync(user.Id); var result = await _userManager.ChangePasswordAsync(applicationUser, oldPassword, newPassword); return(InteractionResultSMFactory.CreateResult(user, result)); }
public async Task <InteractionResultSM> CreateUserAsync(UserSM user, string password) { var applicationUser = Mapper.Map <ApplicationUser>(user); var createResult = await _userManager.CreateAsync(applicationUser, password); user.Id = applicationUser?.Id; return(InteractionResultSMFactory.CreateResult(user, createResult)); }
private string GetGreetingName(UserSM user) { if (string.IsNullOrEmpty(user.FirstName)) { return(user.UserName); } return(user.FirstName); }
public async Task SignInAsync(UserSM user) { var appUser = Mapper.Map <TAppUser>(user); if (appUser != null) { await _signInManager.SignInAsync(appUser, isPersistent : false); } }
public async Task <InteractionResultSM> UpdateUserAsync(UserSM user) { var applicationUser = await _userManager.FindByIdAsync(user.Id); applicationUser.FirstName = user.FirstName; applicationUser.LastName = user.LastName; applicationUser.Email = user.Email; applicationUser.PhoneNumber = user.PhoneNumber; var result = await _userManager.UpdateAsync(applicationUser); return(InteractionResultSMFactory.CreateResult(user, result)); }
public static InteractionResultSM CreateResult(UserSM user, IdentityResult identityResult) { if (identityResult.Succeeded) { return(new InteractionResultSM { Succeeded = true, User = user }); } return(new InteractionResultSM { Succeeded = false, User = null, Errors = identityResult.Errors.ToDictionary(x => x.Code, y => y.Description) }); }
public UserVM Map(UserSM user) { UserVM person = new UserVM(); //guy.Password = new PasswordSM(); person.UserId = user.UserId; person.UserName = user.UserName; person.Password.ConfirmPassword = user.Password.ConfirmPassword; person.Password.NewPassword = user.Password.NewPassword; person.Password.CurrentPassword = user.Password.CurrentPassword; person.SecLev = user.SecLev; return(person); }
public UserSM Map(UserVM user) { UserSM guy = new UserSM(); //guy.Password = new PasswordSM(); guy.UserId = user.UserId; guy.UserName = user.UserName; guy.Password.ConfirmPassword = user.Password.ConfirmPassword; guy.Password.NewPassword = user.Password.NewPassword; guy.Password.CurrentPassword = user.Password.CurrentPassword; guy.SecLev = user.SecLev; return(guy); }
public async Task <AuthResultSM> SeedData() { try { foreach (var appRole in ApplicationRolesDefinition.AllRoles()) { var exists = await _roleManager.RoleExistsAsync(appRole); if (!exists) { var role = (TAppRole)Activator.CreateInstance(typeof(TAppRole)); // TAppRole.Create(); role.Name = appRole; await _roleManager.CreateAsync(role); } } var adminUser = new UserSM { Email = "*****@*****.**", FirstName = "Admin", LastName = "Admin" }; // if there are any users in the admin role we don't want to create any users, so just return var usersInAdminRole = await _userManager.GetUsersInRoleAsync(ApplicationRolesDefinition.RoleAdmin); if (usersInAdminRole.Any()) { return(AuthResultFactory.CreateGenericSuccessResult()); } var result = await RegisterUserAsync(adminUser, "Qwe!23"); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(adminUser.Email); await _userManager.AddToRoleAsync(user, ApplicationRolesDefinition.RoleAdmin); return(AuthResultFactory.CreateGenericSuccessResult()); } else { return(AuthResultFactory.CreateGenericFailResult(result.Errors.FirstOrDefault()?.Description)); } } catch (Exception ex) { return(AuthResultFactory.CreateGenericFailResult(ex.Message)); } }
public async Task UpdateUserRoles(UserSM user, string role) { var currentUser = await GetUserByEmail(user.Email); //var currentRoles = _usersData.GetCurrentUserRoles(currentUser.ApplicationId).ToList(); var currentRole = await GetUserRoleInternalAsync(currentUser); if (!string.IsNullOrEmpty(currentRole)) { await _userManager.RemoveFromRoleAsync(currentUser, currentRole); } await _userManager.AddToRoleAsync(currentUser, role); }
private UserRolesVM PopulateUserRolesViewModel(UserSM user, IEnumerable <string> rolesForUser) { var model = new UserRolesVM(); model.Id = user.Id; model.UserName = user.UserName; model.Name = user.FirstName + " " + user.LastName; model.Email = user.Email; model.UserRoles = Enum.GetValues(typeof(UserRole)).Cast <UserRole>().Select(x => new CheckBoxListItemVM { Id = x.ToString(), DisplayName = x.ToString() }).ToList(); model.UserRoles.ForEach(x => x.IsChecked = rolesForUser.Contains(x.Id)); return(model); }
public IHttpActionResult Create([FromBody] UserSM userSM) { try { UserServices service = new UserServices(); Users user = new Users(); user.Username = userSM.Username; user.Pass = userSM.Pass; service.Create(user); return(Ok(userSM)); } catch (Exception e) { string error = e.Message; return(BadRequest("Error: " + error)); } }
public async Task <IActionResult> Update(string id) { var applicationUser = await _context.ApplicationUser.SingleOrDefaultAsync(m => m.Id == id); var user = new UserSM { Id = applicationUser.Id, Email = applicationUser.Email, Role = applicationUser.Role, UserName = applicationUser.UserName }; UserRoleVM model = new UserRoleVM { User = user }; PopulateRoles(model); return(View(model)); }
public async Task <NotifierResponseSM> SendConfirmationNotificationAsync(UserSM user, string callbackUrl) { if (user != null) { var message = new MessageSM { From = GetFrom(), To = user.Email, GreetingName = GetGreetingName(user), Subject = "Confirm your email", MessageBody = $"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>link</a>", }; var response = await _notifierService.SendNotificationAsync(message); return(response); } return(null); }
public async Task <NotifierResponseSM> SendForgotPasswordNotificationAsync(UserSM user, string callbackUrl) { if (user != null) { var message = new MessageSM { From = GetFrom(), To = user.Email, GreetingName = GetGreetingName(user), Subject = "Reset Password", MessageBody = $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>", }; var response = await _notifierService.SendNotificationAsync(message); return(response); } return(null); }
public async Task <bool> UpdatePassword(UserSM user, string oldPassword, string newPassword) { var currentUser = await _userManager.FindByNameAsync(user.Email); if (currentUser != null) { AddBusinessError(BusinessErrorCodes.DataAlreadyExists, "User already exists"); return(false); } var result = await _userManager.ChangePasswordAsync(currentUser, oldPassword, newPassword); if (result.Succeeded) { return(true); } AddBusinessError(BusinessErrorCodes.CouldNotUpdate, result.Errors.FirstOrDefault()?.Description); return(false); }
public static UserSM Map(UserVM human) { UserSM User = new UserSM(); User.userFirstName = human.userFirstName; User.userLastName = human.userLastName; User.userName = human.userName; User.userPassword = human.userPassword; User.ConfirmUserPassword = human.ConfirmUserPassword; User.userEmail = human.userEmail; User.ConfirmUserEmail = human.ConfirmUserEmail; User.userPhoneNumber = human.userPhoneNumber; User.userStreet = human.userStreet; User.userCity = human.userCity; User.userState = human.userState; User.userZipcode = human.userZipcode; User.userID = human.userID; User.userPosition = human.userPosition; return(User); }
public static UserVM Map(UserSM human) //Find a way to Map from one List to another List each object { UserVM User = new UserVM(); User.userFirstName = human.userFirstName; User.userLastName = human.userLastName; User.userName = human.userName; User.userPassword = human.userPassword; User.ConfirmUserPassword = human.ConfirmUserPassword; User.userEmail = human.userEmail; User.ConfirmUserEmail = human.ConfirmUserEmail; User.userPhoneNumber = human.userPhoneNumber; User.userStreet = human.userStreet; User.userCity = human.userCity; User.userState = human.userState; User.userZipcode = human.userZipcode; User.userID = human.userID; User.userPosition = human.userPosition; return(User); }
public Tuple <string, string> GenerateAndRegisterAccessAndRefreshTokens(UserSM user, string securityKey, int expiryHours, string issuer, int refreshTokenHours) { var authToken = GenerateAccessToken(user, securityKey, expiryHours, issuer); _authTokenCache.AddAuthToken(authToken); _authTokensData.AddAuthToken(authToken); _authTokensData.DeleteRefreshTokenForUser(user.Id); var refreshToken = new RefreshTokenSM { Expiry = DateTime.Now.AddHours(refreshTokenHours), RefreshToken = GenerateRefreshToken(), UserId = user.Id }; _authTokensData.AddRefreshToken(refreshToken); return(new Tuple <string, string>(authToken.Token, refreshToken.RefreshToken)); }
public async Task <UserSM> UpdateUser(UserSM user) { var currentUser = await _userManager.FindByNameAsync(user.Email); if (currentUser == null) { AddBusinessError(BusinessErrorCodes.DataNotFound, "User cannot be found"); return(null); } currentUser.FirstName = user.FirstName; currentUser.LastName = user.LastName; var result = await _userManager.UpdateAsync(currentUser); if (result.Succeeded) { return(user); } AddBusinessError(BusinessErrorCodes.Generic, "User could not be updated"); return(null); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { string code = await _authService.GeneratePasswordResetTokenAsync(model.Email); if (code == null) { return(RedirectToAction(nameof(ForgotPasswordConfirmation))); } UserSM user = await _authService.FindByEmailAsync(model.Email); var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme); await _emailSender.SendEmailAsync(model.Email, "Reset Password", $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); return(RedirectToAction(nameof(ForgotPasswordConfirmation))); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <string> GetUserRole(UserSM user) { var currentUser = await GetUserByEmail(user.Email); return(await GetUserRoleInternalAsync(currentUser)); }
public async Task <IEnumerable <string> > GetRolesForUserAsync(UserSM user) { var applicationUser = Mapper.Map <ApplicationUser>(user); return(await _userManager.GetRolesAsync(applicationUser)); }
public async Task <InteractionResultSM> ResetPasswordAsync(UserSM user, string code, string password) { IdentityResult result = await _userManager.ResetPasswordAsync(Mapper.Map <ApplicationUser>(user), code, password); return(InteractionResultSMFactory.CreateResult(user, result)); }
public async Task <AuthResultSM> UpdateCurrentUser(ClaimsPrincipal principal, UserSM userUpdates) { var user = await _userManager.GetUserAsync(principal); if (user == null) { return(AuthResultFactory.CreateUserNotFoundResult()); } if (userUpdates.Email != user.Email) { var setEmailResult = await _userManager.SetEmailAsync(user, userUpdates.Email); if (!setEmailResult.Succeeded) { return(AuthResultFactory.CreateResultFromIdentityResult(setEmailResult)); } var setUserNameResult = await _userManager.SetUserNameAsync(user, userUpdates.Email); if (!setUserNameResult.Succeeded) { return(AuthResultFactory.CreateResultFromIdentityResult(setEmailResult)); } } user.FirstName = userUpdates.FirstName; user.LastName = userUpdates.LastName; var result = await _userManager.UpdateAsync(user); return(AuthResultFactory.CreateResultFromIdentityResult(result)); }