Example #1
0
        public ActionResult VerificationCode(VerificationCodeModel verificationCode)
        {
            if (ModelState.IsValid)
            {
                string     connectionString = ConfigurationManager.ConnectionStrings["Partner"].ConnectionString;
                HttpClient httpClient       = new HttpClient
                {
                    BaseAddress = new Uri(connectionString)
                };
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var phone = TempData["Phone"];
                //var client = new LoyconClient.ServiceClientSoapClient();
                GetConfirmCodeRequest request = new GetConfirmCodeRequest
                {
                    Code  = verificationCode.Code,
                    Phone = Convert.ToInt64(phone)
                };
                HttpResponseMessage responseMessage = httpClient.PostAsJsonAsync("api/values/GetConfirmCode", request).Result;
                if (responseMessage.IsSuccessStatusCode)
                {
                    GetConfirmCodeResponse confirm = responseMessage.Content.ReadAsAsync <GetConfirmCodeResponse>().Result;
                    if (confirm.ErrorCode == 0)
                    {
                        TempData["Code"] = verificationCode.Code;
                        return(RedirectToAction("NewPassword", "Account"));
                    }
                }
            }
            return(View(verificationCode));
        }
Example #2
0
        public async Task UserTriesToConfirmEmail_WithCustomerThatIsAlreadyVerified_AlreadyVerifiedReturned()
        {
            var verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();
            var callRateLimiterService      = new Mock <ICallRateLimiterService>();

            var customerProfileClient = new Mock <ICustomerProfileClient>();

            customerProfileClient.Setup(c => c.CustomerProfiles.GetByCustomerIdAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(
                new CustomerProfileResponse
            {
                Profile = new CustomerProfile.Client.Models.Responses.CustomerProfile
                {
                    Email = "*****@*****.**"
                }
            });

            var verificationEmailGetResponse = new VerificationCodeModel
            {
                CustomerId       = "70fb9648-f482-4c29-901b-25fe6febd8af",
                ExpireDate       = DateTime.UtcNow,
                VerificationCode = "DDD666",
                IsVerified       = true
            };

            verificationEmailRepository
            .Setup(x => x.GetByValueAsync(It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse);

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync((IVerificationCode)null);

            var publisherEmailMessage = new Mock <IRabbitPublisher <EmailMessageEvent> >();
            var publisherCodeVerified = new Mock <IRabbitPublisher <EmailCodeVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    logFactory,
                    publisherEmailMessage.Object,
                    publisherCodeVerified.Object,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    EmailVerificationLink,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    customerProfileClient.Object,
                    callRateLimiterService.Object
                    );
            }

            var result = await emailVerificationService.ConfirmCodeAsync("DDD666".ToBase64());

            Assert.Equal(VerificationCodeError.AlreadyVerified.ToString(), result.Error.ToString());
            Assert.True(result.IsVerified);
        }
Example #3
0
        /// <summary>
        /// Method Name     : GetVerifyCode
        /// Author          : Sanket Prajapati
        /// Creation Date   : 2 Dec 2017
        /// Purpose         : For use Verify code
        /// Revision        :
        /// </summary>
        public ServiceResponse GetVerifyCode(int?strVerifyCode)
        {
            string errorMessage = string.Empty;
            bool   isVerified   = false;

            VerificationCodeModel verificationCodeModel = new VerificationCodeModel {
                VerificationCode = strVerifyCode
            };

            errorMessage = loginValidateServices.ValidateVerificationCodeModel(verificationCodeModel);

            if (string.IsNullOrEmpty(errorMessage))
            {
                APIResponse <CustomerModel> response = loginAPIServies.CheckVerificationCode(verificationCodeModel, UtilityPCL.LoginCustomerData);
                errorMessage = response.Message;

                if (response.STATUS)
                {
                    isVerified   = true;
                    errorMessage = string.Empty;
                }
            }

            return(getServiceResponse(errorMessage, isVerified));
        }
Example #4
0
        public async Task ChecekVierificationCode(VerificationCodeModel model)
        {
            if (true)
            {
                if (model.VerificationCode.IsNullOrWhiteSpace())
                {
                    throw new UserFriendlyException(L("NotValidVerificationCode"));
                }

                // 分租户获取验证码缓存
                const string key = "VerificationCode_Cache_Key";

                // 从缓存验证码值
                var cacheValue = await _cacheManager.GetValue <string>(key, model.CacheKey, true);

                // 过期
                if (cacheValue.IsNullOrWhiteSpace())
                {
                    throw new UserFriendlyException(L("VerificationCodeExpiredOrNodFound"));
                }

                // 对比
                if (model.VerificationCode.ToLower() != cacheValue)
                {
                    throw new UserFriendlyException(L("NotMatchVerificationCode"));
                }
            }
            else
            {
                throw new UserFriendlyException(L("NotActiveVerificationCode"));
            }
        }
Example #5
0
        //Verifies email
        public async Task VerifyEmailAsync(UserModel user, VerificationCodeModel verification)
        {
            if (user.Status == (int)UserStatus.Valid)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("User Already Verified", "User already verified");
                errors.Throw();
            }

            if (user.Status == (int)UserStatus.Banned)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("User Is Banned", "User is banned from application");
                errors.Throw();
            }

            InformationModel EmailVerificationCodeInfo = await _informationRepository.GetInformationByInformationNameAsync("EmailVerificationCode");

            InformationModel EmailVerificationCodeGenerateDateInfo = await _informationRepository.GetInformationByInformationNameAsync("EmailVerificationCodeGenerateDate");

            UserInformationModel EmailVerificationCode = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, EmailVerificationCodeInfo.Id);

            UserInformationModel EmailVerificationCodeGenerateDate = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, EmailVerificationCodeGenerateDateInfo.Id);

            //Bad request
            if (EmailVerificationCode == null)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Email Verification Code Not Exist", "There is no verification code which is generated for you");
                errors.Throw();
            }

            //Generated code timed out
            if (String.Format("{0:u}", DateTime.UtcNow.AddMinutes(-15)).CompareTo(EmailVerificationCodeGenerateDate.Value) > 0)
            {
                _userInformationRepository.Delete(EmailVerificationCode);
                _userInformationRepository.Delete(EmailVerificationCodeGenerateDate);

                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Verification Code Timeout", "Verification code timed out, please request another verification code");
                errors.Throw();
            }

            //Verification code accepted
            if (EmailVerificationCode.Value == verification.VerificationCode)
            {
                user.Status = (int)UserStatus.Valid;
                _userRepository.Update(user);

                _userInformationRepository.Delete(EmailVerificationCode);
                _userInformationRepository.Delete(EmailVerificationCodeGenerateDate);
            }
            //Verification code does not matched
            else
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Verification Code", "Verification code does not matched");
                errors.Throw();
            }
        }
Example #6
0
        public IHttpActionResult ValidateSecurityCode(VerificationCodeModel model)
        {
            var r = new ReturnItem <RetVerificationCode>();

            if (CustomConfigParam.IsUseRedis)
            {
                string key      = "VerificationCode:" + model.VerificationCode;
                string realCode = new RedisClient(CustomConfigParam.RedisDbNumber).GetString(key);
                if (realCode != null)
                {
                    if (realCode.ToLower() == model.Code.ToLower())
                    {
                        r.Code = 1;
                    }
                    else
                    {
                        r.Code = 0;
                    }
                }
                else
                {
                    r.Code = -1;
                }
            }
            return(InspurJson <RetVerificationCode>(r));
        }
Example #7
0
        public async Task <IActionResult> VerifyEmail([FromBody] VerificationCodeModel verificationCode)
        {
            var user = await _authenticationService.GetUserByIdAsync(verificationCode.UserId);

            await _authenticationService.VerifyEmailAsync(user, verificationCode);

            return(Ok(user.Token));
        }
Example #8
0
        UserTriesToConfirmEmail_WithVerificationCodeThatNotExistsInTheSrorage_VerificationCodeMismatchReturned()
        {
            var verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();
            var callRateLimiterService      = new Mock <ICallRateLimiterService>();

            var customerProfileClient = new Mock <ICustomerProfileClient>();

            var verificationEmailGetResponse = new VerificationCodeModel
            {
                CustomerId       = "70fb9648-f482-4c29-901b-25fe6febd8af",
                ExpireDate       = DateTime.UtcNow.AddYears(1000),
                VerificationCode = "DDD666",
                IsVerified       = false
            };

            var confirmEmailResponse = new ConfirmVerificationCodeResultModel
            {
                Error = VerificationCodeError.VerificationCodeMismatch, IsVerified = true
            };

            verificationEmailRepository
            .Setup(x => x.GetByValueAsync(It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse);

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(verificationEmailGetResponse);

            var publisherEmailMessage = new Mock <IRabbitPublisher <EmailMessageEvent> >();
            var publisherCodeVerified = new Mock <IRabbitPublisher <EmailCodeVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    logFactory,
                    publisherEmailMessage.Object,
                    publisherCodeVerified.Object,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    EmailVerificationLink,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    customerProfileClient.Object,
                    callRateLimiterService.Object
                    );
            }

            var result =
                await emailVerificationService.ConfirmCodeAsync("123456".ToBase64());

            Assert.Equal(confirmEmailResponse.Error.ToString(), result.Error.ToString());
            Assert.False(result.IsVerified);
        }
Example #9
0
 public static VerificationCode MapToVerificationCodeEntity(VerificationCodeModel verificationCodeModel)
 {
     return(new VerificationCode
     {
         Id = verificationCodeModel.Id,
         UserId = verificationCodeModel.UserId,
         ExpiresOn = verificationCodeModel.ExpiresOn,
         Code = verificationCodeModel.Code
     });
 }
Example #10
0
        private async Task InitCostumerWithCode(int phoneCode)
        {
            var verificationModel = new VerificationCodeModel
            {
                Code     = phoneCode,
                Costumer = this.Costumer
            };
            await _appRepository.VerificationCodes.AddAsync(verificationModel);

            await _appRepository.SaveChangesAsync();
        }
Example #11
0
        public IActionResult ValidateAccessCode([FromBody] VerificationCodeModel model)
        {
            var response = new HttpBaseResponse
            {
                Success = false
            };

            if (_accountService.ValidateAccessCode(model.PhoneNumber, model.Code))
            {
                response.Success = true;
            }

            return(Ok(response));
        }
Example #12
0
        /// <summary>
        /// Method Name     : ValidateVerificationCodeModel
        /// Author          : Hiren Patel
        /// Creation Date   : 5 Dec 2017
        /// Purpose         : Validate verification code model.
        /// Revision        :
        /// </summary>
        /// <param name="verificationCodeModel"></param>
        /// <returns></returns>
        public string ValidateVerificationCodeModel(VerificationCodeModel verificationCodeModel)
        {
            string errorMessage = string.Empty;

            if (verificationCodeModel.VerificationCode is null)
            {
                errorMessage = Resource.msgRequiredVerificationCode;
            }
            else if (verificationCodeModel.VerificationCode.ToString() == "0")
            {
                errorMessage = Resource.msgCorrectVerificationCode;
            }
            else if (verificationCodeModel.VerificationCode.ToString().Length < 6)
            {
                errorMessage = Resource.msgRequired6digitVerificationCode;
            }

            return(errorMessage);
        }
Example #13
0
        public async Task <IActionResult> GenerateAccessCode([FromBody] VerificationCodeModel model)
        {
            var userAccount = _accountService.GetByPhoneNumber(model.PhoneNumber);
            var response    = new HttpBaseResponse
            {
                Success = false
            };

            if (!string.IsNullOrEmpty(userAccount?.Id))
            {
                var accessCode = await _accountService.GenerateAccessCode(userAccount.Id);

                if (!string.IsNullOrEmpty(accessCode))
                {
                    response.Success = true;
                    response.Object  = JsonConvert.SerializeObject(accessCode);
                }
            }

            return(Ok(response));
        }
Example #14
0
        /// <summary>
        /// Method Name     : CheckVerificationCode
        /// Author          : Hiren Patel
        /// Creation Date   : 20 Dec 2017
        /// Purpose         : validate verification code base on code valid till date with current date
        /// Revision        :
        /// </summary>
        /// <param name="verifyCodeModel"></param>
        /// <param name="customerModel"></param>
        /// <returns></returns>
        public APIResponse <CustomerModel> CheckVerificationCode(VerificationCodeModel verifyCodeModel, CustomerModel customerModel)
        {
            APIResponse <CustomerModel> apiResponse = new APIResponse <CustomerModel>();
            DateTime codeValidTill = Convert.ToDateTime(customerModel.CodeValidTill);

            if (codeValidTill < DateTime.Today)
            {
                apiResponse.Message = Resource.msgVerificationcodeisexpired;
            }
            else
            {
                apiResponse.STATUS = (verifyCodeModel.VerificationCode == customerModel.VerificationCode);
                apiResponse.DATA   = customerModel;

                if (!apiResponse.STATUS)
                {
                    apiResponse.Message = Resource.msgCorrectVerificationCode;
                }
            }

            return(apiResponse);
        }
        public async Task <ResponseModel <string> > CreateAsync(VerificationCodeModel verificationCode)
        {
            if (string.IsNullOrWhiteSpace(verificationCode.UserId))
            {
                var user = await _applicationUserRepository.GetUserByPhoneNumberAsync(verificationCode.PhoneNumber);

                if (user == null)
                {
                    return(new GetResponse <string>("").GetErrorResponse("Unable to find such account"));
                }
                verificationCode.UserId = user.Id;
            }
            verificationCode.Code = new PasswordHelper().GeneratePassword();
            var result = await _verificationCodeRepository.CreateAsync(MapToVerificationCode.MapToVerificationCodeEntity(verificationCode));

            if (result)
            {
                var result = new TwilioHelper().SendMessage(verificationCode.PhoneNumber, verificationCode.Code);
                return(new GetResponse <string>("").GetSuccessResponse(""));
            }
            return(new GetResponse <string>("").GetErrorResponse(""));
        }
Example #16
0
        public async Task <IActionResult> VerificationCode([FromBody] VerificationCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = await _userRepository.FindUser(model.PhoneNumber);

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

            var result = user.VerificationCode.Equals(model.VerificationCode);

            if (result)
            {
                await _userRepository.ConfirmPhone(user);
            }

            return(Ok(result));
        }
Example #17
0
        public ActionResult ForgetPassword(ForgetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                string     connectionString = ConfigurationManager.ConnectionStrings["Partner"].ConnectionString;
                HttpClient httpClient       = new HttpClient
                {
                    BaseAddress = new Uri(connectionString)
                };
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                //var client = new LoyconClient.ServiceClientSoapClient();
                //string phone = model.Phone.Substring(4).Replace(")", "").Replace("-", "").Replace(" ", "");
                ManagerSendCodeRequest request = new ManagerSendCodeRequest
                {
                    Login = model.Login
                };
                HttpResponseMessage responseMessage = httpClient.PostAsJsonAsync("api/values/ManagerSendCode", request).Result;

                //var d = client.GetSendVerificationCode(request);
                if (responseMessage.IsSuccessStatusCode)
                {
                    ManagerSendCodeResponse verificationCodeResponse = responseMessage.Content.ReadAsAsync <ManagerSendCodeResponse>().Result;
                    if (verificationCodeResponse.ErrorCode == 0)
                    {
                        VerificationCodeModel codeModel = new VerificationCodeModel {
                            Phone = verificationCodeResponse.Phone
                        };
                        TempData["Phone"] = codeModel.Phone;
                        return(RedirectToAction("VerificationCode", "Account"));
                    }
                }
            }

            return(View(model));
        }
        public async Task <bool> ConfirmCode(VerificationCodeModel verificationCode)
        {
            var result = await _verificationCodeRepository.CheckCodeAndConfirm(MapToVerificationCode.MapToVerificationCodeEntity(verificationCode));

            return(result);
        }
Example #19
0
        UserTriesToGenerateVerificationEmail_WithCustomerThatIsAlreadyVerified_AlreadyVerifiedReturned()
        {
            const string customerId                  = "70fb9648-f482-4c29-901b-25fe6febd8af";
            var          callRateLimiterService      = new Mock <ICallRateLimiterService>();
            var          verificationEmailRepository = new Mock <IEmailVerificationCodeRepository>();
            var          customerProfileClient       = new Mock <ICustomerProfileClient>();

            callRateLimiterService.Setup(x => x.IsAllowedToCallEmailVerificationAsync(customerId))
            .ReturnsAsync(true);

            customerProfileClient.Setup(c => c.CustomerProfiles.GetByCustomerIdAsync(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(
                new CustomerProfileResponse
            {
                Profile = new CustomerProfile.Client.Models.Responses.CustomerProfile
                {
                    Email = "*****@*****.**"
                }
            });

            var verifyRequestResponse = new VerificationCodeModel
            {
                VerificationCode = Guid.NewGuid().ToString("D"),
                CustomerId       = customerId,
                IsVerified       = true
            };

            verificationEmailRepository
            .Setup(x => x.CreateOrUpdateAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(verifyRequestResponse);

            verificationEmailRepository
            .Setup(x => x.GetByCustomerAsync(It.IsAny <string>()))
            .ReturnsAsync(verifyRequestResponse);

            var publisherEmailMessage = new Mock <IRabbitPublisher <EmailMessageEvent> >();
            var publisherCodeVerified = new Mock <IRabbitPublisher <EmailCodeVerifiedEvent> >();

            EmailVerificationService emailVerificationService;

            using (var logFactory = LogFactory.Create().AddUnbufferedConsole())
            {
                emailVerificationService = new EmailVerificationService(
                    verificationEmailRepository.Object,
                    logFactory,
                    publisherEmailMessage.Object,
                    publisherCodeVerified.Object,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    EmailVerificationLink,
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    customerProfileClient.Object,
                    callRateLimiterService.Object
                    );
            }

            var result = await emailVerificationService.RequestVerificationAsync(customerId);

            Assert.Equal(VerificationCodeError.AlreadyVerified.ToString(), result.Error.ToString());
        }
Example #20
0
        /// <summary>
        /// Method Name     : PostCustomerVerificationData
        /// Author          : Hiren Patel
        /// Creation Date   : 18 Dec 2017
        /// Purpose         : Posts the customer verification data.
        /// Revision :
        /// </summary>
        /// <returns>The customer verification data.</returns>
        /// <param name="verificationCodeModel">Verification code model.</param>
        public async Task <APIResponse <CustomerModel> > PostCustomerVerificationData(VerificationCodeModel verificationCodeModel)
        {
            string apiURL = string.Format(Resource.CustomerVerificationUrl, baseAPIURL, verificationCodeModel.CustomerId);
            APIResponse <CustomerModel> response = new APIResponse <CustomerModel> {
                STATUS = false
            };

            HttpResponseMessage responseMessage = await apiHelper.InvokePostAPI <VerificationCodeModel>(apiURL, verificationCodeModel);

            if (responseMessage.StatusCode == HttpStatusCode.OK)
            {
                response.STATUS  = true;
                response.Message = Resource.msgPostCustomerService;
            }
            else
            {
                if (responseMessage.StatusCode == HttpStatusCode.NoContent)
                {
                    response.Message = Resource.msgInvalidCustomer;
                }
                else
                {
                    response.Message = apiHelper.GetAPIResponseStatusCodeMessage(responseMessage);
                }
            }
            return(response);
        }