Last active
April 15, 2019 20:00
-
-
Save passatgt/b7505f7aa89b999c1bc7a3cbf7b12c61 to your computer and use it in GitHub Desktop.
Log failed login attempts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
preLoginHandler: function(formData, req, res, next) { | |
var authRequest = { | |
username: formData.login, | |
password: formData.password | |
}; | |
//Try to authenticate the user | |
req.app.get('stormpathApplication').authenticateAccount(authRequest, function(err, result) { | |
//if (err) return helpers.handleError(err,res); | |
if (err && err.code == 7100) { | |
//7100 means the password was wrong, email correct | |
//Find the user by email address | |
req.app.get('stormpathApplication').getAccounts({ | |
email: formData.login | |
}, function(err, results) { | |
if (results && results.size > 0) { | |
var account = results.items[0]; | |
var loginAttempt = {}; | |
account.getCustomData(function(err, customData) { | |
//Setup sessions custom data, if not exists yet | |
if (!customData.loginAttempts) customData.loginAttempts = []; | |
//Log ip address | |
loginAttempt.ip = req.headers['x-forwarded-for'] || | |
req.connection.remoteAddress || | |
req.socket.remoteAddress || | |
req.connection.socket.remoteAddress; | |
//Log user agent | |
loginAttempt.userAgent = req.headers['user-agent']; | |
//Log time | |
loginAttempt.time = Date.now(); | |
//Save customData | |
customData.loginAttempts.push(loginAttempt); | |
customData.save(); | |
//Send notification email | |
mailer.sendEmailTemplate(account.email, 'loginAttemptEmail', loginAttempt); | |
}); | |
} | |
}); | |
} | |
}); | |
next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment