node.js用护照登录

时间:2014-01-23 17:25:29

标签: javascript node.js express passport.js

我正在使用护照实施基本登录系统,但是当我使用正确的凭据登录时,我仍然收到此错误:

快车 500 TypeError:无法读取未定义的属性“passport”

但是,当我使用错误的凭据登录时,通过重定向回登录页面可以正常工作。救命?

app.js

 //dependencies
 var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('./auth');

var app = express();
server = require('http').createServer(app),
    io = require('socket.io').listen(server);
// all environments
app.use(passport.initialize());
app.use(passport.session());
....
app.use(app.router);
app.use(require('less-middleware')({src: path.join(__dirname, 'public')}));
 app.use(express.static(path.join(__dirname, 'public')));
 ......
 //routes

 app.get('/login', routes.login);
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/user'
}));

 app.get('/user', routes.user);

index.js

    exports.login = function(req, res) {
        res.render('login', {title: 'Log in'});
    };

     exports.user = function(req, res) {
   if (req.session.passport.user === undefined) {
        res.redirect('/login');
    } else {

       res.render('user', {title: 'Welcome!',
            user: req.user
        })
    }
    };

auth.js

     var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {
        if (username === 'admin' && password === 'lynda') {
            return done(null, {username: 'admin'});
        }

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

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

passport.deserializeUser(function(username, done) {
    done(null, {username: username});
});

module.exports = passport;

2 个答案:

答案 0 :(得分:5)

您错过了会话​​声明,因此req.session未定义

app.use( express.cookieParser() );
app.use(express.session({ secret: 'my secret', cookie: { maxAge : 1200000 } }));  

另外,你似乎在混淆要求:

var passport = require('./auth');

我会将其更改为:

var auth = require('./auth');

避免与护照库混淆

答案 1 :(得分:1)

你没有会话,所以你不能这样做(req.session.passport.user === undefined)......

您可能在登录后未设置会话