我发布的代码是coffeescript。
http = require('http')
Url = require('url')
express = require('express')
bodyParser = require('body-parser')
paginate = require('express-paginate')
session = require('express-session')
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
cookieSession = require('cookie-session')
models = require(__dirname + '/database')
app = express()
app.use(paginate.middleware(10, 50));
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use session(
secret: 'keyboard cat'
proxy: true
resave: true
saveUninitialized: true)
app.use passport.initialize()
app.use passport.session()
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
models.User.findById id, (err, user) ->
done err, user
app.use (req, res, next) ->
res.setHeader 'Access-Control-Allow-Origin', '*'
res.setHeader 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'
res.setHeader 'Access-Control-Allow-Headers', 'X-Requested-With,content-type'
res.setHeader 'Access-Control-Allow-Credentials', true
next()
我的策略:
passport.use new LocalStrategy (username, password, done) ->
models.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.')
done null, user
app.post '/login', (req, res, next) ->
passport.authenticate('local', (err, user, info) ->
if err
return next(err)
req.logIn user, (err) ->
if err
return next(err)
res.send "200"
) req, res, next
app.listen 9998
当我尝试从其他路由访问req.user时,例如/current_user
,它是未定义的。
app.get '/login/current_user', (req, res) ->
console.log(req.user) // this is undefined
res.send req.user
我已经读过req.login()
应该做的伎俩,但事实并非如此。
req.user
和req.session
仅存在于/login
回调函数中。