I am wondering if there is a more efficient route to take here. Using AspNet.Identity
I would like to allow the user to sign in to the same text box using either their usernameor email. I went ahead and addressed this issue in the
AccountController Login ActionResult`.
I run the check before calling:
var result = await SignInManager.PasswordSignInAsync(model.Username,
model.Password,
model.RememberMe,
shouldLockout: false);
My method for checking username or email:
// Determine if user has entered their UserName or Email address.
// TODO: research if there is a more efficient way to do this.
using (var db = new ApplicationDbContext())
{
model.Username = (db.Users.Any(p => p.UserName == model.Username)) ?
model.Username :
(db.Users.Any(p => p.Email == model.Username)) ?
db.Users.SingleOrDefault(p => p.Email == model.Username).UserName :
model.Username;
}
My concerns here:
- Is there a more efficient practical way to do this?
- Am I introducing any new security risks or performance risks by doing it this way?
I am including the entire ActionResult
below for reference:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Determine if user has entered their UserName or Email address.
// TODO: research if there is a more efficient way to do this.
using (var db = new ApplicationDbContext())
{
model.Username = (db.Users.Any(p => p.UserName == model.Username)) ?
model.Username :
(db.Users.Any(p => p.Email == model.Username)) ?
db.Users.SingleOrDefault(p => p.Email == model.Username).UserName :
model.Username;
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}