Node.js module.exports护照是对路线的认证

时间:2017-04-17 20:13:15

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

我想将文件中的每组路线分开。我需要在大多数路由中使用isAuthenticated来限制访问。当我将所有路由放在同一个文件中时,它可以工作。

当我在auth.js和order.js中使用module.exports = isAuthenticated时,我使用var auth = require('auth.js');当我转到http://localhost:3000/order路线时,我会收到'isAuthenticated is not defined'错误在auth.js中定义的只是按预期工作。

我正在使用Express.js中间件“Passport本地策略”(来自tutsplus的教程,并从here下载了github存储库)。

我的项目结构:

bin/www
models/auth/init.js
models/auth/user.js
models/auth/signup.js
models/auth/login.js
models/order.js
views/error.pug
views/index.pug
views/home.pug
views/layout.pug
views/order.pug
views/register.pug
routes/order.js 
routes/auth.js
public/stylesheets/style.css
app.js
db.js

./路由/ auth.js:

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


var isAuthenticated = function (req, res, next) {
    // if user is authenticated in the session, call the next() to call the next request handler 
    // Passport adds this method to request object. A middleware is allowed to add properties to
    // request and response objects
    if (req.isAuthenticated())
        return next();
    // if the user is not authenticated then redirect him to the login page
    res.redirect('/');
}

module.exports = isAuthenticated;

module.exports = function(passport){

    /* GET login page. */
    router.get('/', function(req, res) {
        // Display the Login page with any flash message, if any
        res.render('index', { message: req.flash('message') });
    });

    /* Handle Login POST */
    router.post('/login', passport.authenticate('login', {
        successRedirect: '/home',
        failureRedirect: '/',
        failureFlash : true  
    }));

    /* GET Registration Page */
    router.get('/signup', function(req, res){
        res.render('register',{message: req.flash('message')});
    });

    /* Handle Registration POST */
    router.post('/signup', passport.authenticate('signup', {
        successRedirect: '/home',
        failureRedirect: '/signup',
        failureFlash : true  
    }));

    /* GET Home Page */
    router.get('/home', isAuthenticated, function(req, res){
        res.render('home', { user: req.user });
    });


    /* Handle Logout */
    router.get('/signout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    return router;
}

./路由/ order.js:

var express = require('express');
var router = express.Router();
var order = require('../models/order');

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



module.exports = function(passport){

    router.get('/order', isAuthenticated, function(req, res){
    res.render('order');

    });

    router.post('/order', isAuthenticated, function(req, res)
    {
        var testorder = new order({
            orderid: '52363',
            productname: 'it works',
            quantity: 1337
        });
        testorder.save(function (err) {
            if (err) {console.log(err.stack);}    
            console.log('saving done...');
        });

            res.render('order', { product: req.body.productname });
    });

};

./ app.js

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var pug = require('pug');

var dbConfig = require('./db');
var mongoose = require('mongoose');
// Connect to DB
mongoose.connect(dbConfig.url);

var app = express();

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

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());

 // Using the flash middleware provided by connect-flash to store messages in session
 // and displaying in templates
var flash = require('connect-flash');
app.use(flash());

// Initialize Passport
var initPassport = require('./models/auth/init.js');
initPassport(passport);

var auth = require('./routes/auth')(passport);
var order = require('./routes/order');
app.use('/', auth);
app.use('/order', order);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

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

module.exports = app;

1 个答案:

答案 0 :(得分:2)

尝试auth.isAuntheticated(), 它应该这样工作。