req.isAuthenticated()返回false并登录用户

时间:2017-07-19 18:19:30

标签: node.js express passport-local

我正在测试护照以识别用户是通过req.isAuthenticated()登录的,但即使用户登录后,req.isAuthenticated()也会返回false。有谁知道为什么会这样?

const request = require('supertest')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const expressSession = require('express-session')
const User = require('../src/models/User.js')


const mongoose = require('mongoose')
const url = "mongodb://user1:password1@ds155091.mlab.com:55091/redditmock"  
mongoose.connect(url)



//Configuring local authentication
passport.use(new LocalStrategy(
    (username, password, done) => {
        User.findOne({username: username}, (err, user) => {
            if (err) return done(err)
            if (!user) {
                return done(null, false, {message: 'Incorrect username.'});
            }
            if (user.password !== password) {
                return done(null, false, { message: 'Incorrect password.' })
            }
            return done(null, user)
        })
    }
))


//Configuring app to have sessions 
passport.serializeUser((user, done) => {
    done(null, user._id)
})
passport.deserializeUser((id, done) => {
    User.findById(id, function(err, user) {
    done(err, user)
  })
})



app.use(bodyParser())
app.use(expressSession({secret: 'aSecretKey'}))
app.use(passport.initialize())
app.use(passport.session())


app.post('/login', passport.authenticate('local'))
app.post('/api/insertComment', (req, res) => {
    console.log(req.isAuthenticated())
    res.end()
})



const server = app.listen(3000)


describe('Routes', () => {
    before(done => {   
        //Logging in the user
        request(server)
            .post('/api/login')
            .type('form')
            .send({username: 'srpalo'})
            .send({password: 'secretpassword'})
            .then((res) => {
                cookie = res.header['set-cookie'][0]
                done()
            })
    })     
    it('/api/insertComment', (done) => {
        request(server)
            .post('/api/insertComment')
            .set('Content-Type', 'application/json')
            .set('Set-Cookie', cookie)
            .then((req, res) => {
                done()
            })            
    })    
})

user.js的

const mongoose = require('mongoose')


const schema = new mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
}) 

module.exports = mongoose.model('User', schema)

0 个答案:

没有答案