コード例 #1
0
        public async Task <IActionResult> OnPostAsync( )
        {
            if (this.ModelState.IsValid)
            {
                HeimdallUser user = await this.userManager.FindByEmailAsync(this.Input.Email).ConfigureAwait(false);

                if (user == null || !await this.userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(this.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 this.userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                string callbackUrl = this.Url.Page(
                    "/Account/ResetPassword",
                    null,
                    new { area = "Identity", code },
                    this.Request.Scheme);

                await this.emailSender.SendEmailAsync(
                    this.Input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode( callbackUrl )}'>clicking here</a>.")
                .ConfigureAwait(false);

                return(this.RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(this.Page( ));
        }
コード例 #2
0
        public async Task NotifyOfAttachmentAsync(string userId, Ticket ticket, TicketAttachment attachment)
        {
            HeimdallUser user =
                await this.context.Users
                .FirstOrDefaultAsync(u => u.Id == userId)
                .ConfigureAwait(false);

            Notification notification = new Notification
            {
                TicketId    = ticket.Id,
                Description =
                    $"{user.FullName} added an attachment on Ticket titled: '{ticket.Title}', named, '{attachment.Description}'",
                Created     = DateTime.Now,
                SenderId    = userId,
                RecipientId = ticket.DeveloperUserId
            };

            await this.context.Notifications
            .AddAsync(notification)
            .ConfigureAwait(false);

            await this.context
            .SaveChangesAsync( )
            .ConfigureAwait(false);

            string to = ticket.DeveloperUser.Email;

            string subject =
                $"For project: {ticket.Project.Name}, ticket: {ticket.Title}, priority: {ticket.TicketPriority.Name}";

            await this.emailService
            .SendEmailAsync(to, subject, notification.Description)
            .ConfigureAwait(false);
        }
コード例 #3
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            this.logger.LogInformation(
                "User with ID '{UserId}' asked for their personal data.",
                this.userManager.GetUserId(this.User));

            // Only include personal data for download
            Dictionary <string, string> personalData      = new Dictionary <string, string>( );
            IEnumerable <PropertyInfo>  personalDataProps = typeof(HeimdallUser).GetProperties( )
                                                            .Where(prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));

            foreach (PropertyInfo p in personalDataProps)
            {
                personalData.Add(p.Name, p.GetValue(user)?.ToString( ) ?? "null");
            }

            IList <UserLoginInfo> logins = await this.userManager.GetLoginsAsync(user).ConfigureAwait(false);

            foreach (UserLoginInfo l in logins)
            {
                personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
            }

            this.Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");

            return(new FileContentResult(JsonSerializer.SerializeToUtf8Bytes(personalData), "application/json"));
        }
コード例 #4
0
        public List <HeimdallUser> SortListOfDevsByTicketCountAsync(
            List <HeimdallUser> users,
            List <Ticket> tickets)
        {
            int i, j;
            int n = users.Count;

            for (j = n; j > 0; j--)
            {
                for (i = 0; i < j; i++)
                {
                    List <ProjectUser> pu1 = users[i].ProjectUsers;
                    int tc1 = pu1.Sum(pu => tickets.Where(t => t.DeveloperUserId == users[i].Id).ToList( ).Count);

                    List <ProjectUser> pu2 = users[i + 1].ProjectUsers;
                    int tc2 = pu2.Sum(
                        pu => tickets.Where(t => t.DeveloperUserId == users[i + 1].Id)
                        .ToList( )
                        .Count);

                    if (tc2 >= tc1)
                    {
                        continue;
                    }

                    HeimdallUser temp = users[i];
                    users[i]     = users[i + 1];
                    users[i + 1] = temp;
                }
            }

            return(users);
        }
コード例 #5
0
        public async Task <IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey)
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound("Unable to load user with ID 'user.Id'."));
            }

            IdentityResult result = await this.userManager.RemoveLoginAsync(user, loginProvider, providerKey)
                                    .ConfigureAwait(false);

            if (!result.Succeeded)
            {
                this.StatusMessage = "The external login was not removed.";

                return(this.RedirectToPage( ));
            }

            await this.signInManager.RefreshSignInAsync(user).ConfigureAwait(false);

            this.StatusMessage = "The external login was removed.";

            return(this.RedirectToPage( ));
        }
コード例 #6
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            IdentityResult disable2FaResult =
                await this.userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);

            if (!disable2FaResult.Succeeded)
            {
                throw new InvalidOperationException(
                          $"Unexpected error occurred disabling 2FA for user with ID '{this.userManager.GetUserId( this.User )}'.");
            }

            this.logger.LogInformation(
                "User with ID '{UserId}' has disabled 2fa.",
                this.userManager.GetUserId(this.User));
            this.StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app";

            return(this.RedirectToPage("./TwoFactorAuthentication"));
        }
コード例 #7
0
        public async Task <IActionResult> OnPostAsync( )
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page( ));
            }

            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            IdentityResult addPasswordResult = await this.userManager.AddPasswordAsync(user, this.Input.NewPassword)
                                               .ConfigureAwait(false);

            if (!addPasswordResult.Succeeded)
            {
                foreach (IdentityError error in addPasswordResult.Errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.Description);
                }

                return(this.Page( ));
            }

            await this.signInManager.RefreshSignInAsync(user).ConfigureAwait(false);

            this.StatusMessage = "Your password has been set.";

            return(this.RedirectToPage( ));
        }
コード例 #8
0
        public async Task <IActionResult> ManageUserRoles(ManageUserRolesViewModel heimdallUser)
        {
            if (!this.User.IsInRole("DemoUser"))
            {
                HeimdallUser user = await this.context.Users.FindAsync(heimdallUser.User.Id).ConfigureAwait(false);

                IEnumerable <string> roles = await this.RolesService.ListUserRolesAsync(user).ConfigureAwait(false);

                await this.userManager.RemoveFromRolesAsync(user, roles).ConfigureAwait(false);

                string[] userRoles = heimdallUser.SelectedRoles;

                // string userRole = HeimdallUser.SelectedRoles.FirstOrDefault();
                foreach (string role in userRoles)
                {
                    if (Enum.TryParse(role, out Roles roleValue))
                    {
                        await this.RolesService.AddUserToRoleAsync(user, role).ConfigureAwait(false);
                    }
                }

                return(this.RedirectToAction("ManageUserRoles"));
            }
            else
            {
                this.TempData["DemoLockout"] =
                    "Your changes have not been saved. To make changes to the database, please log in as a full user.";

                return(this.RedirectToAction("Index", "Home"));
            }
        }
コード例 #9
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            bool isTwoFactorEnabled = await this.userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false);

            string userId = await this.userManager.GetUserIdAsync(user).ConfigureAwait(false);

            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 this.userManager
                                                 .GenerateNewTwoFactorRecoveryCodesAsync(user, 10)
                                                 .ConfigureAwait(false);

            this.RecoveryCodes = recoveryCodes.ToArray( );

            this.logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId);
            this.StatusMessage = "You have generated new recovery codes.";

            return(this.RedirectToPage("./ShowRecoveryCodes"));
        }
コード例 #10
0
        public async Task <IActionResult> OnGetLinkLoginCallbackAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound("Unable to load user with ID 'user.Id'."));
            }

            ExternalLoginInfo info =
                await this.signInManager.GetExternalLoginInfoAsync(user.Id).ConfigureAwait(false);

            if (info == null)
            {
                throw new InvalidOperationException(
                          $"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
            }

            IdentityResult result = await this.userManager.AddLoginAsync(user, info).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                this.StatusMessage =
                    "The external login was not added. External logins can only be associated with one account.";

                return(this.RedirectToPage( ));
            }

            // Clear the existing external cookie to ensure a clean login process
            await this.HttpContext.SignOutAsync(IdentityConstants.ExternalScheme).ConfigureAwait(false);

            this.StatusMessage = "The external login was added.";

            return(this.RedirectToPage( ));
        }
コード例 #11
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            if (!this.ModelState.IsValid)
            {
                await this.LoadSharedKeyAndQrCodeUriAsync(user).ConfigureAwait(false);

                return(this.Page( ));
            }

            // Strip spaces and hypens
            string verificationCode = this.Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            bool is2FaTokenValid = await this.userManager
                                   .VerifyTwoFactorTokenAsync(
                user,
                this.userManager.Options.Tokens
                .AuthenticatorTokenProvider,
                verificationCode)
                                   .ConfigureAwait(false);

            if (!is2FaTokenValid)
            {
                this.ModelState.AddModelError("Input.Code", "Verification code is invalid.");
                await this.LoadSharedKeyAndQrCodeUriAsync(user).ConfigureAwait(false);

                return(this.Page( ));
            }

            await this.userManager.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);

            string userId = await this.userManager.GetUserIdAsync(user).ConfigureAwait(false);

            this.logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId);

            this.StatusMessage = "Your authenticator app has been verified.";

            if (await this.userManager.CountRecoveryCodesAsync(user).ConfigureAwait(false) == 0)
            {
                IEnumerable <string> recoveryCodes = await this.userManager
                                                     .GenerateNewTwoFactorRecoveryCodesAsync(user, 10)
                                                     .ConfigureAwait(false);

                this.RecoveryCodes = recoveryCodes.ToArray( );

                return(this.RedirectToPage("./ShowRecoveryCodes"));
            }

            return(this.RedirectToPage("./TwoFactorAuthentication"));
        }
コード例 #12
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl           = returnUrl ?? this.Url.Content("~/");
            this.ExternalLogins =
                (await this.signInManager.GetExternalAuthenticationSchemesAsync( ).ConfigureAwait(false)).ToList( );

            if (this.ModelState.IsValid)
            {
                HeimdallUser user = new HeimdallUser {
                    UserName = this.Input.Email, Email = this.Input.Email
                };
                IdentityResult result =
                    await this.userManager.CreateAsync(user, this.Input.Password).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    this.logger.LogInformation("User created a new account with password.");

                    string code = await this.userManager.GenerateEmailConfirmationTokenAsync(user)
                                  .ConfigureAwait(false);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    string callbackUrl = this.Url.Page(
                        "/Account/ConfirmEmail",
                        null,
                        new { area = "Identity", userId = user.Id, code, returnUrl },
                        this.Request.Scheme);

                    await this.emailSender.SendEmailAsync(
                        this.Input.Email,
                        "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode( callbackUrl )}'>clicking here</a>.")
                    .ConfigureAwait(false);

                    if (this.userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(this.RedirectToPage(
                                   "RegisterConfirmation",
                                   new { email = this.Input.Email, returnUrl }));
                    }

                    await this.signInManager.SignInAsync(user, false).ConfigureAwait(false);

                    return(this.LocalRedirect(returnUrl));
                }

                foreach (IdentityError error in result.Errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(this.Page( ));
        }
コード例 #13
0
        public async Task <IActionResult> OnGet( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            return(this.Page( ));
        }
コード例 #14
0
        public async Task <ICollection <Project> > ListUserProjectsAsync(string userId)
        {
            HeimdallUser user = await this.context.Users.Include(p => p.ProjectUsers)
                                .ThenInclude(p => p.Project)
                                .FirstOrDefaultAsync(p => p.Id == userId)
                                .ConfigureAwait(false);

            List <Project> projects = user.ProjectUsers.SelectMany(p => (IEnumerable <Project>)p.Project).ToList( );

            return(projects);
        }
コード例 #15
0
        private async Task LoadAsync(HeimdallUser user)
        {
            string userName = await this.userManager.GetUserNameAsync(user).ConfigureAwait(false);

            string phoneNumber = await this.userManager.GetPhoneNumberAsync(user).ConfigureAwait(false);

            this.Username = userName;

            this.Input = new InputModel {
                PhoneNumber = phoneNumber
            };
        }
コード例 #16
0
        private async Task LoadAsync(HeimdallUser user)
        {
            string email = await this.userManager.GetEmailAsync(user).ConfigureAwait(false);

            this.Email = email;

            this.Input = new InputModel {
                NewEmail = email
            };

            this.IsEmailConfirmed = await this.userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false);
        }
コード例 #17
0
        public async Task <IActionResult> OnGetAsync(string returnUrl = null)
        {
            // Ensure the user has gone through the username & password screen first
            HeimdallUser user = await this.signInManager.GetTwoFactorAuthenticationUserAsync( ).ConfigureAwait(false);

            if (user == null)
            {
                throw new InvalidOperationException("Unable to load two-factor authentication user.");
            }

            this.ReturnUrl = returnUrl;

            return(this.Page( ));
        }
        public async Task <IActionResult> OnPost( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            await this.signInManager.ForgetTwoFactorClientAsync( ).ConfigureAwait(false);

            this.StatusMessage =
                "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code.";

            return(this.RedirectToPage( ));
        }
コード例 #19
0
        public async Task <IActionResult> OnGet( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            if (!await this.userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
            {
                throw new InvalidOperationException(
                          $"Cannot disable 2FA for user with ID '{this.userManager.GetUserId( this.User )}' as it's not currently enabled.");
            }

            return(this.Page( ));
        }
コード例 #20
0
        public async Task <IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page( ));
            }

            returnUrl = returnUrl ?? this.Url.Content("~/");

            HeimdallUser user = await this.signInManager.GetTwoFactorAuthenticationUserAsync( ).ConfigureAwait(false);

            if (user == null)
            {
                throw new InvalidOperationException("Unable to load two-factor authentication user.");
            }

            string authenticatorCode =
                this.Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            SignInResult result = await this.signInManager
                                  .TwoFactorAuthenticatorSignInAsync(
                authenticatorCode,
                rememberMe,
                this.Input.RememberMachine)
                                  .ConfigureAwait(false);

            if (result.Succeeded)
            {
                this.logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id);

                return(this.LocalRedirect(returnUrl));
            }

            if (result.IsLockedOut)
            {
                this.logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);

                return(this.RedirectToPage("./Lockout"));
            }

            this.logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id);
            this.ModelState.AddModelError(string.Empty, "Invalid authenticator code.");

            return(this.Page( ));
        }
コード例 #21
0
        public async Task <IActionResult> OnPostChangeEmailAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            if (!this.ModelState.IsValid)
            {
                await this.LoadAsync(user).ConfigureAwait(false);

                return(this.Page( ));
            }

            string email = await this.userManager.GetEmailAsync(user).ConfigureAwait(false);

            if (this.Input.NewEmail != email)
            {
                string userId = await this.userManager.GetUserIdAsync(user).ConfigureAwait(false);

                string code = await this.userManager.GenerateChangeEmailTokenAsync(user, this.Input.NewEmail)
                              .ConfigureAwait(false);

                string callbackUrl = this.Url.Page(
                    "/Account/ConfirmEmailChange",
                    null,
                    new { userId, email = this.Input.NewEmail, code },
                    this.Request.Scheme);
                await this.emailSender.SendEmailAsync(
                    this.Input.NewEmail,
                    "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode( callbackUrl )}'>clicking here</a>.")
                .ConfigureAwait(false);

                this.StatusMessage = "Confirmation link to change email sent. Please check your email.";

                return(this.RedirectToPage( ));
            }

            this.StatusMessage = "Your email is unchanged.";

            return(this.RedirectToPage( ));
        }
コード例 #22
0
        public async Task <IActionResult> OnGetAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            bool hasPassword = await this.userManager.HasPasswordAsync(user).ConfigureAwait(false);

            if (!hasPassword)
            {
                return(this.RedirectToPage("./SetPassword"));
            }

            return(this.Page( ));
        }
コード例 #23
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(HeimdallUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            string unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await this.userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);

                unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
            }

            this.SharedKey = this.FormatKey(unformattedKey);

            string email = await this.userManager.GetEmailAsync(user).ConfigureAwait(false);

            this.AuthenticatorUri = this.GenerateQrCodeUri(email, unformattedKey);
        }
コード例 #24
0
        public async Task <IActionResult> OnGetAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound("Unable to load user with ID 'user.Id'."));
            }

            this.CurrentLogins = await this.userManager.GetLoginsAsync(user).ConfigureAwait(false);

            this.OtherLogins =
                (await this.signInManager.GetExternalAuthenticationSchemesAsync( ).ConfigureAwait(false))
                .Where(auth => this.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
                .ToList( );
            this.ShowRemoveButton = user.PasswordHash != null || this.CurrentLogins.Count > 1;

            return(this.Page( ));
        }
コード例 #25
0
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            if (userId == null || email == null || code == null)
            {
                return(this.RedirectToPage("/Index"));
            }

            HeimdallUser user = await this.userManager.FindByIdAsync(userId).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{userId}'."));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            IdentityResult result =
                await this.userManager.ChangeEmailAsync(user, email, code).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                this.StatusMessage = "Error changing email.";

                return(this.Page( ));
            }

            // In our UI email and user name are one and the same, so when we update the email
            // we need to update the user name.
            IdentityResult setUserNameResult =
                await this.userManager.SetUserNameAsync(user, email).ConfigureAwait(false);

            if (!setUserNameResult.Succeeded)
            {
                this.StatusMessage = "Error changing user name.";

                return(this.Page( ));
            }

            await this.signInManager.RefreshSignInAsync(user).ConfigureAwait(false);

            this.StatusMessage = "Thank you for confirming your email change.";

            return(this.Page( ));
        }
コード例 #26
0
        public async Task <IActionResult> OnGetAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            bool isTwoFactorEnabled = await this.userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false);

            if (!isTwoFactorEnabled)
            {
                string userId = await this.userManager.GetUserIdAsync(user).ConfigureAwait(false);

                throw new InvalidOperationException(
                          $"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled.");
            }

            return(this.Page( ));
        }
        public async Task <IActionResult> OnGet( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            this.HasAuthenticator =
                await this.userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false) != null;

            this.Is2FaEnabled = await this.userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false);

            this.IsMachineRemembered =
                await this.signInManager.IsTwoFactorClientRememberedAsync(user).ConfigureAwait(false);

            this.RecoveryCodesLeft = await this.userManager.CountRecoveryCodesAsync(user).ConfigureAwait(false);

            return(this.Page( ));
        }
コード例 #28
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            await this.userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);

            await this.userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);

            this.logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);

            await this.signInManager.RefreshSignInAsync(user).ConfigureAwait(false);

            this.StatusMessage =
                "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.";

            return(this.RedirectToPage("./EnableAuthenticator"));
        }
コード例 #29
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            if (!this.ModelState.IsValid)
            {
                await this.LoadAsync(user).ConfigureAwait(false);

                return(this.Page( ));
            }

            string userId = await this.userManager.GetUserIdAsync(user).ConfigureAwait(false);

            string email = await this.userManager.GetEmailAsync(user).ConfigureAwait(false);

            string code = await this.userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            string callbackUrl = this.Url.Page(
                "/Account/ConfirmEmail",
                null,
                new { area = "Identity", userId, code },
                this.Request.Scheme);

            await this.emailSender.SendEmailAsync(
                email,
                "Confirm your email",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode( callbackUrl )}'>clicking here</a>.")
            .ConfigureAwait(false);

            this.StatusMessage = "Verification email sent. Please check your email.";

            return(this.RedirectToPage( ));
        }
コード例 #30
0
        public async Task <IActionResult> OnPostAsync( )
        {
            HeimdallUser user = await this.userManager.GetUserAsync(this.User).ConfigureAwait(false);

            if (user == null)
            {
                return(this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId( this.User )}'."));
            }

            if (!this.ModelState.IsValid)
            {
                await this.LoadAsync(user).ConfigureAwait(false);

                return(this.Page( ));
            }

            string phoneNumber = await this.userManager.GetPhoneNumberAsync(user).ConfigureAwait(false);

            if (this.Input.PhoneNumber != phoneNumber)
            {
                IdentityResult setPhoneResult = await this.userManager
                                                .SetPhoneNumberAsync(user, this.Input.PhoneNumber)
                                                .ConfigureAwait(false);

                if (!setPhoneResult.Succeeded)
                {
                    this.StatusMessage = "Unexpected error when trying to set phone number.";

                    return(this.RedirectToPage( ));
                }
            }

            await this.signInManager.RefreshSignInAsync(user).ConfigureAwait(false);

            this.StatusMessage = "Your profile has been updated";

            return(this.RedirectToPage( ));
        }