public async Task <IActionResult> TwoFactorAuthentication(TwoFactorModel twoFactorModel, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(twoFactorModel));
            }
            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid authentication code.");
                return(RedirectToAction());
            }
            var result = await _signInManager.TwoFactorSignInAsync(TokenOptions.DefaultPhoneProvider, twoFactorModel.TwoFactorAuthCode, twoFactorModel.RememberMe, rememberClient : false);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else if (result.IsLockedOut)
            {
                ModelState.AddModelError("", "The account is locked out");
                return(View());
            }
            else
            {
                ModelState.AddModelError("", "Invalid Login Attempt");
                return(View());
            }
        }
Пример #2
0
        public ActionResult VerifyCode(string returnUrl, bool resendTwoFactorAuthentication = false)
        {
            if (!TempData.ContainsKey("UserName"))
            {
                return(RedirectToAction("Login", new { ReturnUrl = returnUrl }));
            }
            TwoFactorModel m = new TwoFactorModel();

            m.UserName             = TempData["UserName"].ToString();
            TempData["UserName"]   = m.UserName; //The value of TempData persists until it is read or until the current user’s session times out. So we set it again incase the user refreshes the page.
            ViewBag.ReturnUrl      = returnUrl;
            ViewBag.ActionName     = "VerifyCode";
            ViewBag.ControllerName = "Access";
            if (resendTwoFactorAuthentication)
            {
                UserClient uc     = new UserClient();
                var        result = uc.ResendTwoFactorAuthentication(m.UserName);
                if (result.Succeeded)
                {
                    TempData["NotificationMessage"] = "Code has been send";
                }
                else
                {
                    ModelState.AddModelError("", result.ErrorMessages);
                }
            }
            return(View(m));
        }
Пример #3
0
        public async Task <IActionResult> TwoFactor(TwoFactorModel model)
        {
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Your login request has expired, please start over");
                return(View());
            }
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByIdAsync(result.Principal.FindFirstValue("sub"));

                if (user != null)
                {
                    var isValid = await userManager.VerifyTwoFactorTokenAsync(user, result.Principal.FindFirstValue("amr"), model.Token);

                    if (isValid)
                    {
                        await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);

                        var claimsPrincipal = await claimsPrincipalFactory.CreateAsync(user);

                        await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claimsPrincipal);

                        return(RedirectToAction("Index"));
                    }

                    ModelState.AddModelError("", "Invalid Token");
                    return(View());
                }
                ModelState.AddModelError("", "Invalid Request");
            }
            return(View());
        }
Пример #4
0
        public async Task <Result> UsePhone(string newNumber, string verificationCode)
        {
            if (_me.IsAnonymous)
            {
                return(new Failure("需要先登录"));
            }

            if (newNumber.StartsWith('+'))
            {
                newNumber = newNumber.Substring(1);
            }
            if (newNumber.StartsWith("86"))
            {
                newNumber = newNumber.Substring(2);
            }

            if (!newNumber.IsMainlandMobile())
            {
                return(new Failure("格式错误"));
            }
            if (_db.UserPhones.Any(x => x.UserId != _me.Id && x.Number == newNumber))
            {
                return(new Failure($"{newNumber.Mask()} 已被其它帐号使用"));
            }

            var verifyModel = new TwoFactorModel {
                SendTo = newNumber, Code = verificationCode
            };
            var verifyResult = await _me.TwoFactor().VerifyTwoFactorCode(verifyModel, true);

            if (!verifyResult.Ok)
            {
                return(verifyResult);
            }

            var userPhone = _db.UserPhones.Find(_me.Id);

            if (userPhone == null)
            {
                userPhone = new UserPhone {
                    UserId = _me.Id
                };
                _db.UserPhones.Add(userPhone);
            }

            userPhone.Number     = newNumber;
            userPhone.IsVerified = true;

            await _db.Normalize().SaveChangesAsync();

            return(new Success());
        }
Пример #5
0
        public ActionResult VerifyCode(TwoFactorModel model, string returnUrl)
        {
            UserClient uc = new UserClient();

            if (uc.TwoFactorAuthenticate(model.UserName, model.TwoFactorCode))
            {
                TempData["UserName"] = model.UserName;
                return(RedirectToAction("SelectRole", new { ReturnUrl = returnUrl }));
            }
            TempData["NotificationMessage"] = "";
            ViewBag.ReturnUrl = returnUrl;
            return(View());
        }
Пример #6
0
        public async Task <ActionResult> TwoFactor(TwoFactorModel model)
        {
            var signInStatus = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, true, model.RememberBrowser);

            switch (signInStatus)
            {
            case SignInStatus.Success:
                return(RedirectToAction("Index", "Home"));

            default:
                ModelState.AddModelError("", "Invalid Credentials");
                return(View(model));
            }
        }
Пример #7
0
        public async Task <ActionResult> TwoFactor(TwoFactorModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("TwoFactorModal", model));
            }

            ModelState.Clear();
            var result = await PaytopiaWriter.UpdateTwoFactor(User.Identity.GetUserId(), model);

            if (!ModelState.IsWriterResultValid(result))
            {
                return(View("TwoFactorModal", model));
            }

            return(CloseModal(result));
        }
Пример #8
0
        public async Task <IActionResult> SmsTwoFactorAuthorizationConfirmed(TwoFactorModel model)
        {
            var user = _userManager.Users.SingleOrDefault(y => y.PhoneNumber == model.PhoneNumber);

            if (user == null)
            {
                ModelState.AddModelError("", $"Пользователей с номером телефона {model.PhoneNumber} больше чем 1");
                return(RedirectToAction(nameof(Login)));
            }

            var verifySucceded = await _userManager.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultPhoneProvider, model.Code);

            if (!verifySucceded)
            {
                ModelState.AddModelError("", "Неверно введен код");
                return(View(model));
            }

            await _signInManager.SignInAsync(user, false);

            return(Redirect(model.ReturnUrl));
        }
        public async Task <Result> UseNewPasswordWithPhoneValidation(string newPassword, string verificationCode)
        {
            var userPhone = _db.UserPhones.Find(_me.Id);

            if (userPhone == null)
            {
                return(new Failure("需要先绑定手机"));
            }

            var verifyModel = new TwoFactorModel {
                SendTo = userPhone.Number, Code = verificationCode
            };
            var verifyResult = await _me.TwoFactor().VerifyTwoFactorCode(verifyModel, true);

            if (!verifyResult.Ok)
            {
                return(verifyResult);
            }
            userPhone.IsVerified = true;

            return(await UseNewPassword(newPassword));
        }
Пример #10
0
        public async Task <IActionResult> TwoFactor(TwoFactorModel model)
        {
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Seu token expirou");
                return(View());
            }

            if (ModelState.IsValid)
            {
                var user = await userManager.FindByIdAsync(result.Principal.FindFirstValue("sub"));

                if (user != null)
                {
                    var isvalid = await userManager.VerifyTwoFactorTokenAsync(user, result.Principal.FindFirstValue("amr"), model.Token);

                    if (isvalid)
                    {
                        await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);

                        var claimsPrincipal = await _userClaimsPrincipalFactory.CreateAsync(user);

                        await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claimsPrincipal);

                        return(RedirectToAction("About"));
                    }

                    ModelState.AddModelError("", "Token inválido");
                    return(View());
                }

                ModelState.AddModelError("", "Requisição inválida");
            }

            return(View());
        }
Пример #11
0
        public HttpResponseMessage ValidateTwoFactor(TwoFactorModel model)
        {
            try
            {
                var userFacade = this.Container.GetInstance <UserFacade>();

                if (!userFacade.IsTwoFactorCodeCorrect(base.UserId.GetValueOrDefault(), model.Code))
                {
                    return(this.Request.CreateResponse(HttpStatusCode.OK, ""));
                }
                else
                {
                    var encCode = EncryptionHelper.Encrypt(base.UserId.ToString(), "code", true);

                    return(this.Request.CreateResponse(HttpStatusCode.OK, encCode));
                }
            }
            catch (Exception ex)
            {
                base.HandleExceptionForResponse(ex);
                return(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Пример #12
0
        public async Task <IActionResult> TwoFactor(TwoFactorModel model)
        {
            // validate if token has expired
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Token has expired");
                return(View());
            }
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(result.Principal.FindFirstValue("sub"));

                if (user != null)
                {
                    // try to find the claims of the user
                    var isValid = await UserManager.VerifyTwoFactorTokenAsync(user, result.Principal.FindFirstValue("amr"), model.Token);

                    if (isValid)
                    {
                        await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);

                        var claimsPrincipal = await UserClaimsPrincipalFactory.CreateAsync(user);

                        await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claimsPrincipal);

                        return(RedirectToAction("About"));
                    }
                    ModelState.AddModelError("", "Invalid token");
                    return(View());
                }
                ModelState.AddModelError("", "Invalid request");
            }
            return(View());
        }
Пример #13
0
 public IActionResult SmsTwoFactorAuthorization(TwoFactorModel model)
 {
     return(View(model));
 }
        public async Task <Result> SignInWithPhone(string mobileNumber, string verificationCode)
        {
            if (string.IsNullOrEmpty(mobileNumber) || string.IsNullOrEmpty(verificationCode))
            {
                return(new Failure(LoginResult.InvalidInput.ToLabel()));
            }
            if (!mobileNumber.IsMainlandMobile())
            {
                return(new Failure(LoginResult.InvalidInput.ToLabel()));
            }

            //读取用户记录
            var user = _db.Users.SingleOrDefault(x => x.Phone != null && x.Phone.Number == mobileNumber);

            var verifyModel = new TwoFactorModel {
                SendTo = mobileNumber, Code = verificationCode
            };
            var verifyResult = await _me.TwoFactor().VerifyTwoFactorCode(verifyModel, true);

            //验证码不通过
            if (!verifyResult.Ok)
            {
                return(await AddLoginRecord(LoginResult.ErrorTwoFactorCode, mobileNumber, user?.Id));
            }

            //如果通过手机号没找到已注册用户,判断用户当前是否已经通过其它方式登录,是的话直接使用该用户身份
            if (user == null && _me.IsAuthenticated)
            {
                user = _db.Users
                       .Where(x => x.Phone == null)
                       .Where(x => x.Id == _me.Id)
                       .SingleOrDefault();
            }

            //如果仍然没找到,自动注册新建用户
            if (user == null)
            {
                user = new User {
                    Phone = new UserPhone {
                        Number     = mobileNumber,
                        IsVerified = true
                    }
                };
                _db.Users.Add(user);
            }
            else
            {
                //用户记录是异常状态时,阻止获得登录身份
                if (user.Status == RowStatus.Suspended)
                {
                    return(await AddLoginRecord(LoginResult.RejectedAccountSuspended, mobileNumber, user.Id));
                }
                if (user.Status == RowStatus.DeletedByAdmin || user.Status == RowStatus.DeletedByUser)
                {
                    return(await AddLoginRecord(LoginResult.RejectedAccountDeleted, mobileNumber, user.Id));
                }
                if (user.Status != RowStatus.Active)
                {
                    return(await AddLoginRecord(LoginResult.RejectedAccountInactive, mobileNumber, user.Id));
                }
            }

            await _db.Normalize().SaveChangesAsync();

            _me.Id          = user.Id;
            _me.DisplayName = user.DisplayName ?? mobileNumber.Mask() !;
            _me.IdentityManager.SaveIdentity(_me);
            _me.User().IsTwoFactorValidated = true;

            return(await AddLoginRecord(LoginResult.Success, mobileNumber, user.Id));
        }
 public async Task <IActionResult> TwoFactor(TwoFactorModel model)
 {
     return(View());
 }