Невозможно выполнить вход в Google с помощью экспресс-отклонения. Ошибка: промежуточное ПО passport.initialize () не используется - PullRequest
0 голосов
/ 13 октября 2018

Я получаю это сообщение об ошибке при попытке использовать паспорт с Google:

Unhandled rejection Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn

Это функция Google внутри passport.js:

passport.use('google', new GoogleStrategy({
    clientID        : process.env.GOOGLE_CLIENTID,
    clientSecret    : process.env.GOOGLE_CLIENTSECRET,
    callbackURL     : process.env.GOOGLE_CALLBACKURL,
    passReqToCallback: true,
},
    function(req, token, refreshToken, profile, done) {


        process.nextTick(function() {

            console.log(profile);

            var values = { 
                where: { google_id: profile.id }, 
                defaults: {google_id: profile.id, name: profile.displayName} 
            };

            User.findOrCreate(values)
            .spread(function(user, created) {

                return done(null,user);
            });
        });
    }
));

Это полная ошибка:

Unhandled rejection Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn 
(/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport/lib/http/request.js:46:34)
    at Strategy.strategy.success (/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport/lib/middleware/authenticate.js:248:13)
    at verified (/Users/filipeferminiano/MEGA/altcoin-site/node_modules/passport-oauth2/lib/strategy.js:177:20)
    at /Users/filipeferminiano/MEGA/altcoin-site/config/passport.js:168:13
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
From previous event:
    at /Users/filipeferminiano/MEGA/altcoin-site/config/passport.js:166:6
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Как я могу это исправить?

1 Ответ

0 голосов
/ 13 октября 2018

app.js

var express=require('express');
var app=express();
var port=process.env.PORT || 3000;
var mongoose=require('mongoose');
var passport=require('passport');
var session = require('express-session');


mongoose.connect('mongodb://localhost:27017/myapp');
require('./config/passport')(passport);
var User = require('./models/user');

app.set('view engine', 'ejs'); 
app.use(session({ secret: '1234567' ,
       saveUninitialized: true,
       resave: true})); 
app.use(passport.initialize());
app.use(passport.session()); 

  app.get('/', function(req, res) {
        res.render('index.ejs'); 
    });

app.get('/profile/:provider', isLoggedIn, function(req, res) {
console.log(req.user);
    res.render('profile.ejs', {
        provider:req.params.provider,
        user : req.user // get the user out of session and pass to template
    });
});

app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));


     app.get('/auth/google/callback',
                passport.authenticate('google', {
                        successRedirect : '/profile/google',
                        failureRedirect : '/'
                }));


   // route for logging out
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });


// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

app.listen(port);

passport.js

var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

var User       = require('../models/user');

module.exports = function(passport) {

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });



  passport.use(new GoogleStrategy({

        clientID        : 'clientID',
        clientSecret    : 'clientSecret',
        callbackURL     : 'http://localhost:3000/auth/google/callback',

    },
    function(token, refreshToken, profile, done) {
    process.nextTick(function() {
             User.findOne({ 'google.id' : profile.id }, function(err, user) {
                if (err)
                    return done(err);
                if (user) {
              return done(null, user);
                } else {
                    var newUser          = new User();
                    newUser.google.id    = profile.id;
                    newUser.google.token = token;
                    newUser.google.name  = profile.displayName;
                    newUser.google.email = profile.emails[0].value; // pull the first email

                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });

    }));



};
...