示例#1
0
文件: User.cs 项目: x8mhz/BookStore
 public void Verify(string verification)
 {
     if (verification == VerificationCode.ToString().ToUpper())
     {
         Verification = true;
     }
 }
        public Task SendSmsAsync(string number, string message)
        {
            if (smtp.UsePickupFolder)
            {
                string path = $@"{smtp.PickupFolder}\{number}.txt";
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine($"{number}");
                        sw.WriteLine($"Verification code: {message}");
                    }
                }
            }
            else
            {
                SmsIrRestful.Token tk     = new SmsIrRestful.Token();
                string             result = tk.GetToken("f102ae793839867ae1ee90f4", "d@k@nB2z1&2&3@VN@87134");

                RestVerificationCode messageSendObject = new RestVerificationCode()
                {
                    Code         = message,
                    MobileNumber = number
                };
                RestVerificationCodeRespone restVerificationCodeRespone = new VerificationCode().Send(result, messageSendObject);
            }

            return(Task.FromResult(0));
        }
示例#3
0
        private static VerificationCode ExtractInfo(string data)
        {
            if (data.Length < 6)
            {
                return(null);
            }
            else
            {
                VerificationCode verificationCode = new VerificationCode();

                try
                {
                    string[] slices = data.Split(new char[] { '┇' }, StringSplitOptions.None);

                    string phoneNum = slices[1];

                    string code = string.Empty;

                    Match match = Regex.Matches(slices[4], @"\d\d\d-\d\d\d")[0];

                    string result = match.Value.Replace("-", "");

                    verificationCode.Code     = result;
                    verificationCode.PhoneNum = phoneNum;
                }
                catch (Exception ex)
                {
                    LogUtils.Error($"{ex}");
                }

                return(verificationCode);
            }
        }
示例#4
0
        public ActionResult Create([Bind(Include = "Id,UserName,PassWord,Email,Phone,Status")] Account account)
        {
            if (ModelState.IsValid)
            {
                var random = new Random();
                account.Status = Account.AccountStatus.INACTICE;

                var newAccount = db.Accounts.Add(account);

                db.SaveChanges();
                var code = new VerificationCode()
                {
                    AccountId = newAccount.Id,
                    Code      = random.Next(100000, 999999).ToString()
                };

                var newCode = db.VerificationCodes.Add(code);

                var accountSid = "AC6f7db6a784b209ec8a1a9b9da19c68ce";
                var authToken  = "[AuthToken]";
                TwilioClient.Init(accountSid, authToken);

                var messageOptions = new CreateMessageOptions(
                    new PhoneNumber(newAccount.Phone));
                messageOptions.MessagingServiceSid = "MG1c7f4e78f0273088ca8993888a73d3e5";
                messageOptions.Body = "Your Verification Code : " + newCode.Code;

                var message = MessageResource.Create(messageOptions);
                Console.WriteLine(message.Body);
                return(View("VerificationCode"));
                //return RedirectToAction("Index");
            }

            return(View(account));
        }
示例#5
0
        private async Task SendVerificationCode()
        {
            try
            {
                if (VerificationCode.HasValue())
                {
                    _validator = new VerificationCodeValidator(VerificationCodeEntered);

                    if (ProcessValidationErrors(_validator.Validate(this)))
                    {
                        IsBusy = true;
                        var clientFromRemote = await _userManager.GetContact(emailAddress, true);

                        if (clientFromRemote != null)
                        {
                            await NavigateSuccess(clientFromRemote);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ProcessErrorReportingForRaygun(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
示例#6
0
        private static void HandleInfo(VerificationCode verificationCode)
        {
            Console.WriteLine($"手机号:{verificationCode.PhoneNum}, 验证码:{verificationCode.Code}");

            try
            {
                var obj = new JObject()
                {
                    { "tasktype", (int)TaskType.SendVerificationCode }, { "txtmsg", verificationCode.Code }
                };
                var list = new JArray();
                obj.Add("list", list);

                int vmIndex = VmManager.Instance.VmModels.Values.FirstOrDefault(vm => vm.PhoneNumber == verificationCode.PhoneNum).Index;

                TaskSch taskSch = new TaskSch()
                {
                    Bodys       = obj.ToString(Formatting.None),
                    MobileIndex = vmIndex,
                    TypeId      = (int)TaskType.SendVerificationCode,
                    Status      = "waiting",
                };

                TasksBLL.CreateTask(taskSch);

                ConfigVals.IsRunning = 1;
                TasksSchedule tasks = new TasksSchedule();
                tasks.ProessTask();
            }
            catch (Exception ex)
            {
                LogUtils.Error($"{ex}");
            }
        }
示例#7
0
        public void Providing_correct_code_after_three_incorrect_attempts(string validCode, HttpResponseMessage verificationRequestResponse, string invalidCode, HttpResponseMessage verificationSubmissionResponse)
        {
            "Given I have a user with a verified email and unverified phone number".x(async() => { await this.smsDriver.RegisterUser(emailVerified: true, phoneVerified: false); });

            "And I can login as the user".x(async() => { await this.smsDriver.Login(); });

            "When I request a code to be sent via SMS to verify my phone number".x(async() => { verificationRequestResponse = await this.smsDriver.RequestSMSCode(); });

            "And the request is accepted".x(() => verificationRequestResponse.StatusCode.Should().Be(HttpStatusCode.Accepted));

            "And I wait for the email confirmation code".x(async() => { validCode = await this.smsDriver.WaitForSMS(); });

            "And I have an invalid code".x(() => { invalidCode = VerificationCode.Generate().ToString(); });

            "And I send the invalid code".x(async() => verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode));

            "Then the code is rejected".x(() => verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest));

            "And When I submit the invalid code again".x(async() => verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode));

            "Then the code is rejected".x(() => verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest));

            "And When I submit the invalid code a third time".x(async() => verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode));

            "Then the code is rejected".x(() => verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest));

            "And when I submit the valid code".x(async() => verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(validCode));

            "Then the code is rejected".x(() => verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest));
        }
示例#8
0
        public static VerificationCode GetVerificationCodeByUid(int sellerId, int userId)
        {
            var cmdText = @"select * from VerificationCode where SellerId=?SellerId and UserId =?UserId and ExpiredTime>?ExpiredTime limit 1;";
            List <MySqlParameter> parameters = new List <MySqlParameter>();

            parameters.Add(new MySqlParameter("?SellerId", sellerId));
            parameters.Add(new MySqlParameter("?UserId", userId));
            parameters.Add(new MySqlParameter("?ExpiredTime", DateTime.Now));
            try
            {
                using (var conn = Utility.ObtainConn(Utility._gameDbConn))
                {
                    MySqlDataReader reader = MySqlHelper.ExecuteReader(conn, CommandType.Text, cmdText, parameters.ToArray());
                    if (reader.HasRows)
                    {
                        if (reader.Read())
                        {
                            VerificationCode verificationCode = new VerificationCode();
                            verificationCode.Id          = reader.GetInt32(0);
                            verificationCode.SellerId    = (int)reader["SellerId"];
                            verificationCode.Phone       = reader["Phone"].ToString();
                            verificationCode.Code        = reader["Code"].ToString();
                            verificationCode.ExpiredTime = (DateTime)reader["ExpiredTime"];
                            return(verificationCode);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return(null);
        }
示例#9
0
        public async Task SendConfirmEmailCodeAsync(string email, string captcha)
        {
            _captchaManager.CheckCaptcha(captcha);
            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                throw new UserFriendlyException("找不到此邮箱关联的用户");
            }
            if (user.IsActive && user.IsEmailConfirmed)
            {
                throw new UserFriendlyException("您的邮箱已处于激活状态,直接登录即可");
            }
            string code = VerificationCode.GetRandomCode();

            _cacheManager.GetCache("EmailCode").Set(email, code, new TimeSpan(0, 10, 0));

            var secretkey = user.Id + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "|" + Guid.NewGuid().ToString("N");

            secretkey = secretkey.EncryptQueryString();
            var url = await SettingManager.GetSettingValueAsync(AppSettingNames.SiteUrl) + $"/#/confirm?key={secretkey}";

            var subject = "验证码";
            var body    = $"您好,您的验证码为:{code}";
            await _emailSender.SendAsync(email, subject, body);
        }
示例#10
0
        public IActionResult VerificationCode()
        {
            var codeGenerator = new VerificationCode();
            var code          = codeGenerator.GenerateCode();

            return(File(codeGenerator.CreateCode(code), @"image/Gif"));
        }
示例#11
0
        public void Send()
        {
            var token = GetToken();

            if (string.IsNullOrWhiteSpace(token))
            {
                throw new Exception($@"{nameof(token) } is null");
            }

            var restVerificationCode = new RestVerificationCode()
            {
                Code         = "1234567890",
                MobileNumber = "09353429089"
            };

            RestVerificationCodeRespone restVerificationCodeRespone = new VerificationCode().Send(token, restVerificationCode);

            if (restVerificationCodeRespone == null)
            {
                throw new Exception($@"{nameof(restVerificationCodeRespone) } is null");
            }

            if (restVerificationCodeRespone.IsSuccessful)
            {
            }
            else
            {
            }
        }
示例#12
0
        public void TwoInstanceHaveTheSameHashCodeWhenTheirValuesAreEqual()
        {
            var sut   = VerificationCode.Generate();
            var other = VerificationCode.Generate();

            Assert.False(sut.GetHashCode().Equals(other.GetHashCode()));
        }
示例#13
0
        public List <object> HrLogin(string user, string pwd, string yzm, string systemYzm)
        {
            List <object> result = new List <object>();

            if (VerificationCode.ComparisonVerCode(yzm, systemYzm))
            {
                List <admin> admins = base.Search(d => d.admin_Username == user && d.admin_Password == pwd && d.admin_IsDel == false && d.admin_Power == 2);
                if (admins.Count != 0)
                {
                    result.Add(1);
                    result.Add(admins[0].admin_Id);
                }
                else
                {
                    result.Add(0);
                    result.Add("用户名或密码错误!");
                }
            }
            else
            {
                result.Add(0);
                result.Add("验证码错误!");
            }
            return(result);
        }
示例#14
0
        public void ShouldBeActiveIfConfirmed()
        {
            var code          = VerificationCode.Generate();
            var failedRequest = new VerificationRequest("userId", VerificationType.SMS, VerificationRequestStatus.Confirmed, DateTime.MaxValue, code, 2);

            failedRequest.IsActive().Should().BeTrue();
        }
示例#15
0
        public void TwoInstanceAreNotEqualWhenTheirValuesAreNotEqual()
        {
            var sut   = VerificationCode.Generate();
            var other = VerificationCode.Generate();

            Assert.False(sut.Equals(other));
        }
示例#16
0
        public ActionResult VerCode()
        {
            VerificationCode vc = new VerificationCode();

            Session["ver"] = vc.GetVerCode();
            return(File(vc.StreamVerCod(), @"image/jpeg"));
        }
示例#17
0
        public void Providing_incorrect_code_three_times(string invalidCode, HttpResponseMessage verificationRequestResponse, HttpResponseMessage verificationSubmissionResponse)
        {
            "Given I have a user with a verified email and unverified phone number".x(async() => { await this.smsDriver.RegisterUser(emailVerified: true, phoneVerified: false); });

            "And I can login as the user".x(async() => { await this.smsDriver.Login(); });

            "When I request a code to be sent via SMS to verify my phone number".x(async() => { verificationRequestResponse = await this.smsDriver.RequestSMSCode(); });

            "And the request is accepted".x(() => verificationRequestResponse.StatusCode.Should().Be(HttpStatusCode.Accepted));

            "And I have an invalid code".x(() => { invalidCode = VerificationCode.Generate().ToString(); });

            "And I submit the invalid confirmation code to be verified".x(async() => { verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode); });

            "Then the confirmation response is rejected".x(() => verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest)); // todo problem+json parsing KYC-36

            "And I submit the invalid confirmation code to be verified a second time".x(async() => { verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode); });

            "Then the confirmation response is rejected".x(() =>
                                                           verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest)); // todo problem+json parsing

            "And I submit the invalid confirmation code to be verified a third time".x(async() => { verificationSubmissionResponse = await this.smsDriver.SubmitVerificationCode(invalidCode); });

            "Then the confirmation response is rejected with a different error".x(() =>
                                                                                  verificationSubmissionResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest)); // todo problem+json parsing
        }
示例#18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");



            var token = new Token().GetToken("apiKey", "secretKey");

            var restVerificationCode = new RestVerificationCode()
            {
                Code         = "1234567890",
                MobileNumber = "09120000001"
            };

            var restVerificationCodeRespone = new VerificationCode().Send(token, restVerificationCode);

            Console.WriteLine(restVerificationCodeRespone.Message);


            if (restVerificationCodeRespone.IsSuccessful)
            {
            }
            else
            {
            }
            Console.ReadLine();
        }
        private bool ValidateInternal(string columnName)
        {
            switch (columnName)
            {
            case nameof(UserEmail):
                if (!UserEmail.IsValidEmail())
                {
                    ValidationError = (int)ViewModel.ValidationError.InvalidEmail;
                    return(false);
                }
                return(true);

            case nameof(PasswordText):
                return(ValidatePassphrasePolicy(PasswordText));

            case nameof(Verification):
                return(String.Compare(PasswordText, Verification, StringComparison.Ordinal) == 0);

            case nameof(VerificationCode):
                return(VerificationCode.Length == 6 && VerificationCode.ToCharArray().All(c => Char.IsDigit(c)));

            case nameof(ErrorMessage):
                return(ErrorMessage.Length == 0);

            default:
                return(true);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private VerificationCode InnerCreate(VerificationCodeCreateParam param)
        {
            if (param == null)
            {
                return(null);
            }

            VerificationCode result = new VerificationCode();

            result.Key = Guid.NewGuid().ToString("N");

            switch (param.Type)
            {
            case CodeCharacterTypeEnum.Character:
                result.Code = RandomCodeCreator.CreatRandomChar(param.CharacterCount);
                break;

            case CodeCharacterTypeEnum.Number:
                result.Code = RandomCodeCreator.CreatRandomNum(param.CharacterCount);
                break;

            case CodeCharacterTypeEnum.NumberAndCharacter:
                result.Code = RandomCodeCreator.CreatRandomNumAndChar(param.CharacterCount);
                break;
            }
            result.Image = RandomCodeImageCreator.Create(result.Code, param.FontSize);

            return(result);
        }
        public static async Task <Result <UiMessage> > ConfirmEmail <TUser>(
            this IIdentityService <TUser> identity, TUser user, VerificationCode code)
            where TUser : class, IUserKey, IUserEmail
        {
            Guard.Null(nameof(identity), identity);
            Guard.Null(nameof(user), user);
            Guard.Null(nameof(code), code);

            var key = user.Key();

            if (key is null)
            {
                throw new ArgumentException(
                          paramName: nameof(user),
                          message: $"The {nameof(user)} argument's {nameof(user.Key)}() method cannot return null.");
            }

            var tokenValid = await identity.Helper.ValidateEmailVerificationCode(key,
                                                                                 code).ConfigureAwait(false);

            if (!tokenValid)
            {
                return(identity.Helper.InvalidEmailVerificationCode);
            }

            await identity.Helper.ConfirmEmail(user).ConfigureAwait(false);

            await identity.Update(user).ConfigureAwait(false);

            return(new Result <UiMessage>());
        }
示例#22
0
        public void ShouldBeActiveIfPendingAndExpiryGreaterThanNow()
        {
            var code          = VerificationCode.Generate();
            var failedRequest = new VerificationRequest("userId", VerificationType.SMS, VerificationRequestStatus.Pending, DateTime.UtcNow.AddMinutes(1), code, 2);

            failedRequest.IsActive().Should().BeTrue();
        }
        private async Task SendVerificationCode()
        {
            if (VerificationCode.HasValue())
            {
                _validator = new VerificationCodeValidator(VerificationCodeEntered);

                if (ProcessValidationErrors(_validator.Validate(this), true))
                {
                    try
                    {
                        IsBusy = true;
                        var clientFromRemote = await _userManager.GetContact(emailAddress, "", true);

                        if (clientFromRemote != null)
                        {
                            GetLogonDetailsFromRemoteDBResult(clientFromRemote);
                        }
                        else
                        {
                            await GetLogonDetailsFromRemoteDBWrongResult();
                        }
                    }
                    catch (Exception ex)
                    {
                        ProcessErrorReportingForHockeyApp(ex);
                    }
                }
            }
        }
示例#24
0
        private async Task <Response> GetRegistCodeAsync()
        {
            var exist = await _verificationCodeService.ExistAvailableRegistCodeByClientIpAsync(ClientIP).ConfigureAwait(false);

            if (exist)
            {
                return(Ok(new { code = await _verificationCodeService.GetAvailableRegistCodeByClientIpAsync(ClientIP).ConfigureAwait(false) }));
            }
            else
            {
                var help   = VerifyCodeHelper.GetSingleObj();
                var code   = help.CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
                var entity = new VerificationCode
                {
                    Code       = code,
                    Type       = CodeType.Regist,
                    CreatedOn  = DateTime.Now,
                    IsDisabled = false,
                    ClientIp   = ClientIP
                };
                await _verificationCodeService.NewVerificationCodeAsync(entity).ConfigureAwait(false);

                return(Ok(new { code = code }));
            }
        }
示例#25
0
        public void TwoInstanceAreEqualWhenTheirValuesAreEqual()
        {
            var sut   = VerificationCode.Generate();
            var other = new VerificationCode(sut.ToString());

            Assert.True(sut.Equals(other));
        }
示例#26
0
        //验证码
        public ActionResult ValidateCode()
        {
            string code = VerificationCode.GetCheckCode(5);

            Session["ValidateCode"] = code.ToUpper();
            byte[] bytes = VerificationCode.CreateImage(code);
            return(File(bytes, @"image/png"));
        }
        public async Task <VerificationCode> AddCodeAsync(string email, string referer, string returnUrl, string cid, string traffic)
        {
            var code = new VerificationCode(email, referer, returnUrl, cid, traffic);

            await AddCacheAsync(code);

            return(code);
        }
示例#28
0
 /// <summary>
 /// 触发验证码事件
 /// </summary>
 /// <param name="e"></param>
 public virtual string OnVerificationCode(OnVerificationCodeEventArgs e)
 {
     if (VerificationCode != null)
     {
         return(VerificationCode.Invoke(this, e));
     }
     return(string.Empty);
 }
示例#29
0
        public FileContentResult GetVerificationCode()
        {
            VerificationCode code = new VerificationCode();

            code.GetVerificationCode(6);
            Session["VerificationCode"] = code.Code;
            return(File(code.CodeBuffer, @"image/jpeg"));
        }
示例#30
0
 public bool IsCodeMatch(string code)
 {
     if (code == VerificationCode.ToString())
     {
         return(true);
     }
     return(false);
 }