public async Task <IActionResult> Edit(string id) { if (id == null) { return(NotFound()); } IdentityUser user = await _userManager.FindByIdAsync(id); if (user == null) { return(NotFound()); } IList <string> existingUserRoles = (await _userManager.GetRolesAsync(user)); string userRole = SecurityConstants.GuestRoleString; if (existingUserRoles.Count > 0) { userRole = existingUserRoles.ElementAt(0); } UserEditVM vm = new UserEditVM() { Email = user.Email, Username = user.UserName, UserRole = userRole }; ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IActionResult> Create(UserCreateVM vm) { if (ModelState.IsValid) { IdentityUser user = new IdentityUser { UserName = vm.Username, Email = vm.Email }; IdentityResult result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { _logger.LogInformation($"Created new account for {user.UserName} with id {user.Id}"); // check if role string is valid bool isValidRole = SecurityConstants.GetRoles().Contains(vm.UserRole); if (isValidRole) { await _userManager.AddToRoleAsync(user, vm.UserRole); _logger.LogInformation($"{vm.UserRole} role assigned to new user {user.UserName} with id {user.Id}"); } return(RedirectToAction(nameof(Index)).WithSuccess($"Created new user {user.UserName} {(isValidRole ? $"with role {vm.UserRole}" : "")}")); } AddErrors(result); } // If we got this far, something failed, redisplay form ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IActionResult> Create(UserCreateVM vm) { if (ModelState.IsValid) { ApplicationUser user = new ApplicationUser { UserName = vm.Username, Email = vm.Email, TwoFactorEnabled = vm.IsTwoFactorEnabled }; IdentityResult result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { _logger.LogInformation($"Created new account for {user.UserName} with id {user.Id}"); // check if role string is valid bool isValidRole = SecurityConstants.GetRoles().Contains(vm.UserRole); if (isValidRole) { await _userManager.AddToRoleAsync(user, vm.UserRole); _logger.LogInformation($"{vm.UserRole} role assigned to new user {user.UserName} with id {user.Id}"); } // verify user email string emailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); IdentityResult emaiVerifiedResult = await _userManager.ConfirmEmailAsync(user, emailToken); if (emaiVerifiedResult.Succeeded) { _logger.LogInformation($"Email verified for new user {user.UserName} with id {user.Id} and email {vm.Email}"); } else { _logger.LogInformation($"Email verify failed for {user.UserName} with id {user.Id} and email {vm.Email} due to errors {emaiVerifiedResult.Errors}"); } if (!string.IsNullOrWhiteSpace(vm.PhoneNumber)) { // verify phone number string phoneVerifyToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, vm.PhoneNumber); IdentityResult phoneVeifyResult = await _userManager.ChangePhoneNumberAsync(user, vm.PhoneNumber, phoneVerifyToken); _logger.LogInformation($"Phone verified new user {user.UserName} with id {user.Id} and phone {vm.PhoneNumber} = {phoneVeifyResult.Succeeded}"); } return(RedirectToAction(nameof(Index)).WithSuccess($"Created new user {user.UserName} {(isValidRole ? $"with role {vm.UserRole}" : "")}")); } AddErrors(result); } // If we got this far, something failed, redisplay form ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IActionResult> Create(CreateAppUserCommand vm) { vm.BaseUrl = new Uri(new Uri(Request.Scheme + "://" + Request.Host.Value), "Identity/Account/ConfirmEmail").ToString(); IdentityResult result = await _mediator.Send(vm); if (result.Succeeded) { _logger.LogInformation($"Created new account for {vm.Username}"); return(RedirectToAction(nameof(Index)).WithSuccess($"Created new user {vm.Username}")); } AddErrors(result); // If we got this far, something failed, redisplay form ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IActionResult> Edit(EditAppUserCommand vm) { List <string> errors = await _mediator.Send(vm); AddErrors(errors); // check if we have any errors and redirect if successful if (errors.Count == 0) { _logger.LogInformation("User edit operation successful"); return(RedirectToAction(nameof(Index)).WithSuccess("User Editing done")); } // If we got this far, something failed, redisplay form ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IActionResult> Edit(string id) { UserDTO uDTO = await _mediator.Send(new GetAppUserByIdQuery() { Id = id }); if (uDTO == null) { return(NotFound()); } EditAppUserCommand vm = _mapper.Map <EditAppUserCommand>(uDTO); ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <IdentityResult> Handle(CreateAppUserCommand request, CancellationToken cancellationToken) { ApplicationUser user = new ApplicationUser { UserName = request.Username, Email = request.Email }; IdentityResult result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { //TODO use logger here Console.WriteLine($"Created new account for {user.UserName} with id {user.Id}"); // check if role string is valid bool isValidRole = SecurityConstants.GetRoles().Contains(request.UserRole); if (isValidRole) { await _userManager.AddToRoleAsync(user, request.UserRole); Console.WriteLine($"{request.UserRole} role assigned to new user {user.UserName} with id {user.Id}"); } // send confirmation email to user var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = QueryHelpers.AddQueryString(request.BaseUrl, new Dictionary <string, string>() { { "code", code }, { "userId", user.Id } }); try { await _emailSender.SendEmailAsync( user.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); Console.WriteLine($"Confirmation email sent to ${user.UserName}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(result); }
public IActionResult Create() { ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View()); }
public async Task <IActionResult> Edit(string id, UserEditVM vm) { if (ModelState.IsValid) { if (id == null) { return(NotFound()); } IdentityUser user = await _userManager.FindByIdAsync(id); if (user == null) { return(NotFound()); } List <IdentityError> identityErrors = new List <IdentityError>(); // change password if not null string newPassword = vm.Password; if (newPassword != null) { string passResetToken = await _userManager.GeneratePasswordResetTokenAsync(user); IdentityResult passResetResult = await _userManager.ResetPasswordAsync(user, passResetToken, newPassword); if (passResetResult.Succeeded) { _logger.LogInformation("User password changed"); } else { identityErrors.AddRange(passResetResult.Errors); } } // change username if changed if (user.UserName != vm.Username) { IdentityResult usernameChangeResult = await _userManager.SetUserNameAsync(user, vm.Username); if (usernameChangeResult.Succeeded) { _logger.LogInformation("Username changed"); } else { identityErrors.AddRange(usernameChangeResult.Errors); } } // change email if changed if (user.Email != vm.Email) { string emailResetToken = await _userManager.GenerateChangeEmailTokenAsync(user, vm.Email); IdentityResult emailChangeResult = await _userManager.ChangeEmailAsync(user, vm.Email, emailResetToken); if (emailChangeResult.Succeeded) { _logger.LogInformation("email changed"); } else { identityErrors.AddRange(emailChangeResult.Errors); } } // change user role if not present in user bool isValidRole = SecurityConstants.GetRoles().Contains(vm.UserRole); List <string> existingUserRoles = (await _userManager.GetRolesAsync(user)).ToList(); bool isRoleChanged = !existingUserRoles.Any(r => r == vm.UserRole); if (isValidRole) { if (isRoleChanged) { // remove existing user roles if any await _userManager.RemoveFromRolesAsync(user, existingUserRoles); // add new Role to user from VM await _userManager.AddToRoleAsync(user, vm.UserRole); } } // check if we have any errors and redirect if successful if (identityErrors.Count == 0) { _logger.LogInformation("User edit operation successful"); return(RedirectToAction(nameof(Index)).WithSuccess("User Editing done")); } AddErrors(identityErrors); } // If we got this far, something failed, redisplay form ViewData["UserRole"] = new SelectList(SecurityConstants.GetRoles()); return(View(vm)); }
public async Task <List <string> > Handle(EditAppUserCommand request, CancellationToken cancellationToken) { List <string> errors = new List <string>(); ApplicationUser user = await _userManager.FindByIdAsync(request.Id); if (user == null) { errors.Add($"Unable to find user with id {request.Id}"); } List <IdentityError> identityErrors = new List <IdentityError>(); // change password if not null string newPassword = request.Password; if (!string.IsNullOrWhiteSpace(newPassword)) { string passResetToken = await _userManager.GeneratePasswordResetTokenAsync(user); IdentityResult passResetResult = await _userManager.ResetPasswordAsync(user, passResetToken, newPassword); if (passResetResult.Succeeded) { Console.WriteLine("User password changed"); } else { identityErrors.AddRange(passResetResult.Errors); } } // change username if changed if (user.UserName != request.Username) { IdentityResult usernameChangeResult = await _userManager.SetUserNameAsync(user, request.Username); if (usernameChangeResult.Succeeded) { Console.WriteLine("Username changed"); } else { identityErrors.AddRange(usernameChangeResult.Errors); } } // change email if changed if (user.Email != request.Email) { string emailResetToken = await _userManager.GenerateChangeEmailTokenAsync(user, request.Email); IdentityResult emailChangeResult = await _userManager.ChangeEmailAsync(user, request.Email, emailResetToken); if (emailChangeResult.Succeeded) { Console.WriteLine("email changed"); } else { identityErrors.AddRange(emailChangeResult.Errors); } } // change user role if not present in user bool isValidRole = SecurityConstants.GetRoles().Contains(request.UserRole); List <string> existingUserRoles = (await _userManager.GetRolesAsync(user)).ToList(); bool isRoleChanged = !existingUserRoles.Any(r => r == request.UserRole); if (isValidRole) { if (isRoleChanged) { // remove existing user roles if any await _userManager.RemoveFromRolesAsync(user, existingUserRoles); // add new Role to user from VM await _userManager.AddToRoleAsync(user, request.UserRole); } } foreach (IdentityError iError in identityErrors) { errors.Add(iError.Description); } return(errors); }
public async Task <IdentityResult> Handle(CreateAppUserCommand request, CancellationToken cancellationToken) { ApplicationUser user = new ApplicationUser { UserName = request.Username, DisplayName = request.DisplayName, Email = request.Email, PhoneNumber = request.PhoneNumber, GenderId = request.GenderId, ShiftRoleId = request.ShiftRoleId, ShiftGroupId = request.ShiftGroupId, OfficeId = request.OfficeId, Designation = request.Designation, IsActive = request.IsActive }; IdentityResult result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { //TODO use logger here Console.WriteLine($"Created new account for {user.UserName} with id {user.Id}"); // check if role string is valid bool isValidRole = SecurityConstants.GetRoles().Contains(request.UserRole); if (isValidRole) { await _userManager.AddToRoleAsync(user, request.UserRole); Console.WriteLine($"{request.UserRole} role assigned to new user {user.UserName} with id {user.Id}"); } // verify user email string emailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); IdentityResult emaiVerifiedResult = await _userManager.ConfirmEmailAsync(user, emailToken); if (emaiVerifiedResult.Succeeded) { Console.WriteLine($"Email verified for new user {user.UserName} with id {user.Id} and email {user.Email}"); } else { Console.WriteLine($"Email verify failed for {user.UserName} with id {user.Id} and email {user.Email} due to errors {emaiVerifiedResult.Errors}"); } if (!string.IsNullOrWhiteSpace(user.PhoneNumber)) { // verify phone number string phoneVerifyToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, user.PhoneNumber); IdentityResult phoneVeifyResult = await _userManager.ChangePhoneNumberAsync(user, user.PhoneNumber, phoneVerifyToken); Console.WriteLine($"Phone verified new user {user.UserName} with id {user.Id} and phone {user.PhoneNumber} = {phoneVeifyResult.Succeeded}"); } /** * // send confirmation email to user * var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); * var callbackUrl = QueryHelpers.AddQueryString(request.BaseUrl, new Dictionary<string, string>() { { "code", code }, { "userId", user.Id } }); * try * { * await _emailSender.SendEmailAsync( * user.Email, * "Please confirm your email for WRLDC Shift Roster web app", * $"Please confirm your account of WRLDC Shift Roster web app by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>"); * * Console.WriteLine($"Email address Confirmation mail sent to ${user.UserName}"); * } * catch (Exception ex) * { * Console.WriteLine(ex.Message); * } **/ } return(result); }