public async Task <ActionResult> Login(IotUser @user) { if (string.IsNullOrEmpty(@user.UserName)) { return(View()); } if (string.IsNullOrEmpty(@user.Password)) { return(View()); } //Context var OwinContext = HttpContext.GetOwinContext(); //实例化UserStore对象 var userStore = new IotUserStore(_sysUserService); //UserManager var userManager = new IotUserManager(userStore); //signInManager var signInManager = new IotSignInManager(userManager, AutherticationManager); //登录 var signInStatus = await signInManager.PasswordSignInAsync(@user.UserName, @user.Password, true, shouldLockout : false); //状态 switch (signInStatus) { //成功 case SignInStatus.Success: //标示 //System.Security.Claims.ClaimsIdentity identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //授权登陆 //AutherticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties { IsPersistent = true }, identity); return(RedirectToAction("index", "home")); //锁定 case SignInStatus.LockedOut: Response.Write("LockedOut!"); break; //要求验证 case SignInStatus.RequiresVerification: Response.Write("RequiresVerification!"); break; //登录失败 case SignInStatus.Failure: Response.Write("Failure!"); break; } return(View(@user)); }
private async Task LoadAsync(IotUser user) { var userName = await _userManager.GetUserNameAsync(user); var phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel { PhoneNumber = phoneNumber }; }
private async Task GenerateAndSendPasswordResetToken(IotUser user) { var token = await _userManager.GeneratePasswordResetTokenAsync(user); var confirmationLink = Url.Action( nameof(ResetPassword), nameof(Account), new { token, user = user.Id }, Request.Scheme, Request.Host.ToString()); _ = _emailService.SendResetPasswordConfirmation(confirmationLink, user); }
private async Task GenerateAndSendTokeByEmail(IotUser user) { var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action( nameof(EmailConfirmed), nameof(Account), new { token, user = user.Id }, Request.Scheme, Request.Host.ToString()); _ = _emailService.SendEmailConfirmation(confirmationLink, user); }
public Task SendResetPasswordConfirmation(string confirmationLink, IotUser user) { _emailService.SendAsync( user.Email, $"{user.Firstname}, zlecono zmianę hasła", "<h3>Otrzymujesz ten email, bo uruchomiono opcję resetowania hasła do serwisu 'Home Automation'</h3><br />" + $"Kliknij <a href=\"{confirmationLink}\">link</a>, by potwierdzić operację<br />" + "Nastąpi przekierowanie do formularza zmiany hasła.<br />" + "Zignoruj tę wiadomość, jeśli nie zlecełeś(aś) operacji.", true); _logger.LogDebug("Password reset email sent to {Email}.", user.Email); return(Task.CompletedTask); }
private async Task LoadAsync(IotUser user) { var email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new IotUser { 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); 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 _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _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()); }
public Task SendEmailConfirmation(string confirmationLink, IotUser user) { var result = _emailService.SendAsync( user.Email, //"*****@*****.**", $"{user.Firstname}, confirm your registration", $"<h3>Kliknij link, by potwierdzić rejestrację do serwisu 'Home Automation'</h3><br />" + $"<a href=\"{confirmationLink}\">Potwierdź adres email</a><br />" + $"Zignoruj tę wiadomość, jeśli nie donowywałeś(aś) rejestracji.", true); if (result.IsCompletedSuccessfully) { _logger.LogDebug("Account activation email sent to {Email}.", user.Email); } return(Task.CompletedTask); }
private async Task <ClaimsIdentity> CreateIdentity() { ClaimsIdentity identity = null; //用户 var user = new IotUser(); user.Id = Guid.NewGuid().ToString(); user.UserName = "******"; user.NickName = "农业气象物联网"; //Context var owinContext = HttpContext.GetOwinContext(); var userManager = OwinContextExtensions.GetUserManager <UserManager <IotUser, string> >(owinContext); identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); return(identity); }
public async Task <ActionResult> Registration(RegistrationViewModel model) { if (!ModelState.IsValid) { return(View(model)); } if (!_userManagerService.IsEmailUnique(model.Email)) { ModelState.AddModelError("", "This email is taken"); return(View(model)); } if (!IsPhoneNumberValid(model.PhoneNumber)) { ModelState.AddModelError("", "Check phone number. Allowed characters: 0-9, '+- .'. Ex: 0048.501 502 503. The only country code accepted is 48."); return(View(model)); } var random = new Random(); var user = new IotUser() { Firstname = model.FirstName, Lastname = model.LastName, Email = model.Email }; user.UserName = $"{user.Firstname}{user.Lastname}"; user.UserName = RemoveDiacritics(user.UserName); user.UserName = RemoveNotLetterNorDigit(user.UserName); user.UserName += random.Next(1000).ToString("D3"); user.NormalizedUserName = user.UserName.ToUpper(); user.NormalizedEmail = user.Email.ToUpper(); try { // Create user IdentityResult createUserResult = await _userManager.CreateAsync(user, model.Password); if (createUserResult.Succeeded) { _logger.LogInformation("User {User} with email {Email} created.", user.UserName, user.Email); // Add to Roles. Add first user created with FirstName="Administrator" to Administrator role :o IdentityResult addToRoleResult; if (_userManagerService.IsOnlyAdministratorExisting() && model.FirstName == "Administrator") { addToRoleResult = await _userManager.AddToRoleAsync(user, "Administrator"); if (addToRoleResult.Succeeded) { _logger.LogInformation("User with email {Email} added to role {Role}", user.Email, "Administrator"); } else { _logger.LogWarning("Error adding user with email {Email} to role {Role}", user.Email, "Administrator"); } } addToRoleResult = await _userManager.AddToRoleAsync(user, "User"); if (addToRoleResult.Succeeded) { _logger.LogInformation("User with email {Email} added to role {Role}", user.Email, "User"); } else { _logger.LogWarning("Error adding user with email {Email} to role {Role}", user.Email, "User"); } _ = GenerateAndSendTokeByEmail(user); return(RedirectToAction(nameof(ConfirmRegistration))); } createUserResult.Errors .Select(e => e.Description) .ToList() .ForEach(e => ModelState.AddModelError("", e)); return(View(model)); } catch (Exception e) { _logger.LogError(e, "Error creating user."); } return(View(model)); // consider redirect to error page }
public async Task ConfirmEmailAsync(IotUser user) { _context.Users.FirstOrDefault(u => u.Email == user.Email).EmailConfirmed = true; await _context.SaveChangesAsync(); }