Esempio n. 1
0
        public async Task <IActionResult> LoginWith2Fa(LoginWith2FaViewModel model, bool rememberMe, string returnUrl = null)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }

            var user = await this.signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result = await this.signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);

            if (result.Succeeded)
            {
                this.logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
                return(this.RedirectToLocal(returnUrl));
            }
            else if (result.IsLockedOut)
            {
                this.logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
                return(this.RedirectToAction(nameof(this.Lockout)));
            }
            else
            {
                this.logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
                this.ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
                return(this.View());
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> LoginWith2Fa(LoginWith2FaViewModel model, bool rememberMe, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);

            if (result.Succeeded)
            {
                return(RedirectToLocal(returnUrl));
            }

            if (result.IsLockedOut)
            {
                return(RedirectToAction(nameof(Lockout)));
            }

            ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
            return(View());
        }
Esempio n. 3
0
        public async Task <IActionResult> LoginWith2fa(
            bool rememberMe, string returnUrl = null, bool showResendMessage = false
            )
        {
            if (User?.Identity.IsAuthenticated == true)
            {
                return(Redirect(returnUrl ?? m_returnUrlConfiguration.DefaultRedirectUrl));
            }

            // Ensure the user has gone through the username & password screen first
            var user = await m_signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                ModelState.AddModelError(m_localization.Translate("no-valid-2f-session", "LoginWith2FaViewModel"));
                CacheModelState();
                return(RedirectToAction(nameof(Login), new { returnUrl }));
            }

            await m_signInManager.GenerateTwoFactorTokenAsync(user, user.TwoFactorProvider);

            var model = new LoginWith2FaViewModel
            {
                RememberMe        = rememberMe,
                ReturnUrl         = returnUrl,
                Username          = user.UserName,
                ShowResendMessage = showResendMessage
            };

            return(View(model));
        }
Esempio n. 4
0
        public async Task <IActionResult> ExternalLoginCallback([Required] LoginViewModel viewModel)
        {
            var logInTryoutResult = await PerformLogInTryout(viewModel);

            if (logInTryoutResult.Success || User?.Identity.IsAuthenticated == true)
            {
                var userId = logInTryoutResult.Success ? logInTryoutResult.User.Id : int.Parse(User.Identity.GetSubjectId());

                var authorizationResult = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);

                if (authorizationResult.Succeeded)
                {
                    var userExternalProvider = await FindUserFromExternalProviderAsync(authorizationResult);

                    m_userManager.CreateExternalLogin(
                        userId, userExternalProvider.Provider, userExternalProvider.ProviderUserId
                        );
                }
                else
                {
                    ModelState.AddModelError(Translator.Translate("failed-login-through-external-provider"));

                    viewModel.Action = nameof(ExternalLoginCallback);
                    viewModel.LinkExternalIdentity = true;
                    viewModel.ExternalProviders    = null;

                    return(View(nameof(Login), viewModel));
                }
            }
            else if (logInTryoutResult.SecondFactorRequired)
            {
                await m_signInManager.GenerateTwoFactorTokenAsync(logInTryoutResult.User, logInTryoutResult.User.TwoFactorProvider);

                var model = new LoginWith2FaViewModel
                {
                    RememberMe        = viewModel.Input.RememberLogin,
                    ReturnUrl         = Url.Action(nameof(ExternalLoginCallback), new { viewModel.ReturnUrl }),
                    Username          = logInTryoutResult.User.UserName,
                    ShowResendMessage = false
                };

                return(View(nameof(LoginWith2fa), model));
            }

            if (logInTryoutResult.ActionResult is ViewResult)
            {
                viewModel.Action = nameof(ExternalLoginCallback);
                viewModel.LinkExternalIdentity = true;
                viewModel.ExternalProviders    = null;

                return(View(nameof(Login), viewModel));
            }

            return(logInTryoutResult.ActionResult);
        }
Esempio n. 5
0
        public async Task <IActionResult> LoginWith2Fa(string returnUrl = null)
        {
            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var model = new LoginWith2FaViewModel
            {
                ReturnUrl = returnUrl
            };

            return(View(model));
        }
        public async Task <IActionResult> LoginWith2Fa(bool rememberMe, string _retunrUrl = null)
        {
            var _user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var _model = new LoginWith2FaViewModel {
                RememberMe = rememberMe
            };

            ViewData["ReturnUrl"] = _retunrUrl;

            return(View(_model));
        }
        public async Task <IActionResult> LoginWith2Fa(bool rememberMe, string returnUrl = null)
        {
            // Ensure the user has gone through the username & password screen first
            var user = await signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var model = new LoginWith2FaViewModel {
                RememberMe = rememberMe
            };

            ViewData["ReturnUrl"] = returnUrl;

            return(View(model));
        }
Esempio n. 8
0
        public async Task <IActionResult> LoginWith2Fa(LoginWith2FaViewModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var userId = await _signInManager.GetTwoFactorAuthenticationUserAsync();

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

            var verify2FaToken = new VerifyTwoFactorModel
            {
                UserId          = userId,
                Code            = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty),
                RememberMachine = model.RememberMachine
            };

            var result = await _accountsEndpoint.VerifyTwoFactorTokenAsync(verify2FaToken);

            if (result.Verified)
            {
                await _signInManager.DoTwoFactorSignInAsync(userId, model.RememberMachine);

                _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", userId);
                returnUrl ??= Url.Content("~/");
                return(LocalRedirect(returnUrl));
            }

            _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", userId);
            ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
            return(View(model));
        }
Esempio n. 9
0
        public async Task <IActionResult> LoginWith2fa(LoginWith2FaViewModel viewModel)
        {
            if (User?.Identity.IsAuthenticated == true)
            {
                return(Redirect(viewModel.ReturnUrl ?? m_returnUrlConfiguration.DefaultRedirectUrl));
            }

            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            var user = await m_signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                ModelState.AddModelError(m_localization.Translate("no-valid-2f-session", "LoginWith2FaViewModel"));
                CacheModelState();
                return(RedirectToAction(nameof(Login), new { returnUrl = viewModel.ReturnUrl }));
            }

            var result = await m_signInManager.TwoFactorSignInAsync(
                user, viewModel.TwoFactorCode, viewModel.RememberMe, viewModel.RememberMachine, user.TwoFactorProvider
                );

            if (result.Succeeded)
            {
                m_signInManager.DeleteTwoFactorToken(user, user.TwoFactorProvider);

                return(await SuccessLogin(user.UserName, viewModel.ReturnUrl));
            }

            ModelState.AddModelError(m_localization.Translate("invalid-authenticator-code"));

            return(View(viewModel));
        }
Esempio n. 10
0
        public async Task <IActionResult> ResendAuthorizationCode(bool isFormSubmit = false, LoginWith2FaViewModel viewmodel = null)
        {
            if (isFormSubmit && viewmodel != null)
            {
                return(RedirectToAction(nameof(LoginWith2fa),
                                        new
                {
                    remeberMe = viewmodel.RememberMe,
                    username = viewmodel.Username,
                    returnUrl = viewmodel.ReturnUrl,
                    ShowResendMessage = true,
                }));
            }

            // Ensure the user has gone through the username & password screen first
            var user = await m_signInManager.GetTwoFactorAuthenticationUserAsync();

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

            await m_signInManager.GenerateTwoFactorTokenAsync(user, user.TwoFactorProvider);

            return(Ok());
        }
        public async Task <IActionResult> LoginWith2Fa([FromBody] LoginWith2FaViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError(string.Empty, _localizer["LoginWith2faError"]);
                Unauthorized(ModelState);
                return(new JsonResult(ModelState));
            }

            var user = await _userResolver.GetUserAsync(model.Username);

            if (user == null)
            {
                throw new InvalidOperationException(_localizer["Unable2FA"]);
            }

            var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result2 = await _userManager.VerifyTwoFactorTokenAsync(user, _userManager.Options.Tokens.AuthenticatorTokenProvider,
                                                                       authenticatorCode);

            var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, model.RememberMe, model.RememberMachine);

            if (result2)
            {
                var userRoles = await _identityService.GetUserRolesAsync(user.Id.ToString());

                var token = await _userManager.GetAuthenticationTokenAsync(user, "oidc", "TokenName");

                return(new JsonResult(new LoginResultDto
                {
                    Token = token,
                    NextStepNeeded = false,
                    UserInfo = new UserInfoDto
                    {
                        PharmaciesInfo = new List <PharmacyInfoDto>
                        {
                            new PharmacyInfoDto
                            {
                                AGB = "02009717",
                                CustomerId = user.CustomerId,
                                Id = user.PharmacyId,
                                IsDepot = true,
                                Name = "Apotheek de Duffelt"
                            }
                        },
                        UserDto = new UserDto
                        {
                            Id = Convert.ToInt64(user.Id.ToString()),
                            Name = user.UserName,
                            Email = user.Email,
                            Initials = "",
                            IsActive = !user.LockoutEnabled,
                            IsTwoFaEnabled = user.TwoFactorEnabled,
                            PhoneNumber = user.PhoneNumber,
                            Username = user.UserName,
                            Roles = userRoles.Roles != null ? userRoles.Roles.Select(x => new RoleDto
                            {
                                Id = Convert.ToInt64(x.Id.ToString()),
                                Title = x.Name,
                                Code = x.Id.ToString()
                            }) : new List <RoleDto>()
                        }
                    }
                }));
            }

            if (result.IsLockedOut)
            {
                ModelState.AddModelError(string.Empty, _localizer["Lockout"]);
                Unauthorized(ModelState);
                return(new JsonResult(ModelState));
            }

            ModelState.AddModelError(string.Empty, _localizer["InvalidAuthenticatorCode"]);
            Unauthorized(ModelState);
            return(BadRequest(ModelState));
        }