app.get(“/ api / current_user”..在passport.js认证后没有解雇.NODE

时间:2017-11-16 12:42:35

标签: javascript node.js passport.js

我是NodeJS的新手。我正在尝试创建一个简单的Web服务器。 我现在只使用NodeJS和Passport.js(使用谷歌策略)。

目前,当我未经过身份验证时,所有app.get(“”)调用都在工作,但是一旦我使用google进行身份验证并且回调发生,我就无法再访问任何app.get路由了。我尝试在箭头函数中设置一个断点,它永远不会调用,只是在使用auth cookie从浏览器加载时挂起。

这是我目前的代码:

Index.js

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require("cookie-session");
const passport = require("passport");
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,   //30 days
        keys: [keys.cookieKey]
    })
);

app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

authRoutes.js

   const passport = require('passport');

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

    app.get(
        '/auth/google/callback',
        passport.authenticate('google')
    );

    app.get("/api/logout", (req, res) => {
        req.logout();
        res.send(req.user);
    });

    app.get("/api/current_user", (req, res) => {
            res.send("test");//req.user);   //Tried as a test, is called when    
                                           //not authenticated, but does not get 
                                          //called when authenticated
    });
   }

passport.js

const passport = require('passport');
const googleStrategy = require('passport-google-oauth20');
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model("users");

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

passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});

passport.use(new googleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleclientSecret,
    callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
        User.findOne({ googleId: profile.id })
        .then((existingUser) => {
            if (existingUser){
                //we already have a user
                done(null, existingUser);
            }
            else{
                new User({ googleId: profile.id })
                .save()
                .then (user => done(null, user));                
            }
        });
    })
);

1 个答案:

答案 0 :(得分:1)

除了事实之外,这可能不会帮助任何人检查TYPOS!

我在这里发现了我的问题:

passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});

注意事项应该完成

我没有收到任何帮助我的错误信息。