/// <summary> /// Verify password recovery token and change user password /// </summary> /// <param name="userId">user id</param> /// <param name="token">user token</param> /// <param name="newPassword">new user password</param> /// <returns>instance of DefaultServiceResult</returns> public virtual async Task <ServiceNoResult> VerifyPasswordRecoveryTokenAsync(string userIdentification, string token, string newPassword) { if (string.IsNullOrEmpty(userIdentification)) { throw new ArgumentNullException(nameof(userIdentification)); } if (string.IsNullOrEmpty(token)) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(newPassword)) { throw new ArgumentNullException(nameof(newPassword)); } GalleryUser user = await userManager.FindByIdAsync(userIdentification); var resultFactory = new RequestNoResult(); if (user == null) { return(resultFactory.BadRequest("Used doesnt exist")); } var resutlToken = await userManager.ResetPasswordAsync(user, token, newPassword); if (!resutlToken.Succeeded) { resultFactory.BadRequest(resutlToken.Errors.Select(item => item.Description).ToList()); } return(resultFactory.GoodRequest()); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new GalleryUser { Id = Guid.NewGuid().ToString(), Password = model.Password, FullName = model.FullName, UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); var rm = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new GalleryContext())); string userString = model.UserRole == RegisterViewModel.UserRoles.User ? "User" : "Admin"; if (!rm.RoleExists(userString)) { rm.Create(new IdentityRole(userString)); } if (!UserManager.IsInRole(user.Id, userString)) { UserManager.AddToRole(user.Id, userString); } return(RedirectToAction("Index", "Album")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// Verify confirmation token /// </summary> /// <param name="userId">user id</param> /// <param name="token">user token</param> /// <returns>instance of DefaultServiceResult</returns> public virtual async Task <ServiceNoResult> VerifyConfirmationTokenAsync(string userId, string token) { if (string.IsNullOrEmpty(userId)) { throw new ArgumentNullException(nameof(userId)); } if (string.IsNullOrEmpty(token)) { throw new ArgumentNullException(nameof(token)); } GalleryUser user = await userManager.FindByIdAsync(userId); var resultFactory = new RequestNoResult(); if (user == null) { return(resultFactory.BadRequest("Used doesnt exist")); } var resutlToken = await userManager.ConfirmEmailAsync(user, token); return(resultFactory.GoodRequest()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { ReturnUrl = returnUrl; if (ModelState.IsValid) { var user = new GalleryUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); await _emailSender.SendEmailConfirmationAsync(Input.Email, callbackUrl); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(Url.GetLocalUrl(returnUrl))); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task LoadSharedKeyAndQrCodeUriAsync(GalleryUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (!string.IsNullOrEmpty(unformattedKey)) { SharedKey = FormatKey(unformattedKey); AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey); } }
public void UpdateUser(GalleryUser person) { using (var context = new GalleryContext()) { var user = context.Users.Where(p => p.Id == person.Id).FirstOrDefault(); user.FullName = person.FullName; user.Email = person.Email; user.Password = person.Password; user.UserName = person.UserName; context.SaveChanges(); } }
public ActionResult Edit(GalleryUser user) { if (ModelState.IsValid) { if (string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password) || string.IsNullOrWhiteSpace(user.Email) || string.IsNullOrWhiteSpace(user.FullName)) { ModelState.AddModelError("error", "Error: username, password or fullname is empty!"); return(View(user)); } Repo.UpdateUser(user); } return(RedirectToAction("Index")); }
/// <summary> /// External login using SignInManager /// </summary> /// <returns></returns> public virtual async Task <bool> ExecuteExternalLogin() { var result = await signInManager.GetExternalLoginInfoAsync(); if (result == null) // error in authentication { return(false); } ExternalAuthFactory authFactory = ExternalAuthFactory.GetInstance(result.LoginProvider); if (authFactory != null && !authFactory.CanAuthenticate(result.Principal.Claims)) { return(false); } IUploader uploader = await GetUserByIdAsync(authFactory.Identifier); if (uploader != null) //User already registered so sign him in { await signInManager.SignInAsync(uploader as GalleryUser, false); // login user return(true); } string password = Guid.NewGuid().ToString().Substring(0, 8); // password can be random because user will never type in this password var galleryUser = new GalleryUser { Id = authFactory.Identifier, Email = authFactory.Email, UserName = authFactory.UserName, IsExternal = true }; var resultOfRegistration = await RegistrationProcess(galleryUser, password); if (!resultOfRegistration.Success) // registration unsuccessful { return(false); } await signInManager.SignInAsync(resultOfRegistration.Result as GalleryUser, false); // login user return(true); }
/// <summary> /// Register user (used for local registration) /// Method calls RegistrationProcess /// </summary> /// <param name="userName">username</param> /// <param name="email">email</param> /// <param name="password">password</param> /// <returns>instance of ServiceResult</returns> public virtual async Task <ServiceResult <IUploader> > RegisterUserAsync(string userName, string email, string password) { if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException(nameof(userName)); } if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } var galleryUser = new GalleryUser { Email = email, UserName = userName }; return(await RegistrationProcess(galleryUser, password)); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { throw new ApplicationException("Error loading external login information during confirmation."); } var user = new GalleryUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(Url.GetLocalUrl(returnUrl))); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ReturnUrl = returnUrl; return(Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = "~/Identity/Account/Login"; // ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { bool noUsersInDb = this.userManager.Users.Any() == false; var user = new GalleryUser { UserName = Input.Username, FirstName = Input.FirstName, LastName = Input.LastName, Email = Input.Email, PhoneNumber = Input.PhoneNumber, DeliveryAddress = Input.DeliveryAddress, Orders = new List <Order>() }; var result = await this.userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { if (noUsersInDb) { await this.userManager.AddToRoleAsync(user, "Admin"); } this.logger.LogInformation("User created a new account with password."); #region Email Confirmation //var code = await this.userManager.GenerateEmailConfirmationTokenAsync(user); //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); //var callbackUrl = Url.Page( // "/Account/ConfirmEmail", // pageHandler: null, // values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, // protocol: Request.Scheme); //await this.emailSender.SendEmailAsync(Input.Email, "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); #endregion if (this.userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { // await this.signInManager.SignInAsync(user, isPersistent: false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }