Express Passport Google策略-使用res.redirect

时间:2018-08-21 20:28:35

标签: node.js express passport.js google-oauth

我有一个Express应用程序,该应用程序通过Passport管理身份验证,同时支持本地策略和Google策略。

目前,我支持通过Google身份验证创建帐户,但实际上用户的Google帐户并不包含我的应用程序所需的所有信息。因此,我想将没有本地帐户的用户重定向到我自己的帐户创建中,仅支持帐户链接(即,他们的本地帐户可以链接到Google帐户进行授权)。

问题是我通常会通过res.redirect来执行此操作,但是res在Google策略中不可用-处理此问题的最佳方法是什么?

在“ index.js”中,我定义了我的路线,定义了const passportGoogle = require('../handlers/google');,其中包含了我的Google策略的详细信息。

index.js的更下方,我有authenticateauthorise路线:

/* GOOGLE ROUTES FOR AUTHENTICATION*/

router.get('/google',
    passportGoogle.authenticate('google', 
    { scope: ['profile', 'email'] }));

router.get('/google/callback', 
    passportGoogle.authenticate('google', 
    {
        failureRedirect: '/',
        failureFlash: 'Failed Login!',
        successRedirect: '/account',
        successFlash: 'You are logged in!'

    }
));

/* GOOGLE ROUTES FOR AUTHORISATION - IE A USER IS ALREADY LOGGED IN AND WANTS TO CONNECT THEIR GOOGLE ACCOUNT*/

// send to google to do the authentication
router.get('/connect/google', 
    passportGoogle.authorize('google', 
    { scope : ['profile', 'email'] }
));

// the callback after google has authorized the user
router.get('/connect/google/callback',
    passportGoogle.authorize('google', {
        successRedirect : '/profile',
        failureRedirect : '/'
    })
);

如上所述,我的Google策略是在google.js中定义的:

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('../models/User');
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENTID,
    clientSecret: process.env.GOOGLE_CLIENTSECRET,
    callbackURL: "http://127.0.0.1:7777/google/callback",
    passReqToCallback: true
  },
  // google will send back the token and profile
function(req, accessToken, refreshToken, profile, done) {
    // asynchronous
    process.nextTick(function() {

        // check if the user is already logged in
        if (!req.user) {
            // find the user in the database based on their facebook id
            User.findOne({ 'google.id': profile.id }, function(err, user) {

                // if there is an error, stop everything and return that
                // ie an error connecting to the database
                if (err)
                    return done(err);

                // if the user is found, then log them in
                if (user) {
                    return done(null, user); // user found, return that user
                } else { <--here is where I want to redirect
                    //currently I create a new user but i really want to redirect them to create a local account
                    // if there is no user found with that google id, create them
                    var newUser            = new User();

                    // set all of the facebook information in our user model
                    newUser.google.id = profile.id;
                    newUser.google.token = token;
                    newUser.name = profile.displayName;
                    newUser.email = profile.emails[0].value;

                    // save our user to the database
                    newUser.save(function(err) {
                        if (err)
                            throw err;

                        // if successful, return the new user
                        return done(null, newUser);
                    });
                }

            });

        } else {
            const user = User.findOneAndUpdate(
                { _id: req.user._id },
                { $set: {"user.google.id":profile.id, 
                        "user.google.token":accessToken, 
                        "user.google.name":profile.displayName, 
                        "user.google.email":profile.emails[0].value
                    }
                },   
                { new: true, runValidators: true, context: 'query' }
            )
            .exec();
            return done(null, user);
            req.flash('success', 'Google details have been added to your account'); 
            res.redirect(`back`); 
        }
    });
}));

module.exports = passport;

任何帮助,不胜感激!

0 个答案:

没有答案