Beispiel #1
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

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

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
Beispiel #2
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound(_sharedLocalizer["USER_NOTFOUND", _userManager.GetUserId(User)]));
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.FindByIdAsync(User.FindFirst("uid")?.Value).ConfigureAwait(false);

            if (user == null)
            {
                return(BadRequest(new string[] { "Could not find user!" }));
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user).ConfigureAwait(false)
            };

            return(Ok(model));
        }
Beispiel #4
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound(_localizer["UserNotFound", _userManager.GetUserId(User)]));
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator    = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled        = user.TwoFactorEnabled,
                RecoveryCodesLeft   = await _userManager.CountRecoveryCodesAsync(user),
                IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
            };

            return(View(model));
        }
        public async Task <IActionResult> EnableAuthenticator()
        {
            string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";

            var user = await _userManager.GetUserAsync(User);

            await _userManager.ResetAuthenticatorKeyAsync(user);

            var token = await _userManager.GetAuthenticatorKeyAsync(user);

            string AuthenticatorUri = string.Format(AuthenticatorUriFormat, _urlEncoder.Encode("IdentityManager"),
                                                    _urlEncoder.Encode(user.Email), token);
            var model = new TwoFactorAuthenticationViewModel()
            {
                Token = token, QRCodeUrl = AuthenticatorUri
            };

            return(View(model));
        }
        // Metodo que verifica se o usuario esta logado e monta a model para ser apresentada na tela ao usuario
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

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

            // Tenta obter e verificar se o usuario tem um autenticator key, se o TwoFactor ja esta habilitado e se ele ta tem algum recovery code criado
            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            ViewData["Title"] = StringLocalizer["Two-factor authentication"];

            var user = await UserManager.FindByIdAsync(User.GetUserId());

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

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await UserManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await UserManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
        public async Task <IActionResult> EnableAuthenticator(TwoFactorAuthenticationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(User);

                var succeeded = await _userManager.VerifyTwoFactorTokenAsync(user, _userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code);

                if (succeeded)
                {
                    await _userManager.SetTwoFactorEnabledAsync(user, true);
                }
                else
                {
                    ModelState.AddModelError("Verify", "Your two factor auth code could not be avalidated.");
                    return(View(model));
                }
            }
            return(RedirectToAction(nameof(AuthenticatorConfirmation)));
        }
Beispiel #9
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                await _signInManager.SignOutAsync();

                return(RedirectToAction("Index", "Home", new { area = "" }));
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
Beispiel #10
0
        public async Task <IActionResult> PostTwoStepAuth([FromBody] TwoFactorAuthenticationViewModel model)
        {
            if (User == null)
            {
                return(Unauthorized());
            }

            var userName = _userManager.GetUserName(User);

            if (userName == null)
            {
                return(StatusCode(500));
            }

            var applicationUser = await _userManager.FindByNameAsync(userName);

            var totp = new OneTimePassword(applicationUser.TotpSecret);

            if (totp.IsCodeValid(model.code))
            {
                var identity = await GetClaimsIdentity(applicationUser);

                // Serialize and return the response
                var response = new
                {
                    success    = true,
                    id         = identity.Claims.Single(c => c.Type == Helpers.Constants.Strings.JwtClaimIdentifiers.Id).Value,
                    username   = userName,
                    role       = identity.Claims.Single(c => c.Type == Helpers.Constants.Strings.JwtClaimIdentifiers.Role).Value,
                    auth_token = await _jwtFactory.GenerateEncodedToken(userName, identity, true),
                    expires_in = (int)_jwtOptions.ValidFor.TotalSeconds
                };

                return(Ok(response));
            }

            else
            {
                return(Ok(new Response(false, "El código ingresado es incorrecto.")));
            }
        }
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

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

            var model = new TwoFactorAuthenticationViewModel
            {
                Devices = user.DeviceRegistrations?.Select(d => new DeviceModel {
                    Id = d.Id, DeviceName = d.DeviceName, Counter = d.Counter, CreatedOn = d.CreatedOn, KeyHandle = Convert.ToBase64String(d.KeyHandle)
                }).ToList() ?? new List <DeviceModel>(),
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
        public async Task <IActionResult> TwoFactorAuthentication(string alert)
        {
            if (alert != null)
            {
                ViewBag.Alert = "اپلیکشن احراز هویت شما تایید شده است";
            }

            var user = await _userManager.GetUserAsync(User);

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

            TwoFactorAuthenticationViewModel ViewModel = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
                Is2faEnabled      = await _userManager.GetTwoFactorEnabledAsync(user),
            };

            return(View(ViewModel));
        }
Beispiel #13
0
        public async Task <IActionResult> GetTwoFactorAuthenticationData()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(BadRequest(
                           new
                {
                    StatusCode = StatusCodes.Status409Conflict,
                    errors = SetSpecificError($"Unable to load user. Check browser cache")
                }));
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(new JsonResult(new { StatusCode = StatusCodes.Status200OK, _2faData = model }));
        }
        public async Task <IActionResult> Index(string redirectUri, string clientId, string scope,
                                                string nonce, string state, string username)
        {
            var user = await _userManager.FindByNameAsync(username);

            var vm = new TwoFactorAuthenticationViewModel()
            {
                RedirectUri = redirectUri,
                ClientId    = clientId,
                Scope       = scope,
                Nonce       = nonce,
                State       = state,
                Username    = username,
                DisplayText = GetDisplayText(user),
                AllowResend = user.TwoFactorId != (int)TwoFactorTypes.Totp
            };

            if (!_signInManager.IsSignedIn(User))
            {
                return(Redirect("~/Account/Login?returnUrl=" + BuildReturnUrl(vm)));
            }

            switch (user.TwoFactorId)
            {
            case (int)TwoFactorTypes.Email:
                await SendCodeToEmail(user);

                break;

            case (int)TwoFactorTypes.Sms:
                await SendSmsCode(user);

                break;
            }

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

            if (user == null)
            {
                _clientNotification.AddToastNotification("No Such User Exists", NotificationHelper.NotificationType.error, new ToastNotificationOption
                {
                    NewestOnTop       = true,
                    CloseButton       = true,
                    PositionClass     = "toast-bottom-right",
                    PreventDuplicates = true
                });
            }

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user)
            };

            return(View(model));
        }
Beispiel #16
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

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

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);

            return(View(model));
        }
Beispiel #17
0
        public async Task <IActionResult> TwoFactorAuthentication()
        {
            var user = await _userManager.GetUserAsync(User);

            var userPersonalRow = _context.UserPersonalDetail.Where(a => a.UserId == user.Id).SingleOrDefault();

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

            var model = new TwoFactorAuthenticationViewModel
            {
                HasAuthenticator  = await _userManager.GetAuthenticatorKeyAsync(user) != null,
                Is2faEnabled      = user.TwoFactorEnabled,
                RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user),
            };

            return(View(model));
        }
        public async Task <IActionResult> Index(TwoFactorAuthenticationViewModel model, string button)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user.TwoFactorFailedCount > user.MaxTwoFactorFailedAccessAttempts)
            {
                user.TwoFactorFailedCount = 0;
                await _userManager.UpdateAsync(user);

                await _userManager.SetLockoutEndDateAsync(user, DateTime.Now.AddMinutes(user.DefaultTwoFatorLockoutMinutes));

                return(Redirect("~/Account/Login?returnUrl=" + BuildReturnUrl(model) + "&isLockedOut=true"));
            }
            else
            {
                if (button == "submit")
                {
                    if (user.TwoFactorId == (int)TwoFactorTypes.Totp)
                    {
                        if (_totpService.Validate(user.TotpSecret, model.Code))
                        {
                            return(await Authenticated(user, model));
                        }
                        else
                        {
                            return(await AccessDenied(user, model));
                        }
                    }
                    else
                    {
                        if (model.Code == user.TwoFactorCode)
                        {
                            return(await Authenticated(user, model));
                        }
                        else
                        {
                            return(await AccessDenied(user, model));
                        }
                    }
                }
                else
                {
                    switch (user.TwoFactorId)
                    {
                    case (int)TwoFactorTypes.Email:
                        await SendCodeToEmail(user);

                        break;

                    case (int)TwoFactorTypes.Sms:
                        await SendSmsCode(user);

                        break;
                    }

                    model.Code        = null;
                    model.DisplayText = GetDisplayText(user);
                    return(View(model));
                }
            }
        }