(Passport.js)req.isAuthenticated()始终显示为false

时间:2019-03-23 09:33:46

标签: node.js passport.js

我是Passport.js用户,可以通过Facebook登录 我有一条称为专用的路由,其中​​用户必须先登录,如果他们登录了,它将允许用户输入,否则将重定向到登录页面。 但是,每次尝试时,它总是将我重定向到登录页面,而req.isAuthenticate始终显示为false。 希望你能帮我看看,谢谢很多

这是我的代码

server.get('/private',(req,res)=>{
  console.log(req.isAuthenticated())
  if (req.isAuthenticated()){
    res.send('welcome to private page')
  } else {
    res.redirect('/login')
  }
})

我的server.js

const next = require('next');
const routes = require('./routes');
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handler = routes.getRequestHandler(app);
const port = 3000 || process.env.port
// passport
const Passport = require('passport')
const passportface = require('passport-facebook').Strategy
const db = require('./db.js')
const bodyParser = require('body-parser')
const session = require('express-session')

// With express
const express = require('express');
app.prepare().then(() => {
  const server = express()
    server.use(bodyParser.urlencoded({extended: true}))
    server.use(session({secret: 'mysecret'}))
    server.use(Passport.initialize())
    server.use(Passport.session())
    server.get('/auth/fb', Passport.authenticate('facebook', {scope: ['email']}))
    server.get('/auth/fb/cb', Passport.authenticate('facebook',{
      failureRedirect:'/login',successRedirect:'/'
    }))
    server.get('/private',(req,res)=>{
      console.log(req.isAuthenticated())
      if (req.isAuthenticated()){
        res.send('welcome to private page')
      } else {
        res.redirect('/login')
      }
    })
    server.use(handler).listen(3000)
  console.log(`Sever is running on port ${port}`);
});

// Passport authenticate
Passport.use(new passportface(
  {
    clientID:'284388439125701',
    clientSecret:'843d03a61b1f4b78e4efcf729b72c83d',
    callbackURL:'http://localhost:3000/auth/fb/cb',
    profileFields: ['email','displayName']
  },
  (accessToken, refreshToken, profile,done)=>{
    console.log(profile)
    db.findOne({id: profile._json.id},(err,user)=>{
      if(err) return done(err)
      if (user) return done(null,user)
      const newUser = new db({
        id: profile._json.id,
        name: profile._json.name,
        email: profile._json.email
      })
      newUser.save((err)=>{
        return done(null,newUser)
      })
    })
  }
))

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

Passport.deserializeUser((id,done)=>{
  db.findOne({id:id},(err,user)=>{
    done(err, user)
  })
})

我的数据库

const mongoose = require('mongoose')
mongoose.Promise = global.Promise

mongoose.connect("mongodb://localhost/test")

const userSchema = new mongoose.Schema({
    id: String,
    name: String,
    email: String
})

const user = mongoose.model('user', userSchema, 'user')

module.exports = user 

0 个答案:

没有答案