Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 3, 2012 16:40
Show Gist options
  • Save davybrion/3610630 to your computer and use it in GitHub Desktop.
Save davybrion/3610630 to your computer and use it in GitHub Desktop.
code snippets for "Repeated Failed Log-Ins: What's Your Strategy?" post
function delayAuthenticationResponse(session, callback) {
if (!session.attempts) {
session.attempts = 1;
} else {
session.attempts++;
}
setTimeout(callback, session.attempts * 1000);
}
function authenticate(session, name, pass, callback) {
var user = users[name];
if (!user) {
return delayAuthenticationResponse(session, function() {
callback(new Error('cannot find user'));
});
}
if (user.pass == hash(pass, user.salt)) {
delete session.attempts;
return callback(null, user);
}
delayAuthenticationResponse(session, function() {
callback(new Error('invalid password'));
});
}
app.post('/login', function(req, res){
authenticate(req.session, req.body.username, req.body.password, function(err, user){
if (user) {
req.session.regenerate(function(){
req.session.user = user;
res.redirect('back');
});
} else {
req.session.error = 'Authentication failed, please check your '
+ ' username and password.'
+ ' (use "tj" and "foobar")';
res.redirect('back');
}
});
});
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (CredentialsAreValid(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
Session["attempts"] = Session["attempts"] == null ? 1 : (int)Session["attempts"] + 1;
Thread.Sleep((int)Session["attempts"] * 1000);
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
return View(model);
}
[HttpPost]
public void LogOnAsync(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (CredentialsAreValid(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
AsyncManager.Parameters["returnUrl"] = returnUrl;
}
else
{
Session["attempts"] = Session["attempts"] == null ? 1 : (int)Session["attempts"] + 1;
var timeout = (int)Session["attempts"] * 1000;
AsyncManager.OutstandingOperations.Increment();
var timer = new System.Timers.Timer(timeout) { AutoReset = false };
timer.Elapsed += (sender, e) =>
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
AsyncManager.Parameters["model"] = model;
timer.Dispose();
AsyncManager.OutstandingOperations.Decrement();
};
timer.Start();
}
}
}
public ActionResult LogOnCompleted(LogOnModel model, string returnUrl)
{
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
if (model == null)
{
return RedirectToAction("Index", "Home");
}
return View(model);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment