node.js – passport.initialize()中间件未用于快速4.10的自定义回调

栏目: Node.js · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/29600759/passport-initialize-middleware-not-in-use-for-express-4-10-for-custom-callback

任何人都可以帮我这个.当我尝试连接到数据库中的用户时,我不断收到错误:passport.initialize()中间件未使用.异常案例工作正常(e.i密码/用户名不正确).

这是设置:

我正在使用的版本

// version
node --version v0.10.33
express@4.10.2
passport@0.2.1
passport-local@1.0.0

server.js代码在这里

// server.js
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');

//Our custom modules
var mysqlc = require('./modules/mysql_client');

// Our custom apps
var app = express();

//view engine setup
app.set('env', process.env.NODE_ENV);
console.log('Running as environment: ' + app.get('env'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(path.join(__dirname,'./public/favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/rootpath', express.static(path.join(__dirname,'./public')));

// use session/cookie for auth
app.use(cookieParser());
app.use(session({ 
    secret: 'clinksecret',  // TODO: STORE outside
    saveUninitialized: true,
    resave: true
}));

// use connect-flash for flash messages stored in session
app.use(flash());

var server = require('http').Server(app);
var io = require('socket.io')(server);

/**
 * Connect to all servers 1st
 * */

// mysqlc connection setup
var connPropMySqlC = {
        connectionLimit : 10,
        host            : config.settings.auth.clink.host,
        user            : config.settings.auth.clink['user'],
        password        : config.settings.auth.clink['password'],
        database        : config.settings.auth.clink.database
};
var mydbc = new mysqlc.MySqlClient(connPropMySqlC);
mydbc.connect(function (err) {
    if (err) {
        console.error('server-mdbc-connect-ERROR:', err);
        throw err;
    }
});

//authentication with session after connection to mydbc
var passport = require('./modules/auth')({mydbc:mydbc, io:io, app:app, passport:passport});
app.use(passport.initialize());
app.use(passport.session());

/*
 * routers
 * */
var testapp = require('./testapp/app')({mydbc:mydbc, io:io});
app.use('/testapp', testapp);

auth.js(所有护照配置)

// auth.js
/**
 * for user authentication using passport
 */
var LocalStrategy = require('passport-local').Strategy;
var bcrypt   = require('bcrypt-nodejs');

//Variables local to module
var io;
var mydbc;
var app;
var passport;

function validPassword(val, hash, callback) {
    return bcrypt.compare(val, hash, callback);
}

function exportModFunc(args) {
    /**
     * used to passing object across modules
     * @param {object} args: args = {mydbc, io} // where mydbc mysqlc.MySqlClient object
     * @return {object} passport
     */
    mydbc = args.mydbc; // update variable
    io = args.io;       // update variable
    app = args.app;    // update variable
    passport = args.passport;   // update variable

    // route middleware
    passport.use('local-login', new LocalStrategy({
        usernameField : 'formLogin_user',
        passwordField : 'formLogin_password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, username, password, done) {
        mydbc.getUser({'username':username}, function(err, user) {
            console.log('test-local-login', username, password, done, err, user)
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            // if the user is found but the password is wrong
            validPassword(password, user.password, function(err, res) {
                if (err)
                    return done(err);

                if (!res) {
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
                } else {
                    // all is well, return successful user
                    return done(null, user);
                }
            });
        });
    }));

    passport.serializeUser(function(user, done) {
        /**
         * each session will serialize to userid
         * http://passportjs.org/guide/configure/
         * @param {object} user: same as object as returned by mydbc.getUser()
         * @return {null} null
         */
        done(null, user.userid);
    });

    passport.deserializeUser(function(userid, done) {
        /**
         * each session will deserialize to user
         * http://passportjs.org/guide/configure/
         * @param {int} userid: same as mydbc.getUser().userid
         * @return {null} null
         */
        mydbc.getUser({'userid':userid}, function(err, user) {
            done(null, user);
        });
    });

    // route post request
    //// process the login form
    app.post('/authLogin/', function(req, res, next) {
        passport.authenticate('local-login', function(err, user, info) {
            if (err) { return next(err); }
            var errors = {};
            var loginMsg = req.flash('loginMessage');
            if (loginMsg.length !== 0 || (!user)) {
                errors.loginMsg = loginMsg;
                return res.json({
                    errors: errors
                });
            }
            console.log('test-authLogin-local-login', err, user, info);
            req.logIn(user, {failureFlash: true}, function(err) {
                if (err) { return next(err); }
                return res.redirect('/users/' + user.username);
            });
        })(req, res, next);
    });

    return passport;
};

module.exports = exportModFunc;
您应该在将护照添加到路由中间件之前初始化护照: http://passportjs.org/guide/configure/
app.use(passport.initialize());
app.use(passport.session());

//authentication with session after connection to mydbc
var passport = require('./modules/auth')({mydbc:mydbc, io:io, app:app, passport:passport});

您还在server.js中重新定义护照var,这是不必要的.

翻译自:https://stackoverflow.com/questions/29600759/passport-initialize-middleware-not-in-use-for-express-4-10-for-custom-callback


以上所述就是小编给大家介绍的《node.js – passport.initialize()中间件未用于快速4.10的自定义回调》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

文明之光

文明之光

吴军 / 人民邮电出版社 / 2014-12 / 177元

吴军博士从对人类文明产生了重大影响却在过去被忽略的历史故事里,选择了有意思的几十个片段特写,以人文和科技、经济结合的视角,有机地展现了一幅人类文明发展的宏大画卷。 《文明之光》系列大致按照从地球诞生到近现代的顺序讲述了人类文明进程的各个阶段,每个章节相对独立,全景式地展现了人类文明发展历程中的多样性。《文明之光》系列首册讲述从人类文明开始到近代大航海这一历史阶段,共八个专题。第二册讲述了从近......一起来看看 《文明之光》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具