1. 程式人生 > >node + express 登錄攔截器

node + express 登錄攔截器

ret org app.js nco register 攔截 logger ror erro

攔截器可以根據需要 做權限攔截 登錄只是權限的一種,

思路是req.session.user判斷用戶session是否存在,是否是需要攔截的地址,

如果是就跳轉登錄頁,或其他頁,

如果非需攔截頁,則執行 next(); 放行

因為是順序執行的所以 app.all(‘/*‘, function(req, res, next){ 這個方法需放在定義的路由之上

具體寫法如下:

//登錄攔截器
app.all(‘/*‘, function(req, res, next){
  if (req.session.user) {
    next();
  }else {
    var
arr = req.url.split(‘/‘);// 解析用戶請求的路徑 for (var i = 0, length = arr.length; i < length; i++) {// 去除 GET 請求路徑上攜帶的參數 arr[i] = arr[i].split(‘?‘)[0]; } if (arr.length > 1 && arr[1] == ‘‘) {// 判斷請求路徑是否為根、登錄、註冊、登出,如果是不做攔截 next(); } else if (arr.length > 2 && arr[1] == ‘user‘ && (arr[2] == ‘register‘ || arr[2] == ‘login‘ || arr[2] == ‘logout‘ || arr[2].indexOf(‘login‘) > 0 )) { next(); }
else { // 登錄攔截 req.session.originalUrl = req.originalUrl ? req.originalUrl : null; // 記錄用戶原始請求路徑 req.flash(‘error‘, ‘請先登錄‘); res.redirect(‘/user/login‘); // 將用戶重定向到登錄頁面 } } });

結尾附上我的app.js:

var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘); var cookieParser = require(‘cookie-parser‘); var session = require(‘express-session‘); var bodyParser = require(‘body-parser‘); var hbs = require(‘hbs‘); var flash = require(‘connect-flash‘); var index = require(‘./routes/index‘); var users = require(‘./routes/users‘); var about = require(‘./routes/about‘); var list_ = require(‘./routes/product/list‘); var login = require(‘./routes/user/login‘); var login_post = require(‘./routes/user/login_post‘); var app = express(); app.use(cookieParser()); app.use(session({ secret: ‘123456‘, cookie: {maxAge: 60 * 1000 * 30}, resave: false, saveUninitialized: true })); app.use(flash()); hbs.registerPartials(path.join(__dirname, ‘views‘, ‘partials‘ )); // view engine setup app.set(‘views‘, path.join(__dirname, ‘views‘)); app.set(‘view engine‘, ‘hbs‘); var blocks = {}; hbs.registerHelper(‘extend‘, function(name, context) { var block = blocks[name]; if (!block) { block = blocks[name] = []; } block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this)); }); hbs.registerHelper(‘block‘, function(name) { var val = (blocks[name] || []).join(‘\n‘); // clear the block blocks[name] = []; return val; }); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, ‘public‘, ‘favicon.ico‘))); app.use(logger(‘dev‘)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, ‘public‘))); //登錄攔截器 app.all(‘/*‘, function(req, res, next){ if (req.session.user) { next(); }else { var arr = req.url.split(‘/‘);// 解析用戶請求的路徑 for (var i = 0, length = arr.length; i < length; i++) {// 去除 GET 請求路徑上攜帶的參數 arr[i] = arr[i].split(‘?‘)[0]; } if (arr.length > 1 && arr[1] == ‘‘) {// 判斷請求路徑是否為根、登錄、註冊、登出,如果是不做攔截 next(); } else if (arr.length > 2 && arr[1] == ‘user‘ && (arr[2] == ‘register‘ || arr[2] == ‘login‘ || arr[2] == ‘logout‘ || arr[2].indexOf(‘login‘) >= 0 )) { next(); } else { // 登錄攔截 req.session.originalUrl = req.originalUrl ? req.originalUrl : null; // 記錄用戶原始請求路徑 req.flash(‘error‘, ‘請先登錄‘); res.redirect(‘/user/login‘); // 將用戶重定向到登錄頁面 } } }); app.use(‘/‘, index); app.use(‘/users‘, users); app.use(‘/about‘, about); app.use(‘/product/list‘, list_); app.use(‘/user/login‘, login); app.use(‘/user/loginPost‘, login_post); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error(‘Not Found‘); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get(‘env‘) === ‘development‘ ? err : {}; // render the error page res.status(err.status || 500); res.render(‘error‘); }); module.exports = app;

node + express 登錄攔截器