I'm trying to implement a login/sign-up system similar to StackOverflow's, which is to say:
- Both the sign up and login links go to /users/login,
- Users click on an OAuth provider (e.g. Google) regardless of whether they're signing up or logging in,
- The OAuth callback goes to /users/authenticate if the account doesn't yet exist (page to confirm account creation), OR goes to / if the account already exists.
- (I'm adding an administrator account verification step here if the account is new, but not too important for this question.)
I'm not sure I'm going about this correctly. Relevant code below.
See if the profile exists in the database; if not, return the in-memory profile with the status = "new":
passport.use(new GoogleStrategy({
clientID: config.google_client_id,
clientSecret: config.google_client_secret,
callbackURL: "/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
db.db.collection("users", function (err, collection) {
if (err) throw err;
collection.findOne({id: profile.id}, function (err, record) {
if (record) return done(null, record);
profile.status = "new";
done(null, profile);
});
});
});
})
);
Pick the redirect route after OAuth based on status:
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/users/login' }),
function (req, res) {
switch (req.user.status) {
case "validated":
res.redirect('/'); break;
case "new":
res.redirect('/users/oauthconfirm'); break;
case "pending":
res.redirect('/users/login'); break;
}
}
);
And finally, the route for confirming a new account:
// app.js
app.get('/users/oauthconfirm', routes.users.oauthconfirm);
// routes/users.js
exports.oauthconfirm = function(req, res) {
db.db.collection("users", function (err, collection) {
if (err) throw err;
collection.insert(req.user, function (err, records) {
if (err) throw err;
res.render('login', {messages: [{status: "success", text:"Thank you. You will receive an e-mail when your account is validated."}]});
});
});
};
What's the "correct" way to do this? I'm pretty sure my verify callback code is inappropriate. Thanks-