Last active
August 24, 2016 21:30
-
-
Save passatgt/feaac963a8f9b0f99504c8bf04c64c48 to your computer and use it in GitHub Desktop.
Send en email to a user with Stormpath Express on new login attempt
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
const async = require('async'); | |
const parser = require('ua-parser-js'); | |
function checkMultipleLogin(account, req, res) { | |
var sendemail = true; | |
var uagent = req.headers['user-agent']; | |
var ua = parser(uagent); | |
var ip = req.headers['x-forwarded-for'] || | |
req.connection.remoteAddress || | |
req.socket.remoteAddress || | |
req.connection.socket.remoteAddress; | |
//Setup sessions custom data, if not exists yet | |
if(!account.customData.sessions) { | |
account.customData.sessions = []; | |
//In this case we don't need to send an email | |
sendemail = false; | |
} | |
//Log current session | |
var currentSession = { | |
ip: ip, | |
browser: ua.browser.name, | |
os: ua.os.name, | |
device_model: ua.device.model, | |
device_vendor: ua.device.vendor | |
} | |
//If a session like this exists, we don't need to log and send an email | |
var sessionFound = false; | |
async.forEachOf(account.customData.sessions, function (session, key, callback) { | |
//Check if this session was used previously. If so, we don't need to log it, just update the time | |
if(session.ip == currentSession.ip && session.browser == currentSession.browser && session.os == currentSession.os && session.device_model == currentSession.device_model) { | |
sessionFound = true; | |
session.time = Date.now(); | |
} | |
callback(); | |
}, function (err) { | |
//If no existing sessions found, log it and send an email to inform user | |
if(!sessionFound && sendemail) { | |
//Save custom data | |
currentSession.time = Date.now(); | |
account.customData.sessions.push(currentSession); | |
//Send email notification | |
var device = 'Unknown device'; | |
if(ua.device.model && ua.device.vendor) { | |
device = currentSession.device_vendor + ' ' +currentSession.device_model; | |
} else if(ua.browser.name && ua.os.name) { | |
device = ua.browser.name +' on '+ ua.os.name; | |
} | |
mailer.sendEmailTemplate(account.email,'login',{name: account.givenName, time: new Date().toISOString(), device: device}); | |
console.log('email'); | |
} | |
//Save custom data | |
account.customData.save(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment