[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
var validCredentials = await UserManager.FindAsync(model.Email, model.Password);
if (await UserManager.IsLockedOutAsync(user.Id))
{
ModelState.AddModelError("", string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString()));
}
else if (await UserManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null)
{
await UserManager.AccessFailedAsync(user.Id);
string message;
if (await UserManager.IsLockedOutAsync(user.Id))
{
message = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].ToString());
}
else
{
int accessFailedCount = await UserManager.GetAccessFailedCountAsync(user.Id);
int attemptsLeft =
Convert.ToInt32(
ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].ToString()) -
accessFailedCount;
message = string.Format(
"Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft);
}
ModelState.AddModelError("", message);
}
else if (validCredentials == null)
{
ModelState.AddModelError("", "Invalid credentials. Please try again.");
}
else
{
await SignInAsync(user, model.RememberMe);
await UserManager.ResetAccessFailedCountAsync(user.Id);
return RedirectToLocal(returnUrl);
}
}
}
return View(model);
}