Closed simevidas closed 10 years ago
Alright, I've added an example that shows off how to use the custom verifyResponse and logoutResponse options. I did it slightly different from your example, in the case that you might want to allow a user to remain logged in while still not having access to something.
Cool :)
Just for fun, here is the code I use on my site:
var audience = env === 'production' ? 'http://mysite.com:80' : 'http://localhost:3000';
function clearSession(req) {
req.session.email = null;
req.session.active = null;
}
// Mozilla Persona
require('express-persona')(app, {
audience: audience,
verifyResponse: function (err, req, res, email) {
if (err) {
// if Persona threw an error, just pass it through to the browser
res.json({ status: 'failure', reason: 'Persona error: ' + err });
} else if (email === admin) {
// admin email is not in db
res.json({ status: 'admin', name: 'ADMIN' });
} else {
// check if email is in users db and if active field === true
db.users.findOne({ email2: email }, { name: 1, active: 1, _id: 0 }, function (err, doc) {
if (doc) {
if (doc.active) {
req.session.active = true;
res.json({ status: 'active', name: doc.name });
} else {
req.session.active = false;
res.json({ status: 'inactive', name: doc.name });
}
} else {
clearSession(req);
res.json({ status: 'failure', reason: 'The email was not found in "users" database.' });
}
});
}
},
logoutResponse: function (err, req, res) {
if (err) {
// if Persona threw an error, just pass it through to the browser
res.json({ status: 'failure', reason: 'Persona error: ' + err });
} else {
clearSession(req);
res.json({ status: 'ok', message: 'User has been logged out.' });
}
}
});
Great, glad you were able to use this!
I've copy-pasted (and changed appropriately) all the code provided in the "Quick start" section. I've tested my app in production and it works. (I've used my Gmail address for testing.)
Now, from what I see, all valid emails are successfully logged in. So, if a visitor can verify his email address with Persona, they will be logged in to my app. However, I would like to restrict login only to users from my database. (My app uses a MongoDB database which contains a "users" collection.) So, if a visitor tries to log in, I would like to check if their email address is present in my database, and only then log them in.
Could you provide code examples showing how this is performed? I'm assuming I have to provide
verifyResponse
/logoutResponse
callbacks and within them I can run my custom code.Update: I'm guessing here but is this how it's done?