Having the prerequisites ready, all need to be done is to
modify the existing LogOn action method in the AccountController to have verification feature enabled
(Listing 7).
Listing 7: AccountController
//
// GET: /Account/LogOn
public ActionResult LogOn()
{
ViewBag.VerificationCodeEnabled = false;
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
ViewBag.VerificationCodeEnabled = false;
bool valid = false;
if (ModelState.IsValid)
{
if (Users.ValidateUser(model.UserName, model.Password))
{
if (TrustedClients.ValidateClient(model.UserName,
Request.UserHostAddress, Request.UserAgent))
{
valid = true;
}
else
{
if (string.IsNullOrEmpty(model.VerificationCode))
{
ViewBag.VerificationCodeEnabled = true;
string code = CodeGenerator.GenerateCode();
Users.StoreValidationCode(model.UserName, code);
Messenger.SendTextMessage(Users.GetUserPhone(model.UserName),
string.Format("Your verification code is {0}.", code));
View(model);
}
else
{
if (Users.ReadValidationCode(model.UserName) ==
model.VerificationCode)
{
TrustedClients.AddClient(model.UserName,
Request.UserHostAddress, Request.UserAgent);
valid = true;
}
else
{
ModelState.AddModelError("",
"The verification code is incorrect.");
ViewBag.VerificationCodeEnabled = true;
}
}
}
}
else
{
ModelState.AddModelError("",
"The user name or password provided is incorrect.");
}
}
if (valid)
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 &&
returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
I assume that a programmer who is reading this text is able
to read and understand the logic in this code, but in essence, the user
credentials are checked and if they are correct/valid, the client’s properties
(IP address and user agent) are checked to see if it is already trusted,
otherwise, either the verification code is generated and sent to the user’s
number or the code is retrieved and verified against the data store to log the
user in.