PassportJS与ExpressJS的多租户

时间:2018-07-24 15:42:10

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

我试图实现一个解决方案,其中有一个ExpressJS应用程序和两个供用户使用的Mongoose模型,一个供标准用户使用,另一个供管理员使用。我正在为用户模型使用passport-local-mongoose。但是,我遇到了一个问题,即身份验证可以成功,但用户不会停留在会话中(req.user是不确定的)。我认为使用一个ExpressJS应用程序使用两种Passport Local策略会有冲突。我一直在寻找示例,但没有任何效果。请在下面查看我的代码:

index.js

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const Passport = require('passport').Passport,
    appPass = new Passport(),
    adminPass = new Passport();
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const path = require('path');
const keys = require('./config/keys');
require('./models/User');
require('./models/AdminUser');
require('./models/EM');

mongoose.Promise = global.Promise;

mongoose
    .connect(keys.mongoURI)
    .then(() => console.log('DB connection successful'))
    .catch(err => console.error(err));

// Create new instances of express
const app = express();
const adminApp = express();

// View engine setup
adminApp.set('views', path.join(__dirname, 'views/admin'));
adminApp.set('view engine', 'pug');

// Tell express to use the body-parser middleware and to not parse extended bodies
adminApp.use(bodyParser.urlencoded({ extended: true }));
adminApp.use(bodyParser.json());

const AdminUser = mongoose.model('AdminUser');

adminPass.use(AdminUser.createStrategy());
adminPass.serializeUser(AdminUser.serializeUser());
adminPass.deserializeUser(AdminUser.deserializeUser());

adminApp.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.adminCookieKey]
    })
);

adminApp.use(adminPass.initialize());
adminApp.use(adminPass.session());

adminApp.use(express.static('public'));

require('./routes/adminRoutes')(adminApp);

adminApp.listen(5001, function(err) {
    if (err) {
        console.log(err);
    }
    console.log('Admin server started on port 5001');
});

// app.use(cors());

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Tell express to use the body-parser middleware and to not parse extended bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const User = mongoose.model('User');

appPass.use(User.createStrategy());
appPass.serializeUser(User.serializeUser());
appPass.deserializeUser(User.deserializeUser());

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey]
    })
);

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

app.use(express.static('public'));

require('./routes/authRoutes')(app);
require('./routes/portalRoutes')(app);
require('./routes/apiRoutes')(app);

if (process.env.NODE_ENV === 'production') {
    // Express will serve up production assets
    // like our main.js file, or main.css file!
    app.use(express.static('client/build'));

    // Express will serve up the index.html file
    // if it doesn't recognize the route

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
}

const PORT = process.env.PORT || 5000;
app.listen(PORT, function(err) {
    if (err) {
        console.log(err);
    }
    console.log('Server started on port 5000');
});

module.exports = {
    adminPass: adminPass,
    appPass: appPass
};

adminRoutes.js

var Index = require('../index');
var admin = require('../controllers/AdminController.js');

module.exports = app => {
    // route to admin dashboard page
    app.get('/adminDB', admin.adminDB);

    // route to admin login page
    app.get('/adminLogin', admin.adminLogin);

    // route for admin login action
    app.post(
        '/adminLogin',
        Index.adminPass.authenticate('local'),
        admin.adminDoLogin
    );

    // route for admin logout action
    app.get('/adminLogout', admin.adminLogout);
};

运行此命令时,出现错误,提示无法在authenticate上调用undefined。也许我走了走这条路的适当解决方案还差得远,但是我不知道如何使用以前的方法来解决req.user问题。有没有人知道如何实现多租户,理想情况下仅使用一个ExpressJS应用程序即可实现?

0 个答案:

没有答案