I'm building an ASP.NET Core MVC Application in which I send OTP to the user and the user has to enter the OTP within 30 seconds for the OTP to work. How can I check that the OTP entered by the user in the input field is entered within 30 seconds of the OTP generated?
I have already written the Controller for Generating, Getting & Submitting the OTP. Just need to know the logic of time checking of OTP Generation.
Controller
[HttpGet]
public IActionResult GenerateOtp()
{
return View();
}
[HttpPost]
public IActionResult SendOtp()
{
string num = "01223456789";
int len = num.Length;
string otp = string.Empty;
int otpDigit = 4;
string finalDigit;
int getIndex;
for (int i = 0; i < otpDigit; i ) {
do
{
getIndex = new Random().Next(0, len);
finalDigit = num.ToCharArray()[getIndex].ToString();
} while (otp.IndexOf(finalDigit) != -1 );
otp = finalDigit;
}
TempData["otp"] = otp;
return RedirectToAction("GenerateOtp", "Home");
}
[HttpPost]
public IActionResult SubmitOtp([FromForm] int finalDigit, int sentotp)
{
if (finalDigit == null)
return NoContent();
else if (finalDigit == sentotp && ***30 Second Check Here***)
{
return Ok("Activated Successfully");
}
else if(!(***30 Second Check Here***))
{
return BadRequest("OTP Timedout");
}
else
{
return BadRequest("Please Enter Valid OTP");
}
}
}
}
**View**
@{
ViewData["Title"] = "GenerateOtp";
}
<h1>GenerateOtp</h1>
<form method="post" asp-action="SendOtp" asp-controller="Home">
<br />
<input type="submit" value="GetOtp" />
<br />
<div>
@TempData["otp"]
</div>
<br />
<input type="number"/>
<br />
<input type="submit" value="SubmitOtp" />
</form>
CodePudding user response:
Same as OTP that you saved into the temp data, you can save the timestamp when OTP is sent in the SendOtp Action method. While in the SubmitOtp action method, read that timestamp from the TempData. If the difference between the current and TempData timestamp is more than 30 seconds then reject the request.
public IActionResult GenerateOtp()
{
return View();
}
[HttpPost]
public IActionResult SendOtp()
{
string num = "01223456789";
int len = num.Length;
string otp = string.Empty;
int otpDigit = 4;
string finalDigit;
int getIndex;
for (int i = 0; i < otpDigit; i ) {
do
{
getIndex = new Random().Next(0, len);
finalDigit = num.ToCharArray()[getIndex].ToString();
} while (otp.IndexOf(finalDigit) != -1 );
otp = finalDigit;
}
TempData["otp"] = otp;
TempData["timestamp"] = DateTime.Now;
return RedirectToAction("GenerateOtp", "Home");
}
[HttpPost]
public IActionResult SubmitOtp([FromForm] int finalDigit, int sentotp)
{
if (finalDigit == null)
return NoContent();
else if (finalDigit == sentotp && **30 Second Check Here**)
{
return Ok("Activated Successfully");
}
else if((DateTime.Now - Convert.DateTime(TempData["timestamp"])).TotalSeconds > 30)
{
return BadRequest("OTP Timedout");
}
else
{
return BadRequest("Please Enter Valid OTP");
}
}