public async Task <IActionResult> OnPostAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "Incorrect password."); return(Page()); } } IdentityResult result = await _userManager.DeleteAsync(user); string userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return(Redirect("~/")); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } IdentityResult addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword); if (!addPasswordResult.Succeeded) { foreach (IdentityError error in addPasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(Page()); } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your password has been set."; return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } bool isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); string userId = await _userManager.GetUserIdAsync(user); if (!isTwoFactorEnabled) { throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled."); } IEnumerable <string> recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId); StatusMessage = "You have generated new recovery codes."; return(RedirectToPage("./ShowRecoveryCodes")); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } SwishUser user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToPage("./ResetPasswordConfirmation")); } IdentityResult result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return(RedirectToPage("./ResetPasswordConfirmation")); } foreach (IdentityError error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } SwishUser user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } string recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty); Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id); return(LocalRedirect(returnUrl ?? Url.Content("~/"))); } if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return(RedirectToPage("./Lockout")); } else { _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id); ModelState.AddModelError(string.Empty, "Invalid recovery code entered."); return(Page()); } }
public async Task <IActionResult> OnGetLinkLoginCallbackAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'."); } IdentityResult result = await _userManager.AddLoginAsync(user, info); if (!result.Succeeded) { StatusMessage = "The external login was not added. External logins can only be associated with one account."; return(RedirectToPage()); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = "The external login was added."; return(RedirectToPage()); }
public async Task <IActionResult> OnGetAsync(string email) { if (email == null) { return(RedirectToPage("/Index")); } SwishUser user = await _userManager.FindByEmailAsync(email); if (user == null) { return(NotFound($"Unable to load user with email '{email}'.")); } Email = email; // Once you add a real email sender, you should remove this code that lets you confirm the account DisplayConfirmAccountLink = true; if (DisplayConfirmAccountLink) { string userId = await _userManager.GetUserIdAsync(user); string code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); EmailConfirmationUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); } return(Page()); }
public IActionResult Profile(string User) { if (User != null) { SwishUser CurUser = GetUser().Result; DbOperations DBop = new DbOperations(_context, CurUser); string picpath = DBop.GetPicPath(User); if (DBop.IsBlocked(User)) { ViewBag.IBlocked = false; ViewBag.IsBlocked = true; ViewBag.Posts = null; } else { ViewBag.IBlocked = DBop.IBlocked(User); ViewBag.IsBlocked = false; ViewBag.Posts = DBop.GetPosts(User).ToList(); } ViewBag.FriendCount = DBop.GetFriends(User).Count(); ViewBag.picpath = picpath; ViewBag.IsMyFriend = DBop.CheckIfFriend(CurUser.UserName, User); ViewBag.user = DBop.GetUser(User); ViewBag.me = CurUser; } else { return(RedirectToAction("Index")); } return(View(new PostModel())); }
public async Task <IActionResult> UploadFile(IFormFile file, string remove = "false") { SwishUser User = GetUser().Result; DbOperations DBop = new DbOperations(_context, User); if (remove == "true") { DBop.RemovePPic(); if (System.IO.File.Exists(_hostingEnvironment.WebRootPath + "/Images/" + User.Id + "-Thumb.png")) { System.IO.File.Delete(_hostingEnvironment.WebRootPath + "/Images/" + User.Id + "-Thumb.png"); } } if (file == null || file.Length == 0) { return(RedirectToAction("Index")); } using (MemoryStream memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); using (Image image = Image.FromStream(memoryStream)) { // TODO: ResizeImage(img, 100, 100); int width; int height; const int size = 100; if (image.Width > image.Height) { width = size; height = Convert.ToInt32(image.Height * size / (double)image.Width); } else { width = Convert.ToInt32(image.Width * size / (double)image.Height); height = size; } Bitmap res = new Bitmap(width, height); using (Graphics graphic = Graphics.FromImage(res)) { graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.DrawImage(image, 0, 0, width, height); } res.Save(_hostingEnvironment.WebRootPath + "/Images/" + User.Id + "-Thumb.png", ImageFormat.Png); DBop.SavePPic(); } } return(RedirectToAction("Index")); }
public async Task <IActionResult> OnPostChangeEmailAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } string email = await _userManager.GetEmailAsync(user); if (Input.NewEmail != email) { string userId = await _userManager.GetUserIdAsync(user); string code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); string callbackUrl = Url.Page( "/Account/ConfirmEmailChange", pageHandler: null, values: new { userId = userId, email = Input.NewEmail, code = code }, protocol: Request.Scheme); MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress("No-Reply", "*****@*****.**"); BodyBuilder bodyBuilder = new BodyBuilder(); MailboxAddress to = new MailboxAddress(Input.NewEmail); SmtpClient client = new SmtpClient(); bodyBuilder.HtmlBody = $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."; message.From.Add(from); message.To.Add(to); message.Subject = "Confirm your email"; message.Body = bodyBuilder.ToMessageBody(); client.Connect("mail.deepseagt.com", 465, true); client.Authenticate("*****@*****.**", "M^TQ*b#5Hfgb"); client.Send(message); client.Disconnect(true); client.Dispose(); StatusMessage = "Confirmation link to change email sent. Please check your email."; return(RedirectToPage()); } StatusMessage = "Your email is unchanged."; return(RedirectToPage()); }
public async Task <IActionResult> OnPostAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } string phoneNumber = await _userManager.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { IdentityResult setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { string userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'."); } } if (Input.FName != user.FName) { user.FName = Input.FName; } if (Input.LName != user.LName) { user.LName = Input.LName; } if (Input.Gender != user.Gender) { user.Gender = Input.Gender; } if (Input.DOB != user.DOB) { user.DOB = Input.DOB; } await _userManager.UpdateAsync(user); await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your profile has been updated"; return(RedirectToPage()); }
public async Task <IActionResult> OnGet() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } return(Page()); }
public void SavePPic() { SwishUser entity = _context.Users.FirstOrDefault(Me => Me.UserName == (Cureuser.UserName)); if (entity != null) { entity.PPicPath = Cureuser.Id + "-Thumb.png"; _context.Users.Update(entity); _context.SaveChanges(); } }
public ActionResult Profile(PostModel userPost, IFormFile[] Files) { SwishUser CurUser = GetUser().Result; DbOperations DBop = new DbOperations(_context, CurUser, _hostingEnvironment); DBop.SavePost(userPost, Files); ViewBag.Posts = DBop.GetPosts(CurUser.UserName); return(RedirectToAction("Profile", "Home")); }
public void RemovePPic() { Console.WriteLine("<------------Remove profile pic------------>"); SwishUser entity = _context.Users.FirstOrDefault(Me => Me.UserName == (Cureuser.UserName)); if (entity != null) { entity.PPicPath = "ProfilePlaceholder.png"; _context.Users.Update(entity); _context.SaveChanges(); } }
private async Task LoadAsync(SwishUser user) { string email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); }
public async Task <SwishUser> GetUser() { try { applicationUser = await _UserManager.GetUserAsync(User); return(applicationUser); } catch { return(null); } }
private void Load(SwishUser user) { List <SwishUser> swishUsers = new List <SwishUser>(); DbOperations dbOperations = new DbOperations(_context, user, _hostingEnvironment); foreach (string asd in dbOperations.GetBlockedUsers()) { SwishUser BlockedUser = _userManager.FindByNameAsync(asd).Result; ViewData["UserID"] += asd + Environment.NewLine; swishUsers.Add(BlockedUser); } ViewData["ResUsers"] = swishUsers; }
public async Task <IActionResult> OnGetAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } await LoadSharedKeyAndQrCodeUriAsync(user); return(Page()); }
public async Task <IActionResult> OnPostAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user); return(Page()); } // Strip spaces and hypens string verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty); bool is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); if (!is2faTokenValid) { ModelState.AddModelError("Input.Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync(user); return(Page()); } await _userManager.SetTwoFactorEnabledAsync(user, true); string userId = await _userManager.GetUserIdAsync(user); _logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId); StatusMessage = "Your authenticator app has been verified."; if (await _userManager.CountRecoveryCodesAsync(user) == 0) { IEnumerable <string> recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); return(RedirectToPage("./ShowRecoveryCodes")); } else { return(RedirectToPage("./TwoFactorAuthentication")); } }
public async Task <IActionResult> OnPost() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } await _signInManager.ForgetTwoFactorClientAsync(); StatusMessage = "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code."; return(RedirectToPage()); }
public async Task <IActionResult> OnGetAsync(string returnUrl = null) { // Ensure the user has gone through the username & password screen first SwishUser user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } ReturnUrl = returnUrl; return(Page()); }
public async Task <IActionResult> OnGet() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!await _userManager.GetTwoFactorEnabledAsync(user)) { throw new InvalidOperationException($"Cannot disable 2FA for user with ID '{_userManager.GetUserId(User)}' as it's not currently enabled."); } return(Page()); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { SwishUser user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToPage("./ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 string code = await _userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); string callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { area = "Identity", code }, protocol: Request.Scheme); MimeMessage message = new MimeMessage(); MailboxAddress from = new MailboxAddress("No-Reply", "*****@*****.**"); BodyBuilder bodyBuilder = new BodyBuilder(); MailboxAddress to = new MailboxAddress(Input.Email); SmtpClient client = new SmtpClient(); bodyBuilder.HtmlBody = $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."; message.From.Add(from); message.To.Add(to); message.Subject = "Reset Password"; message.Body = bodyBuilder.ToMessageBody(); client.Connect("mail.deepseagt.com", 465, true); client.Authenticate("*****@*****.**", "M^TQ*b#5Hfgb"); client.Send(message); client.Disconnect(true); client.Dispose(); return(RedirectToPage("./ForgotPasswordConfirmation")); } return(Page()); }
public async Task <IActionResult> OnGetAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } CurrentLogins = await _userManager.GetLoginsAsync(user); OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) .ToList(); ShowRemoveButton = user.PasswordHash != null || CurrentLogins.Count > 1; return(Page()); }
public async Task <IActionResult> OnGetAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } bool hasPassword = await _userManager.HasPasswordAsync(user); if (hasPassword) { return(RedirectToPage("./ChangePassword")); } return(Page()); }
private async Task LoadSharedKeyAndQrCodeUriAsync(SwishUser user) { // Load the authenticator key & QR code URI to display on the form string unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); string email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
private async Task LoadAsync(SwishUser user) { string userName = await _userManager.GetUserNameAsync(user); string phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel { FName = user.FName, LName = user.LName, DOB = user.DOB, PPicPath = user.PPicPath, Gender = user.Gender, PhoneNumber = phoneNumber }; }
public async Task <IActionResult> OnGet() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null; Is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user); IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user); RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user); return(Page()); }
public async Task <IActionResult> OnPostAsync() { SwishUser user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } IdentityResult disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false); if (!disable2faResult.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'."); } _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User)); StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app"; return(RedirectToPage("./TwoFactorAuthentication")); }