public async Task <IActionResult> OnPostAsync()
        {
            var newGuest = new PlayerDTO();

            if (await _playerService.DoesPlayerExistAsync(ConventionGuest.PlayerId))
            {
                ToastMessage = _locService.GetLocalizedString("Person with that code is already registered!");
                ToastType    = "error";
            }
            else if (await TryUpdateModelAsync <PlayerDTO>(
                         newGuest,
                         "ConventionGuest",
                         p => p.PlayerId, p => p.FirstName, p => p.LastName, p => p.Telephone, p => p.Email, p => p.PersonalNumber, p => p.Address,
                         p => p.City, p => p.PostalCode))
            {
                newGuest.RegistrationTime = DateTime.UtcNow;
                await _playerService.AddNewPlayerAsync(newGuest);

                ToastMessage = _locService.GetLocalizedString("Record added");
                ToastType    = "success";
                _logger.LogWarning($"Guest with id '{newGuest.PlayerId}' was registered by '{User.Identity.Name}'.");
                return(RedirectToPage("./RegisterGuest"));
            }
            return(Page());
        }
Exemple #2
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content($"~/{culture}");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe, culture }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout", new { culture }));
                }
                else
                {
                    var msg = _loc.GetLocalizedString("Invalid login attempt.");
                    TempData.Warning(msg);
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #3
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            var categoryToUpdate = await _categoryService.GetCategoryAsync(id);

            if (categoryToUpdate == null)
            {
                return(NotFound());
            }

            if (await TryUpdateModelAsync <CategoryDTO>(
                    categoryToUpdate,
                    "category",
                    c => c.CategoryName, c => c.CategoryDescription))
            {
                await _categoryService.UpdateCategory(categoryToUpdate);

                ToastMessage = _locService.GetLocalizedString("Record updated");
                ToastType    = "success";
                return(new LocalRedirectResult(Tools.GetPathWithCultureSufix("/Gamesroom/Categories/")));
            }

            ToastMessage = _locService.GetLocalizedString("Error. Please try again!");
            ToastType    = "error";
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

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

            var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);

            if (!changePasswordResult.Succeeded)
            {
                foreach (var error in changePasswordResult.Errors)
                {
                    //ModelState.AddModelError(string.Empty, error.Description);
                    TempData.Danger(_loc.GetLocalizedString(error.Description));
                }
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            _logger.LogInformation("User changed their password successfully.");
            //StatusMessage = "Your password has been changed.";
            TempData.Success(_loc.GetLocalizedString(LocalizedBackendMessages.ChangePasswordSuccess));

            return(RedirectToPage());
        }
        public async Task <IActionResult> OnGetAsync(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(RedirectToPage("/Index", new { culture }));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", userId);
                return(NotFound(msg));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ConfirmEmailAsync(user, code);

            if (result.Succeeded)
            {
                var msg = _loc.GetLocalizedString("Thank you for confirming your email.");
                TempData.Success(msg);
            }
            else
            {
                var msg = _loc.GetLocalizedString("Error confirming your email.");
                TempData.Danger(msg);
            }

            return(Page());
        }
Exemple #6
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var 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
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code, culture, email = Input.Email },
                    protocol: Request.Scheme);

                var mailHeader = _loc.GetLocalizedString(culture, "Reset password");
                var mailBody   = _loc.GetLocalizedString(culture, "Please reset your password by <a href='{0}'>clicking here</a>.", callbackUrl);

                await _emailSender.SendEmailAsync(Input.Email, mailHeader, mailBody);

                return(RedirectToPage("./ForgotPasswordConfirmation", new { culture }));
            }

            return(Page());
        }
Exemple #7
0
        public async Task <IActionResult> OnPostAsync()
        {
            GameTitles = await _boxService.GetGameTitlesAsync();

            var newBox = new BoxDTO();

            if (await _boxService.DoesBoxExistAsync(Box.BoxId))
            {
                ToastMessage = _locService.GetLocalizedString("Box with that code is already registered!");
                ToastType    = "error";
            }
            else if (await TryUpdateModelAsync <BoxDTO>(
                         newBox,
                         "box",
                         b => b.BoxId, b => b.GameId))
            {
                await _boxService.AddBoxAsync(newBox);

                ToastMessage = _locService.GetLocalizedString("Record added");
                ToastType    = "success";
                _logger.LogWarning($"Box with id '{newBox.BoxId}' for game with id '{newBox.GameId}' was created by '{User.Identity.Name}'.");
                return(RedirectToPage("./Create"));
            }
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var response = await _service.HandleForgottenPassword(Input.Email);

                if (!response.UserExists || !response.UserHasConfrirmedEmail)
                {
                    // 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
                var code = response.Token;
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(
                    Input.Email,
                    _locService.GetLocalizedString("Reset password"),
                    _locService.GetLocalizedString("Please reset your password by") + $" <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>" + _locService.GetLocalizedString("clicking here") + "</a>.");

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

            return(Page());
        }
        public async Task <IActionResult> OnGet()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

            return(Page());
        }
Exemple #10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content($"~/{culture}");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    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, culture },
                        protocol: Request.Scheme);

                    var mailHeader = _loc.GetLocalizedString("Confirm your email");
                    var mailBody   = _loc.GetLocalizedString("Please confirm your account by <a href='{0}'>clicking here</a>.", HtmlEncoder.Default.Encode(callbackUrl));

                    await _emailSender.SendEmailAsync(Input.Email, mailHeader, mailBody);

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, culture }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    // model binding error already locaized by ExpressLocalization
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString(culture, "Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

            await LoadSharedKeyAndQrCodeUriAsync(user);

            return(Page());
        }
Exemple #12
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

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

            var email = await _userManager.GetEmailAsync(user);

            if (Input.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);

                if (!setEmailResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
                }
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }

            await _signInManager.RefreshSignInAsync(user);

            //StatusMessage = "Your profile has been updated";
            TempData.Success(_loc.GetLocalizedString(LocalizedBackendMessages.UserProfileUpdateSuccess));
            return(RedirectToPage());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

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

            var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);

            var 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.");
            }

            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

            RecoveryCodes = recoveryCodes.ToArray();

            _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId);
            TempData.Success(_loc.GetLocalizedString(LocalizedBackendMessages.GeneraterecoveryCodesSuccess));

            return(RedirectToPage("./ShowRecoveryCodes", new { culture = CultureInfo.CurrentCulture.Name }));
        }
Exemple #14
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty);

            var 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($"~/{culture}")));
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
                return(RedirectToPage("./Lockout", new { culture }));
            }
            else
            {
                _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id);
                TempData.Danger(_loc.GetLocalizedString(LocalizedBackendMessages.InvalidRecoveryCode));
                return(Page());
            }
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var(UserName, PhoneNumber, CrewName, UserId) = await _service.GetUserIndexData(User);

            var changePasswordResult = await _service.ChangePasswordAsync(UserId, Input.OldPassword, Input.NewPassword);

            if (!changePasswordResult.Succeeded)
            {
                foreach (var error in changePasswordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Page());
            }

            await _service.RefreshSignInAsync(UserId);

            _logger.LogInformation("User changed their password successfully.");
            StatusMessage = _locService.GetLocalizedString("Your password has been changed.");

            return(RedirectToPage("./Index"));
        }
Exemple #16
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _service.UserPasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogWarning($"User '{Input.Email}' logged in.");
                    return(LocalRedirect(returnUrl));
                }
                //if (result.RequiresTwoFactor)
                //{
                //    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                //}
                if (result.IsLockedOut)
                {
                    _logger.LogWarning($"User '{Input.Email}' account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, _locService.GetLocalizedString("Invalid login attempt."));
                    _logger.LogWarning($"Invalid login attempt - url: '{returnUrl}', user email: '{Input.Email}'");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            var culture = CultureInfo.CurrentCulture.Name;

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToPage("./ResetPasswordConfirmation", new { culture }));
            }

            var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);

            if (result.Succeeded)
            {
                return(RedirectToPage("./ResetPasswordConfirmation", new { culture }));
            }

            foreach (var error in result.Errors)
            {
                //ModelState.AddModelError(string.Empty, error.Description);
                TempData.Danger(_loc.GetLocalizedString(error.Description));
            }
            return(Page());
        }
Exemple #18
0
        public async Task <IActionResult> OnGetAsync(string email)
        {
            if (email == null)
            {
                return(RedirectToPage("/Index", new { culture }));
            }

            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with email '{0}'.", email);
                return(NotFound(msg));
            }

            Email = email;
            // Once you add a real email sender, you should remove this code that lets you confirm the account
            DisplayConfirmAccountLink = true;
            if (DisplayConfirmAccountLink)
            {
                var userId = await _userManager.GetUserIdAsync(user);

                var 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, culture },
                    protocol: Request.Scheme);
            }

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

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

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

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

            Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
            return(new FileContentResult(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(personalData)), "text/json"));
        }
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content($"~/{culture}");
            if (remoteError != null)
            {
                var str = _loc.GetLocalizedString(LocalizedBackendMessages.ExternalLoginsProviderError, args: remoteError);
                //ErrorMessage = $"Error from external provider: {remoteError}";
                TempData.Danger(str);
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl, Culture = culture }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                //ErrorMessage = "Error loading external login information.";
                TempData.Danger(_loc.GetLocalizedString(LocalizedBackendMessages.ExternalLoginsLoadingError));

                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl, Culture = culture }));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                return(LocalRedirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout", new { culture }));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl     = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return(Page());
            }
        }
Exemple #21
0
        public async Task <IActionResult> OnPostAsync(string[] selectedCategories)
        {
            var newGame = new GameDTO();

            if (selectedCategories != null)
            {
                newGame.GameCategories = new List <GameCategoryDTO>();
                foreach (var category in selectedCategories)
                {
                    var categoryToAdd = new GameCategoryDTO
                    {
                        CategoryId = int.Parse(category)
                    };
                    newGame.GameCategories.Add(categoryToAdd);
                }
            }

            if (await _gameService.DoesGameTitleExistAsync(Game.Title))
            {
                ToastMessage = _locService.GetLocalizedString("Game with that title is already registered!");
                ToastType    = "error";
            }
            else if (Game.BoardGameGeekId.HasValue && await _gameService.DoesBoardGameGeekIdExistAsync(Game.BoardGameGeekId.Value))
            {
                ToastMessage = _locService.GetLocalizedString("BoardGameGeek Id is already registered!");
                ToastType    = "error";
            }
            else
            {
                if (await TryUpdateModelAsync <GameDTO>(
                        newGame,
                        "game", // prefix from table in "view" part of this page
                        g => g.Title, g => g.Publisher, g => g.Description, g => g.BoardGameGeekId, g => g.SendBackAfterConvention))
                {
                    await _gameService.AddNewGameAsync(newGame);

                    ToastMessage = _locService.GetLocalizedString("Record added");
                    ToastType    = "success";
                    _logger.LogWarning($"Game '{newGame.Title}' was created by '{User.Identity.Name}'.");
                    return(RedirectToPage("./Create"));
                }
            }

            AssignedCategoryDataList = _gameService.GetAssignedCategoryData(newGame);
            return(Page());
        }
        public async Task <IActionResult> OnGet()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

            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());
        }
Exemple #23
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = await _service.GetExternalAuthenticationSchemesAsync();

            if (ModelState.IsValid)
            {
                var result = await _service.CreateUserAsync(Input.Name, Input.Email, Input.Password);

                if (result.UserCreateResponse.Succeeded)
                {
                    _logger.LogWarning($"User '{Input.Email}' created a new account with password.");

                    var code = result.ConfirmationToken;
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = result.UserId, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

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

                    if (_service.RequireConfirmedAccount())
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _service.SignUserById(result.UserId, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.UserCreateResponse.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #24
0
        public JsonResult GetModulosByCursoId(int id)
        {
            var list = _context.Modulos.Where(m => m.CursoId == id).ToList();

            list.Insert(0, new Modulo {
                Id = 0, Descricao = _loc.GetLocalizedString(culture, "-- Select Module --")
            });
            return(Json(new SelectList(list, "Id", "Descricao")));
        }
Exemple #25
0
        public async Task <IActionResult> OnGetAsync(string userId, string email, string code)
        {
            string msg;

            if (userId == null || email == null || code == null)
            {
                return(RedirectToPage("/Index", new { culture }));
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", userId);
                return(NotFound(msg));
            }

            code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
            var result = await _userManager.ChangeEmailAsync(user, email, code);

            if (!result.Succeeded)
            {
                msg = _loc.GetLocalizedString("Error changing email.");
                TempData.Danger(msg);
                return(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.
            var setUserNameResult = await _userManager.SetUserNameAsync(user, email);

            if (!setUserNameResult.Succeeded)
            {
                msg = _loc.GetLocalizedString("Error changing user name.");
                TempData.Danger(msg);
                return(Page());
            }

            await _signInManager.RefreshSignInAsync(user);

            msg = _loc.GetLocalizedString("Thank you for confirming your email change.");
            TempData.Success(msg);
            return(Page());
        }
Exemple #26
0
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString(culture, "Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

            var hasPassword = await _userManager.HasPasswordAsync(user);

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

            return(Page());
        }
Exemple #27
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content($"~/{_culture}");
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    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.Page(
                        $"/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code, culture = _culture },
                        protocol: Request.Scheme);

                    var str = _loc.GetLocalizedString(LocalizedBackendMessages.VerificationEmailBody, args: HtmlEncoder.Default.Encode(callbackUrl));

                    await _emailSender.SendEmailAsync(Input.Email,
                                                      _loc.GetLocalizedString(LocalizedBackendMessages.VerificationEmailTitle),
                                                      str);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    //ModelState.AddModelError(string.Empty, error.Description);
                    TempData.Danger(error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #28
0
        public async Task <IActionResult> OnGet()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                var msg = _loc.GetLocalizedString("Unable to load user with ID '{0}'.", _userManager.GetUserId(User));
                return(NotFound(msg));
            }

            HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null;

            Is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user);

            IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user);

            RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user);

            return(Page());
        }
Exemple #29
0
        public async Task <IActionResult> OnPostAsync()
        {
            var 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
            var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

            if (!is2faTokenValid)
            {
                var locErr = _loc.GetLocalizedString("Verification code is invalid.");

                ModelState.AddModelError("Input.Code", locErr);
                TempData.Danger(locErr);

                await LoadSharedKeyAndQrCodeUriAsync(user);

                return(Page());
            }

            await _userManager.SetTwoFactorEnabledAsync(user, true);

            var userId = await _userManager.GetUserIdAsync(user);

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

            TempData.Success(LocalizedBackendMessages.EnableAuthenticatorSuccess);

            if (await _userManager.CountRecoveryCodesAsync(user) == 0)
            {
                var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

                RecoveryCodes = recoveryCodes.ToArray();
                return(RedirectToPage("./ShowRecoveryCodes", new { culture }));
            }
            else
            {
                return(RedirectToPage("./TwoFactorAuthentication", new { culture }));
            }
        }
        public void OnGet()
        {
            // This is a sample to show how to localize
            // custom messages from the backend.
            // The texts must be defined in ViewsLocalizationResource.xx.resx
            var msg = _loc.GetLocalizedString("Privacy Policy");

            // Use AlertTagHelper to show messages
            // Available options : .Success .Warning .Danger .Info .Dark .Light .Primary .Secondary
            // For more details visit: http://demo.ziyad.info/alert
            TempData.Warning(msg);
        }