Passport.js记得我的功能

时间:2015-10-09 11:07:35

标签: node.js express passport.js passport-local

https://github.com/jaredhanson/passport-remember-me

passport.use(new RememberMeStrategy(
  function(token, done) {
    Token.consume(token, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      return done(null, user);
    });
  },
  function(user, done) {
    var token = utils.generateToken(64);
    Token.save(token, { userId: user.id }, function(err) {
      if (err) { return done(err); }
      return done(null, token);
    });
  }
));

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res, next) {
    // issue a remember me cookie if the option was checked
    if (!req.body.remember_me) { return next(); }

    var token = utils.generateToken(64);
    Token.save(token, { userId: req.user.id }, function(err) {
      if (err) { return done(err); }
      res.cookie('remember_me', token, { path: '/', httpOnly: true, maxAge: 604800000 }); // 7 days
      return next();
    });
  },
  function(req, res) {
    res.redirect('/');
  });

我试图在我现有的应用程序中实现记住我的功能(上图),但我无法实现。当我将RememberMeStrategy添加到我的login.js中时,它会抛出

  

ReferenceError:未定义RememberMeStrategy

错误。这里缺少什么?

index.js

var rendering = require('../util/rendering');

var express = require('express');
var router = express.Router();

exports.home = function(req, res) {
    res.render('index/index');
};


exports.userHome = function(req, res) {
    res.render('index/user-home');
};

login.js

var crypto = require('crypto'),
    passport = require('passport'),
    passportRememberMe = require('passport-remember-me'),
    passportLocal = require('passport-local'),
    data = require('../models/auth')();

exports.registerPage = function (req, res) {
    res.render('login/register', {username: req.flash('username')});
};


exports.registerPost = function (req, res) {
    var vpw = req.body.vpw;
    var pwu = req.body.pw;
    var un = req.body.un;

    req.flash('username', un);

    if (vpw !== pwu) {
        req.flash('error', 'Your passwords did not match.');
        res.redirect('/register');
        return;
    }

    req.checkBody('un', 'Please enter a valid email.').notEmpty().isEmail();
    var errors = req.validationErrors();
    if (errors) {
        var msg = errors[0].msg;
        req.flash('error', msg);
        res.redirect('/register');
        return;
    }

    var new_salt = Math.round((new Date().valueOf() * Math.random())) + '';
    var pw = crypto.createHmac('sha1', new_salt).update(pwu).digest('hex');
    var created = new Date().toISOString().slice(0, 19).replace('T', ' ');

    new data.ApiUser({email: un, password: pw, salt: new_salt, created: created}).save().then(function (model) {
        passport.authenticate('local')(req, res, function () {
            res.redirect('/home');
        })
    }, function (err) {
        req.flash('error', 'Unable to create account.');
        res.redirect('/register');
    });
};


exports.loginPage = function (req, res) {
    res.render('login/index', {username: req.flash('username')});
};


exports.checkLogin = function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        if (err || !user) {
            req.flash('username', req.body.un);
            req.flash('error', info.message);
            return res.redirect('/login');
        }
        req.logIn(user, function (err) {
            if (err) {
                req.flash('error', info.message);
                return res.redirect('/login');
            }

            req.flash('success', 'Welcome!');
            return res.redirect('/home');
        });
    })(req, res, next);
};

exports.logout = function (req, res) {
    req.logout();
    req.flash('info', 'You are now logged out.');
    res.redirect('/login');
};

routes.js

var rendering = require('./util/rendering'),
    indexController = require('./controllers/index'),
    loginController = require('./controllers/login');

module.exports = function (app, passport) {

    // Home
    app.get('/', indexController.home);
    app.get('/home', ensureAuthenticated, indexController.userHome);


    // Auth
    app.get('/register', loginController.registerPage);
    app.post('/register', loginController.registerPost);
    app.get('/login', loginController.loginPage);
    app.post('/login', loginController.checkLogin);
    app.get('/logout', loginController.logout);

    // 'rendering' can be used to format api calls (if you have an api)
    // into either html or json depending on the 'Accept' request header
    app.get('/apitest', function(req, res) {
        rendering.render(req, res, {
            'data': {
                'test': {
                    'testsub': {
                        'str': 'testsub hello world'
                    },
                    'testsub2': 42
                },
                'test2': 'hello world'
            }
        });
    })


    // Auth Middleware
    function ensureAuthenticated(req, res, next) {
        if (req.isAuthenticated()) { return next(); }
        res.redirect('/login');
    }
}

server.js

var dbConfig;
try {
    // Look for dev conf for local development
    dbConfig = require('./config/db.dev.conf.js');
} catch(e) {
    try {
        // production conf?
        dbConfig = require('./config/db.conf.js');
    } catch(e) {
        console.log('Startup failed.  No db config file found.');
        return false;
    }
}


var knex = require('knex')({
        client: 'mysql',
        connection: dbConfig
    }), 
    express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    cookieSession = require('cookie-session'),
    serveStatic = require('serve-static'),
    expressValidator = require('express-validator'),
    flash = require('connect-flash'),
    swig = require('swig'),
    passport = require('passport'),
    passportRememberMe = require('passport-remember-me'),
    passportLocal = require('passport-local'),
    crypto = require('crypto'),
    Bookshelf = require('bookshelf'),
    messages = require('./util/messages');

var app = express();

Bookshelf.mysqlAuth = Bookshelf(knex);

app.use(cookieParser('halsisiHHh445JjO0'));
app.use(cookieSession({
    keys: ['key1', 'key2']
}));


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(expressValidator());
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('remember-me'));
app.use(flash());
app.use(serveStatic('./public'));
//app.use(express.favicon(__dirname + '/public/images/shortcut-icon.png'));
app.use(messages());

app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

require('./util/auth')(passport);
require('./routes')(app, passport);

app.listen(process.env.PORT || 3000);

console.log('Listening on port 3000');

2 个答案:

答案 0 :(得分:4)

该错误只是说您在调用之前未定义RememberMeStrategy函数(您使用new但在Javascript中只是调用了一个函数使用一个名为this的特殊变量。首先需要require模块,在这种情况下:

var RememberMeStrategy = require('passport-remember-me').Strategy;

答案 1 :(得分:0)

只需在变量RememberMeStrategy

中使用它
var RememberMeStrategy= require('passport-remember-me').Strategy;