Пример #1
0
        public async Task <ActionResult> VerifyCode(VerifyCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                // The following code protects for brute force attacks against the two factor codes.
                // If a user enters incorrect codes for a specified amount of time then the user account
                // will be locked out for a specified amount of time.
                // You can configure the account lockout settings in IdentityConfig
                var result = await _accountService.TwoFactorSignInAsync(model);

                if (result.Succeeded)
                {
                    return(RedirectToLocal(model.ReturnUrl));
                }
                if (result.IsLockedOut)
                {
                    return(View(ConstantMessages.AccountConstant.AccountControllerConstant.Lockout));
                }
                else
                {
                    ModelState.AddModelError("", ConstantMessages.AccountConstant.AccountControllerConstant.InvalidCode);
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                ErrorViewModel errorModel = GlobalExceptionHandler.GetErrorPage(ex.ToString());
                return(View(ConstantMessages.AccountConstant.AccountControllerConstant.ErrorView, errorModel));
            }
        }
Пример #2
0
        public async Task <AuthResult> VerifyCode(VerifyCodeModel model)
        {
            // The following code protects for brute force attacks against the two factor codes.
            // If a user enters incorrect codes for a specified amount of time then the user account
            // will be locked out for a specified amount of time.
            var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);

            var message = new AuthResult();

            if (result.Succeeded)
            {
                message.Suceess = true;
                message.Message = AuthResult.SUCCESS;
            }
            if (result.IsLockedOut)
            {
                message.Message = "User account locked out.";
            }
            else
            {
                message.Message = "Invalid code.";
            }

            return(message);
        }
Пример #3
0
        public void GetVeifyCodeModelTest()
        {
            VerifyCodeManager vcMa = new VerifyCodeManager();

            /*背景是否为图片还是纯色*/
            vcMa.TextConfigM.BackIsImage = true;
            /*背景图片路径(BackIsImage==true时生效)*/
            vcMa.TextConfigM.ImageBackgroundPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\Content\Images";
            /*背景颜色库(BackIsImage==false时生效)*/
            vcMa.TextConfigM.BackgroundColors.Add(Color.Ivory);
            /*值颜色库*/
            vcMa.TextConfigM.ValueColors.Add(Color.Red);
            /*文本库(AllowRandomChinese==true时失效)*/
            vcMa.TextConfigM.TextLibrary.Add("陈明旭中华人民共和国");
            /*采用随机中文模式*/
            vcMa.TextConfigM.AllowRandomChinese = true;
            /*值数量*/
            vcMa.TextConfigM.ValueCount = 4;
            /*混淆数量*/
            vcMa.TextConfigM.ConfusionCount = 10;
            /*图片大小*/
            vcMa.TextConfigM.ImageSize = new Size(120, 30);
            /*字体大小*/
            vcMa.TextConfigM.FontSize = 18;
            /*获取验证码*/
            VerifyCodeModel vcM = vcMa.GetVeifyCodeModel();

            if (vcM.Images.Count > 0)
            {
                string value = vcM.Value;
                vcM.Images[0].Save(@"D:\Images\Temp\VerifyCode.png");
            }
        }
        public async Task <ActionResult> VerifyCode(VerifyCodeModel model)
        {
            if (TempData["user"] == null || TempData["userToken"] == null)
            {
                return(View("Error"));
            }

            var token = TempData["userToken"].ToString();
            var user  = (AppUser)TempData["user"];

            if (model.Code == token)
            {
                if (model.Provider == "СМС")
                {
                    user.PhoneNumberConfirmed = true;
                }
                else if (model.Provider == "Електронна пошта")
                {
                    user.EmailConfirmed = true;
                }

                var identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                GetAuthenticationManager().SignIn(identity);

                return(RedirectToAction("Index", "Home"));
            }

            ModelState.AddModelError("", "Невірний код");
            TempData["user"]      = user;
            TempData["userToken"] = token;

            return(View(model));
        }
Пример #5
0
        public async Task <SignInResult> TwoFactorSignInAsync(VerifyCodeModel model)
        {
            VerifyCodeEntity domainEntity = _mapper.Map <VerifyCodeEntity>(model);
            var result = await _accountRepository.TwoFactorSignInAsync(domainEntity);

            return(result);
        }
Пример #6
0
        /// <summary>
        /// 确认验证码是否正确
        /// </summary>
        /// <param name="taskId">任务Id</param>
        /// <param name="receiver">接收者</param>
        /// <param name="code">验证码</param>
        /// <param name="visitId">访问者ID</param>
        /// <param name="isExpire">是否验证通过立即过期</param>
        /// <returns></returns>
        public bool ConfirmVerifyCode(Guid taskId, string receiver, string code, Guid visitId, bool isExpire = false)
        {
            if (VerifyHelper.IsEmpty(taskId) || VerifyHelper.IsEmpty(receiver) || VerifyHelper.IsEmpty(code) || VerifyHelper.IsEmpty(visitId))
            {
                throw new DefaultException(EnumResultCode.参数错误, "taskId", "receiver", "code", "visitId");
            }

            string key = string.Format(KeyModel.Session.FormatVerifyCode, taskId);

            VerifyCodeModel model = RedisHelper.Get <VerifyCodeModel>(key);

            if (VerifyHelper.IsEmpty(model))
            {
                throw new DefaultException(EnumResultCode.验证码己失效);
            }
            if (model.Code == code && model.Receiver == receiver && model.VisitId == visitId)
            {
                if (isExpire)
                {
                    RedisHelper.Set <VerifyCodeModel>(key, null);
                }
                return(true);
            }

            return(false);
        }
Пример #7
0
        public async Task <IActionResult> VerifyCode([FromBody] VerifyCodeModel options)
        {
            try
            {
                var result = await _resetPasswordService.ValidateConfirmationCodeAsync(options.Email, options.Code);

                return(Ok(new ResetTokenResponse {
                    ResetToken = result
                }));
            }
            catch (KeyNotFoundException)
            {
                return(NotFound());
            }
            catch (ArgumentException ex)
            {
                if (ex.Message == Consts.ErrorReponses.CodeIsNotValid)
                {
                    return(BadRequest(new ValidationProblemDetails(new Dictionary <string, string[]>(new List <KeyValuePair <string, string[]> > {
                        new KeyValuePair <string, string[]>("Code", new string[] { "Code is not valid" })
                    }))));
                }

                throw ex;
            }
        }
Пример #8
0
        private ActionResult HandleVerifySubmit(VerifyCodeModel formData, ConfirmableUserAccount user)
        {
            using (DataContext dataContext = new DataContext("dbOpenXDA"))
            {
                if (s_memoryCache.Contains(formData.type + user.ID.ToString()))
                {
                    string code = s_memoryCache.Get(formData.type + user.ID.ToString()).ToString();

                    if (code != formData.code.ToString("D6"))
                    {
                        TempData["BadCode"] = true;
                        return(RedirectToAction("Verify", new { id = formData.type }));
                    }

                    dataContext.Connection.ExecuteNonQuery($"UPDATE UserAccount Set {(formData.type == "email" ? "EmailConfirmed" : "PhoneConfirmed")} = 1 WHERE ID = '{user.ID}'");
                    s_memoryCache.Remove(formData.type + user.ID.ToString());

                    string emailServiceName = GetEmailServiceName();
                    string recipient        = formData.type == "email" ? user.Email : user.Phone;
                    string subject          = $"{emailServiceName} has confirmed your {(formData.type == "email" ? "email address" : "SMS number")}.";
                    string body             = $"Once you are approved by an administrator, you will begin receiving notifications.";
                    SendEmail(recipient, subject, body);
                }
                else
                {
                    TempData["ExpiredCode"] = true;
                    return(RedirectToAction("Verify", new { id = formData.type }));
                }

                return(RedirectToAction("UpdateSettings"));
            }
        }
Пример #9
0
        public ActionResult VerifyCode(VerifyCodeModel formData)
        {
            using (DataContext dataContext = new DataContext("dbOpenXDA"))
            {
                string username             = HttpContext.User.Identity.Name;
                string usersid              = UserInfo.UserNameToSID(username);
                ConfirmableUserAccount user = dataContext.Table <ConfirmableUserAccount>().QueryRecordWhere("ID = {0}", formData.accountid);

                if (username != user.Name && usersid != user.Name)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
                }

                if (formData.submit == "Submit")
                {
                    return(HandleVerifySubmit(formData, user));
                }
                else if (formData.submit == "Resend Code")
                {
                    return(HandleVerifyResendCode(formData, user));
                }

                ViewBag.Message = "Bad Command";
                return(View("Message"));
            }
        }
Пример #10
0
        private ActionResult HandleVerifyResendCode(VerifyCodeModel formData, ConfirmableUserAccount user)
        {
            string url = m_dataContext.Connection.ExecuteScalar <string>("SELECT Value FROM DashSettings WHERE Name = 'System.URL'");

            // if email changed force reconfirmation
            if (formData.type == "email")
            {
                // generate code for email confirmation
                string code = Random.Int32Between(0, 999999).ToString("D6");
                s_memoryCache.Set("email" + user.ID.ToString(), code, new CacheItemPolicy {
                    SlidingExpiration = TimeSpan.FromDays(1)
                });

                string emailServiceName = GetEmailServiceName();
                string subject          = $"{emailServiceName} requires you to confirm your email.";
                string body             = $"From your workstation, input {code} at {url}/email/verify/email";
                SendEmail(user.Email, subject, body);
            }

            // if phone changed force reconfirmation
            if (formData.type == "sms")
            {
                string code = Random.Int32Between(0, 999999).ToString("D6");
                s_memoryCache.Set("sms" + user.ID.ToString(), code, new CacheItemPolicy {
                    SlidingExpiration = TimeSpan.FromDays(1)
                });

                string emailServiceName = GetEmailServiceName();
                string subject          = $"{emailServiceName} requires you to confirm your SMS number.";
                string body             = $"From your workstation, input {code} at {url}/email/verify/sms";
                SendEmail(user.Phone, subject, body);
            }

            return(RedirectToAction("Verify", new { id = formData.type }));
        }
Пример #11
0
        public async Task <IActionResult> VerifyCode(VerifyCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // The following code protects for brute force attacks against the two factor codes.
            // If a user enters incorrect codes for a specified amount of time then the user account
            // will be locked out for a specified amount of time.
            var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);

            if (result.Succeeded)
            {
                return(RedirectToLocal(model.ReturnUrl));
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(7, "User account locked out.");
                return(View("Lockout"));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid code.");
                return(View(model));
            }
        }
        public HttpResponseMessage GetValidateCode()
        {
            VerifyCodeManager vcMa = new VerifyCodeManager();

            /*背景是否为图片还是纯色*/
            vcMa.TextConfigM.BackIsImage = true;
            /*背景图片路径(BackIsImage==true时生效)*/
            vcMa.TextConfigM.ImageBackgroundPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\Images\ValidateCode";
            /*背景颜色库(BackIsImage==false时生效)*/
            vcMa.TextConfigM.BackgroundColors.Add(Color.Ivory);
            /*值颜色库*/
            vcMa.TextConfigM.ValueColors.Add(Color.Red);
            /*文本库(AllowRandomChinese==true时失效)*/
            vcMa.TextConfigM.TextLibrary = new List <string>
            {
                //"abcdefghijklmnopqrstuvwxyz",
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                "0123456789"
            };
            //vcMa.TextConfigM.TextLibrary.Add("陈明旭中华人民共和国");
            /*采用随机中文模式*/
            vcMa.TextConfigM.AllowRandomChinese = false;
            /*值数量*/
            vcMa.TextConfigM.ValueCount = 4;
            /*混淆数量*/
            vcMa.TextConfigM.ConfusionCount = 10;
            /*混淆模式*/
            vcMa.TextConfigM.ImageObfuscationTypes = new List <VerifyCodeImageObfuscationType>
            {
                /*假值混淆*/
                VerifyCodeImageObfuscationType.FalseValue,
                /*条纹混淆*/
                VerifyCodeImageObfuscationType.Stripe
            };
            /*图片大小*/
            vcMa.TextConfigM.ImageSize = new Size(120, 30);
            /*字体大小*/
            vcMa.TextConfigM.FontSize = 18;
            /*获取验证码*/
            VerifyCodeModel vcM = vcMa.GetVeifyCodeModel();

            if (vcM.Images.Count > 0)
            {
                /*验证码的值存入缓存中*/
                WebCacheManager.Set(ApplicationManager.VALIDATECODEKEY + vcM.Value, vcM.Value, DateTimeOffset.Now.AddMinutes(5));
                using (MemoryStream ms = new MemoryStream())
                {
                    vcM.Images[0].Save(ms, ImageFormat.Jpeg);
                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(ms.ToArray())
                    };
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                    return(result);
                }
            }
            return(null);
        }
        public async Task <IResponse> VerifyCode([FromBody] VerifyCodeModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            return(await _service.VerifyCodeAsync(model));
        }
Пример #14
0
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="uniacid">商户ID</param>
        /// <param name="phoneNumber">手机号码</param>
        /// <returns></returns>
        public IActionResult GetSmsVerifyCode(string uniacid, string phoneNumber)
        {
            var filter = Builders <VerifyCodeModel> .Filter;
            var mongo  = new MongoDBTool();

            var company = mongo.GetMongoCollection <CompanyModel>().Find(x => x.uniacid.Equals(uniacid)).FirstOrDefault();

            if (company == null || company.YTX == null)
            {
                var em = new ExceptionModel()
                {
                    Content = "商户未设置云通信信息"
                };
                em.Save();
                return(this.JsonErrorStatus());
            }

            var collection = mongo.GetMongoCollection <VerifyCodeModel>();
            var date       = DateTime.Now.AddMinutes(VerifyTimeOut);

            collection.DeleteMany(filter.Lt(x => x.CreateTime, date) & filter.Eq(x => x.uniacid, uniacid));
            var             filterSum = filter.Eq(x => x.PhoneNumber, phoneNumber) & filter.Gt(x => x.CreateTime, date);
            VerifyCodeModel vcm       = collection.FindOneAndDelete(filterSum);

            if (vcm == null)
            {
                vcm = new VerifyCodeModel()
                {
                    PhoneNumber = phoneNumber,
                    CreateTime  = DateTime.Now,
                    uniacid     = uniacid
                };
            }
            string jsonData = JsonConvert.SerializeObject(new SMSModel()
            {
                appid  = company.YTX.AppID,
                mobile = vcm.PhoneNumber,
                datas  = new string[] { vcm.VerifyCode, VerifyTimeOut + "" }
            });
            string url = "/sms/TemplateSMS.wx";

            string result = new PhoneHelper(company.YTX).SendRequest(url, jsonData);
            var    jObj   = (JObject)JsonConvert.DeserializeObject(result);
            JToken statuscode;
            bool   hasVal = jObj.TryGetValue("statusCode", out statuscode);

            if (hasVal && statuscode.ToString().Equals("0"))
            {
                collection.InsertOne(vcm);
                return(this.JsonErrorStatus());
            }
            return(this.JsonErrorStatus());
        }
Пример #15
0
        public async Task <IActionResult> VerifyCode(Guid userId, [FromBody] VerifyCodeModel verifyCodeModel)
        {
            var responseModel = await _userService.VerifyCodeAsync(userId, verifyCodeModel.Code);

            if (responseModel.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(Ok(responseModel.Data));
            }
            else
            {
                return(BadRequest(new { Message = responseModel.Message }));
            }
        }
Пример #16
0
        public async Task <object> VerifyCode([FromBody] VerifyCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new
                {
                    success = false,
                    errors = GetModelState()
                });
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Invalid user.");
                return(new
                {
                    success = false,
                    errors = GetModelState()
                });
            }

            var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);

            if (result.Succeeded)
            {
                return(new
                {
                    success = true,
                    user = React.Models.Api.User.From(user)
                });
            }

            ModelState.AddModelError(string.Empty, result.IsLockedOut ? "User account locked out." : "Invalid code.");

            return(new
            {
                success = false,
                errors = GetModelState()
            });
        }
Пример #17
0
        public async Task <IActionResult> VerifyCode(Guid userId, [FromBody] VerifyCodeModel verifyCodeModel)
        {
            var responseModel = await _userService.VerifyCodeAsync(userId, verifyCodeModel.Code);

            return(new CustomActionResult(responseModel));
        }
Пример #18
0
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="receiver">接收者</param>
        /// <param name="type">类型</param>
        /// <param name="paramsList">参数列表</param>
        /// <param name="code">验证码(out 返回)</param>
        /// <param name="visitId">访问者ID</param>
        /// <returns></returns>
        public Guid SendVerifyCode(string receiver, string type, List <KeyValuePair <string, string> > paramsList, Guid visitId, out string code)
        {
            if (VerifyHelper.IsEmpty(receiver) || VerifyHelper.IsEmpty(type) || VerifyHelper.IsEmpty(visitId))
            {
                throw new DefaultException(EnumResultCode.参数错误, "receiver", "type", "visitId");
            }

            //内容
            var content = TemplateConfig.GetValue(type);

            //参数
            if (VerifyHelper.IsEmpty(paramsList))
            {
                paramsList = new List <KeyValuePair <string, string> >();
            }

            //code(必须,默认)
            code = RandHelper.GetRandNumber(6);
            var codeParamModel = paramsList.Where(x => x.Key.ToLower() == "code").FirstOrDefault();

            if (VerifyHelper.IsEmpty(paramsList))
            {
                paramsList.Add(new KeyValuePair <string, string>("code", code));
            }
            else
            {
                codeParamModel = new KeyValuePair <string, string>("code", code);
            }

            //替换
            if (!VerifyHelper.IsEmpty(paramsList))
            {
                paramsList.ForEach(x =>
                {
                    content = content.Replace("{" + x.Key + "}", x.Value);
                });
            }


            List <string> smsTypes = new List <string>()
            {
                KeyModel.Config.Template.KeyRegistMobile,
                KeyModel.Config.Template.KeyBindMobile,
                KeyModel.Config.Template.KeyForgetPwdMobile
            };

            List <string> emailTypes = new List <string>()
            {
                KeyModel.Config.Template.KeyRegistEmail,
                KeyModel.Config.Template.KeyBindEmail,
                KeyModel.Config.Template.KeyForgetPwdEmail
            };

            bool isSuccess = false;

            //发送
            if (smsTypes.Contains(type))
            {
                isSuccess = SendSms(receiver, content);
            }
            if (emailTypes.Contains(type))
            {
                isSuccess = SendEmail(receiver, content);
            }

            if (!isSuccess)
            {
                throw new DefaultException(EnumResultCode.验证码发送失败);
            }

            var model = new VerifyCodeModel();

            model.TaskId   = GuidHelper.NewId();
            model.Receiver = receiver;
            model.Code     = code;
            model.VisitId  = visitId;
            model.SendTime = DateTime.Now;

            //保存
            RedisHelper.Set <VerifyCodeModel>(string.Format(KeyModel.Session.FormatVerifyCode, model.TaskId), model, DateTime.Now.AddMinutes(10));

            return(model.TaskId);
        }
Пример #19
0
        /// <summary>
        /// 检测验证码
        /// </summary>
        private async Task <bool> CheckVerifyCode(ResultModel <LoginResultModel> result, VerifyCodeModel model)
        {
            if (model == null || model.Code.IsNull())
            {
                result.Failed("请输入验证码");
                return(false);
            }

            if (model.Id.IsNull())
            {
                result.Failed("验证码不存在");
                return(false);
            }

            var cacheCode = await _cacheHandler.GetAsync(string.Format(CacheKeys.VerifyCodeKey, model.Id));

            if (cacheCode.IsNull())
            {
                result.Failed("验证码不存在");
                return(false);
            }

            if (!cacheCode.Equals(model.Code))
            {
                result.Failed("验证码有误");
                return(false);
            }

            return(true);
        }
Пример #20
0
        /// <summary>
        /// Verifies the specified code asynchronous.
        /// </summary>
        /// <param name="model">The verify code model.</param>
        /// <returns>A <see cref="Task{TResult}"/> represents the verify operation.</returns>
        public async Task <IResponse> VerifyCodeAsync(VerifyCodeModel model)
        {
            var user = await _userManager.FindByNameAsync(model.PhoneNumber);

            if (user == null)
            {
                if (!ValidateCode(model.Code, model.PhoneNumber))
                {
                    throw new ArgumentException(string.Format(Resources.VerifyCodeFailed, model.Code));
                }

                user = new TUser();

                // set user name
                var result = await _userManager.SetUserNameAsync(user, model.PhoneNumber);

                if (!result.Succeeded)
                {
                    HandleErrors(result, string.Format(Resources.RegisterNewUserFailed, model.PhoneNumber, model.Code));
                }

                // set phone number.
                if (_userManager.SupportsUserPhoneNumber)
                {
                    result = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);

                    if (!result.Succeeded)
                    {
                        HandleErrors(result, string.Format(Resources.RegisterNewUserFailed, model.PhoneNumber, model.Code));
                    }
                }

                var password = $"{GenericUtil.UniqueKey()}@520";
                result = await _userManager.CreateAsync(user, password);

                if (!result.Succeeded)
                {
                    HandleErrors(result, string.Format(Resources.RegisterNewUserFailed, model.PhoneNumber, model.Code));
                }

                SendSmsResult smsResult;
                if (string.IsNullOrWhiteSpace(_options.PasswordSmsTemplate))
                {
                    smsResult = await _smsSender.SendSmsAsync(model.PhoneNumber, password);
                }
                else
                {
                    smsResult = await _smsSender.SendSmsAsync(_options.PasswordSmsTemplate, model.PhoneNumber, Tuple.Create("password", password));
                }
                if (!smsResult.IsSuccessSend)
                {
                    _logger.LogError(string.Format(Resources.SendPasswordFailed, model.PhoneNumber, smsResult.ErrorMessage));
                }

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

                return(await RequestTokenAsync(model.PhoneNumber, password));
            }
            else
            {
                if (!await _userManager.VerifyChangePhoneNumberTokenAsync(user, model.Code, model.PhoneNumber))
                {
                    throw new ArgumentException(string.Format(Resources.VerifyCodeFailed, model.Code));
                }

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

                var token = await RequestTokenAsync(model.PhoneNumber, model.Code);

                if (token.IsError)
                {
                    _logger.LogError(token.ToString());

                    throw new ArgumentNullException(string.Format(Resources.LoginFailedWithCodeAndPhone, model.Code, model.PhoneNumber));
                }

                return(token);
            }
        }