当nodejs服务器重新启动时,passport js无法维护会话

时间:2016-06-01 07:12:09

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

我正在使用nodejs, passportjs, jwtoken and mongoose开发一个应用程序。我面临着一些危急情况,并且在2天后陷入困境。

我使用passport js进行服务器端身份验证,使用jwtoken进行持久登录。它运作良好,有正常情况。但是我在3天前遇到了一个问题,那就是当我重新启动服务器时,护照js无法维护会话或使nodejs用户会话失效。我不知道如何在nodejs中重新验证并重新创建新的护照会话。

我尝试了很多,但未能重新创建。当我尝试重新启动服务器并从Web应用程序发送到服务器的任何请求时,我发现了这个问题。当我尝试访问req.user以从会话中获取用户数据时,它会抛出req.user未定义。

我甚至尝试使用connect-mongo来存储会话,但它会引发错误 -

"Error: failed to deserialize user out of session"

我不知道如何应对这种情况。为我提供解决此问题的指南。

请参阅以下源代码。

  

config.js

var express = require("express");
var http = require("http");
var path = require("path");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var expressSession = require("express-session");
var methodOverride = require("method-override");
var morgan = require("morgan");
var passport = require("passport");
var randToken = require('rand-token');
var jwt = require("jsonwebtoken");
var mongoose = require("mongoose");
var app = express();

var useragent = require('express-useragent');
app.use(useragent.express());

require("./utils")(express, app, path);

require("./db");

app.set("port", process.env.PORT || 2000);
app.set("env", "development");

if (app.get("env") === 'production') {
    process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
    process.env['JWT_PRIVATE_KEY'] = **** ;
    process.env['COOKIE_PRIVATE_KEY'] = **** ;
    process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
    process.env['SECURE_COOKIES'] = true;
} else if (app.get('env') === 'staging') {
    process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
    process.env['JWT_PRIVATE_KEY'] = **** ;
    process.env['COOKIE_PRIVATE_KEY'] = **** ;
    process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
    process.env['SECURE_COOKIES'] = false;
} else if (app.get('env') === 'development') {
    process.env['RECAPTCHA_PRIVATE_KEY'] = **** ;
    process.env['JWT_PRIVATE_KEY'] = **** ;
    process.env['COOKIE_PRIVATE_KEY'] = **** ;
    process.env['JWT_TIME_OUT'] = 60 * 60 * 24 * 30 * 1000; // 30 days
    process.env['SECURE_COOKIES'] = false;
}

app.enable('trust proxy');

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

app.use(bodyParser.json());
app.use(cookieParser());

app.use(expressSession({
    secret: process.env.COOKIE_PRIVATE_KEY,
    name: 'hz-app',
    proxy: true,
    resave: true,
    saveUninitialized: true,
    httponly: true
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(methodOverride('X-HTTP-Method-Override'));

var router = express.Router();
var expressJWT = require("express-jwt");
var allowAccess = expressJWT({
    secret: process.env.JWT_PRIVATE_KEY,
    userProperty: 'payload'
}).unless({
    path: [
        '/api/user/register',
        '/api/user/useractivation',
        '/api/user/authenticate',
        '/api/user/checkEmail',
        '/api/user/checkNickName',
        '/api/user/resetPassword',
        '/api/user/addip',
        '/api/user/forgetPasswordRequest',
        '/api/user/logout',
        '/api/cms/getCms',
        '/adminapi/admin/authnticate',
        '/adminapi/admin/logout',
        '/adminapi/common/getLanguageList',
        '/api/common/getCurrencyList',
        '/adminapi/common/getUserType',
        '/api/newsSubscriber/create',
        //        '/api/newsSubcrib/create',
        //        '/adminapi/admin/userList',
        //        '/adminapi/admin/getUserType',
        //        '/adminapi/admin/userCreate',
        //        '/adminapi/admin/userEdit',

    ]
});

app.use(function(req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization');
    next();
});

app.all(["/api/*", "/adminapi/*"], allowAccess, function(req, res, next) {
    if (req.user) {
        console.log("log in authorize obj for check");
        console.log(JSON.stringify(req.user));
    } else {
        console.log("not authenticated (not log in)");
        //res.clearCookie('hz-token');
        //res.clearCookie('hz-token-admin');
    }

    var reqPath = req.path.split("/");
    console.log('../app/data/routes/' + reqPath[2]);
    app.use(require('../app/data/routes/' + reqPath[2]));
    next();
});

app.get("/", function(req, res) {
    //app.use(function (req, res) {
    res.sendFile(basePath + "app/client/views/index.html");
});

app.get("/admin", function(req, res) {
    res.sendFile(basePath + "app/admin/views/index.html");
});

//Development error handler will print stacktrace
if (app.get('env') === "development") {
    router.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

router.use(function(err, req, res, next) {
    res.status(err.status || 500);
});

http.createServer(app).listen(app.get('port'), function() {
    console.log('Epsilon is listening on port ' + app.get('port'));
});
exports = module.exports = app;
  

user.js的

var express = require('express');
var router = express.Router();
var Helper = require("../components/helper");
var bcrypt = require("bcryptjs");
var moment = require("moment");
var User = require('../models/user');
var passport = require("passport");
var localStrategy = require("passport-local"),
        Startegy;

router
        .route('/api/user/authenticate')
        .post(
                function (req, res, next) {
                    console.log(">> authentication process initiated");

                    passport.authenticate('user-local', function (err, user, info) {
                        if (err) {
                            return res.status(401).json({
                                status: 0,
                                code: 401,
                                type: "error",
                                message: err
                            });
                        }
                        if (!user) {
                            console.log("not user:");
                            console.log(user);
                            return res.status(401).json({
                                status: 0,
                                code: 401,
                                type: "error",
                                message: info
                            });
                        }
                        req.login(user, {}, function (err) {
                            if (err) {
                                return res.status(500).json({
                                    status: 0,
                                    code: 500,
                                    type: "other",
                                    err: 'could not login user'
                                });
                            }

                            NextProcessForGenerateWebToken();

                            var NextProcessForGenerateWebToken = function () {
                                if (err) {
                                    return next(err);
                                }
                                var _res = user.generateJWT(user);
                                res.cookie('hz-token', _res, {maxAge: process.env.JWT_TIME_OUT, httpOnly: false});
                                res.status(200).json({
                                    status: 1,
                                    type: "success",
                                    message: 'login successful',
                                    res: {
                                        link: user.link_id,
                                        nick_name: user.nick_name
                                    }
                                });
                            };
                        });
                    })(req, res, next);
                });


/**
 * Serialize user for passport authentication
 */
passport.serializeUser(function (user, done) {
    console.log("serialize:>>"+user.id);
    console.log(user);
    done(null, user.id);
});

/**
 * Deserialize user for passport authentication
 */
passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        console.log("deserialize:>>"+user.id);
        done(err, user);
    });
});

/**
 * Passport local authentication policy to validate email/username and passport
 */
passport.use('user-local', new localStrategy({
    usernameField: 'txtSigninEmail',
    passwordField: 'txtSigninPassword'
},
        function (username, password, done) {
            User.findOne({$or: [{email: username}, {nick_name: new RegExp('^' + username + '$', "i")}], user_type: 3, is_active: 1, is_close: 0}, function (err, user) {
                if (!user) {
                    return done(null, false, {message: 'Incorrect username.'});
                }

                user.comparePassword(password, function (err, isMatch) {
                    if (err)
                        throw err;
                    if (!isMatch) {
                        return done(null, false, {message: 'Incorrect password.'});
                    }
                    return done(null, user);
                });
            });
        }
));

module.exports = router;

0 个答案:

没有答案