public async Task <IActionResult> OnPostAsync(string returnUrl)
        {
            returnUrl    = returnUrl ?? Url.Content("~/");
            ReturnUrl    = returnUrl;
            Input.Mobile = ConvertClass.PersianToEnglish(Input.Mobile);
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(Input.Mobile);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "No user found with this number");
                    return(Page());
                }
                //Create Token for Reset Password
                var resetPasswordToken = await _userManager.GeneratePasswordResetTokenAsync(user);

                user.ResetPasswordToken = resetPasswordToken;
                //Mobile Verification
                var r = new Random();
                var mobileVerificationToken = r.Next(0, 9999).ToString("D4");
                user.MobileVerificationCode = mobileVerificationToken;
                await _userManager.UpdateAsync(user);

                //Send token (verification code) to the Client
                var bulkSMS            = new BulkSMS(_clientFactory);
                var mobileFormatForSMS = _config.GetValue <string>("BulkSMS:Code") + Input.Mobile.Remove(0, 1);
                var bulkSMSMessage     = new List <BulkSMSMessage>()
                {
                    new BulkSMSMessage()
                    {
                        Number = mobileFormatForSMS,
                        Text   = $"Code= {mobileVerificationToken}. {_config.GetValue<string>("BulkSMS:Website")}"
                    }
                };
                var response = await bulkSMS.SendBulkSMS(senderId : _config.GetValue <string>("BulkSMS:SenderId"), messageParameter : bulkSMSMessage,
                                                         apiKey : _config.GetValue <string>("BulkSMS:ApiKey"),
                                                         clientId : _config.GetValue <string>("BulkSMS:ClientId"));

                if (response.IsSuccessStatusCode)
                {
                    var smsResult = await response.Content.ReadAsStringAsync();

                    //Handle Error
                }
            }

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null, bool acceptTerms = false, bool isMobileConfirmed = false)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ReturnUrl      = returnUrl;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            Input.Mobile   = ConvertClass.PersianToEnglish(Input.Mobile);
            if (ModelState.IsValid)
            {
                //Mobile Verification

                //Create four digint number for verify code as a token
                Random randomNumber = new Random();
                string token        = randomNumber.Next(0, 9999).ToString("D4");

                //Create new user
                var user = new ApplicationUser
                {
                    UserName = Input.Mobile,
                    FullName = Input.FullName,
                    Mobile   = Input.Mobile,
                    MobileVerificationCode = token,
                    IsMobileConfirmed      = false,
                    RegisteredDate         = System.DateTime.Now,
                    ClientRole             = ClientRole.Public
                };

                //Create User and save to database
                var result = await _userManager.CreateAsync(user, Input.Password);


                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, ClientRole.Public.ToString());

                    _logger.LogInformation("User created a new account with password.");
                    //Send token (verification code) to the Client
                    var bulkSMS            = new BulkSMS(_clientFactory);
                    var mobileFormatForSMS = _config.GetValue <string>("BulkSMS:Code") + Input.Mobile.Remove(0, 1);
                    var bulkSMSMessage     = new List <BulkSMSMessage>()
                    {
                        new BulkSMSMessage()
                        {
                            Number = mobileFormatForSMS,
                            Text   = $"Code= {token}. {_config.GetValue<string>("BulkSMS:Website")}"
                        }
                    };
                    var response = await bulkSMS.SendBulkSMS(senderId : _config.GetValue <string>("BulkSMS:SenderId"), messageParameter : bulkSMSMessage,
                                                             apiKey : _config.GetValue <string>("BulkSMS:ApiKey"),
                                                             clientId : _config.GetValue <string>("BulkSMS:ClientId"));

                    if (response.IsSuccessStatusCode)
                    {
                        var smsResult = await response.Content.ReadAsStringAsync();

                        //Handle Error
                    }


                    if (_userManager.Options.SignIn.RequireConfirmedAccount && !string.IsNullOrEmpty(user.Email))
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = user.Email }));
                    }
                    else
                    {
                        //Send Client to verify the phone number
                        user.Id = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(user.Id));
                        return(RedirectToPage("PhoneNumberVerification", new { returnUrl = ReturnUrl, userid = user.Id }));
                    }
                }
                foreach (var error in result.Errors)
                {
                    if (error.Code.Equals("DuplicateUserName"))
                    {
                        error.Description = "An account already exists with this number. Please try to login";
                    }
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync(string returnUrl, string userid, string targetPage)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            ReturnUrl = returnUrl;
            userid    = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(userid));
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(userid);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "No user found with this number");
                    return(Page());
                }
                //Mobile Verification

                user.NumberOfResendVerificationCode++;

                if (user.NumberOfResendVerificationCode > 6)
                {
                    if ((DateTime.Now.Minute - user.LastResendVerificationCode.Minute > 4))
                    {
                        user.NumberOfResendVerificationCode = 0;
                        await _userManager.UpdateAsync(user);
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Due to high demand, it is not possible to resend for up to five minutes for security reasons");
                        return(Page());
                    }
                }
                var r = new Random();
                var mobileVerificationToken = r.Next(0, 9999).ToString("D4");
                user.MobileVerificationCode     = mobileVerificationToken;
                user.LastResendVerificationCode = DateTime.Now;
                await _userManager.UpdateAsync(user);

                //Send token (verification code) to the Client
                try
                {
                    var bulkSMS            = new BulkSMS(_clientFactory);
                    var mobileFormatForSMS = _config.GetValue <string>("BulkSMS:Code") + user.Mobile.Remove(0, 1);
                    var bulkSMSMessage     = new List <BulkSMSMessage>()
                    {
                        new BulkSMSMessage()
                        {
                            Number = mobileFormatForSMS,
                            Text   = $"Code= {mobileVerificationToken}. {_config.GetValue<string>("BulkSMS:Website")}"
                        }
                    };
                    var response = await bulkSMS.SendBulkSMS(senderId : _config.GetValue <string>("BulkSMS:SenderId"), messageParameter : bulkSMSMessage,
                                                             apiKey : _config.GetValue <string>("BulkSMS:ApiKey"),
                                                             clientId : _config.GetValue <string>("BulkSMS:ClientId"));

                    if (response.IsSuccessStatusCode)
                    {
                        var smsResult = await response.Content.ReadAsStringAsync();

                        //Handle Error
                    }
                    user.Id = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(user.Id));
                    if (targetPage == "ForgotPasswordConfirmation")
                    {
                        return(RedirectToPage("ForgotPasswordConfirmation", new { returnUrl = returnUrl, userid = user.Id }));
                    }
                    else
                    {
                        return(RedirectToPage("PhoneNumberVerification", new { returnUrl = returnUrl, userid = user.Id }));
                    }
                }
                catch (Kavenegar.Exceptions.ApiException ex)
                {
                    // در صورتی که خروجی وب سرویس 200 نباشد این خطارخ می دهد.
                    ModelState.AddModelError(string.Empty, "خطا در ارسال کد فعالسازی");
                    return(Page());
                }
                catch (Kavenegar.Exceptions.HttpException ex)
                {
                    // در زمانی که مشکلی در برقرای ارتباط با وب سرویس وجود داشته باشد این خطا رخ می دهد
                    ModelState.AddModelError(string.Empty, "خطا در ارسال کد فعالسازی");
                    return(Page());
                }
            }

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl    = returnUrl ?? Url.Content("~/");
            ReturnUrl    = returnUrl;
            Input.Mobile = ConvertClass.PersianToEnglish(Input.Mobile);
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(Input.Mobile);

                if (user != null)
                {
                    if (!user.IsMobileConfirmed)
                    {
                        string token = user.MobileVerificationCode;
                        //Send token to the KavenegarApi (for sending to client)
                        if (string.IsNullOrEmpty(token))
                        {
                            Random randomNumber = new Random();
                            token = randomNumber.Next(0, 9999).ToString("D4");
                            user.MobileVerificationCode = token;
                            await _userManager.UpdateAsync(user);
                        }
                        var bulkSMS            = new BulkSMS(_clientFactory);
                        var mobileFormatForSMS = _config.GetValue <string>("BulkSMS:Code") + user.Mobile.Remove(0, 1);
                        var bulkSMSMessage     = new List <BulkSMSMessage>()
                        {
                            new BulkSMSMessage()
                            {
                                Number = mobileFormatForSMS,
                                Text   = $"Code= {token}. {_config.GetValue<string>("BulkSMS:Website")}"
                            }
                        };
                        var response = await bulkSMS.SendBulkSMS(senderId : _config.GetValue <string>("BulkSMS:SenderId"), messageParameter : bulkSMSMessage,
                                                                 apiKey : _config.GetValue <string>("BulkSMS:ApiKey"),
                                                                 clientId : _config.GetValue <string>("BulkSMS:ClientId"));

                        if (response.IsSuccessStatusCode)
                        {
                            var smsResult = await response.Content.ReadAsStringAsync();

                            //Handle Error
                        }
                        //Send Client to verify the phone number
                        user.Id = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(user.Id));
                        return(RedirectToPage("PhoneNumberVerification", new { returnUrl = ReturnUrl, userid = user.Id }));
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Mobile number or password is not correct!");
                    return(Page());
                }
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Mobile, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    HttpContext.Session.SetInt32("Message", (int)Messages.LoggedIn);
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Mobile number or password is not correct!");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }