NodeJS-Express-会话-重定向到安全页面

时间:2019-05-03 11:51:07

标签: javascript node.js express authentication express-session

我正在尝试为我创建的网页设置一个“后端”。因此,只有在用户登录后才能访问某些页面。我已经为此建立了基本功能,并且可以对用户是否登录进行简单的验证。但是重定向到页面是我遇到的困难。

示例:

var auth = function(req,res,next){
    if (req.session.loggedin){
        return next();
    } else{
        return res.sendStatus(401);
    }
};

app.get('/list-video', auth, function (req, res) {
    res.redirect('/list-video');
});

所以我的问题是'/ list-video'是我要保护的页面,并且只有在用户成功登录后才可以访问。但是在验证之后,我将重定向到同一页面:'/ list-video视频'。这似乎不起作用,因为我显然陷入了循环。我已经尝试过重定向到另一个页面,例如“ / list-audio”,这当然可以正常工作。

有人可以建议这样做的方式吗?我是否需要创建一个可以重定向到的单独链接? (我确实想防止用户通过在浏览器中键入URL来手动转到该链接。)

任何帮助或建议将不胜感激!

我完整的app.js代码:

const express = require('express');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const session = require('express-session');

const { getHomePage } = require('./routes/index');

const { getBackendPage } = require('./routes/backend');
const { getVideoPage, listVideoPage, editVideoPage, editVideo, deleteVideo, addVideoPage, addVideo } = require('./routes/video');
const { getEbookPage } = require('./routes/ebook');
const { getMusicPage } = require('./routes/music');
const { getGamePage } = require('./routes/game');
const { getShopPage } = require('./routes/shop');

const port = 5000;


const db = mysql.createConnection({
    host: '127.0.0.1',
    user: 'user',
    password: 'bla',
    database: 'test'
    
    db.connect((err) => {
    if (err) {
        throw err;
    }
    console.log('Connected to database');
});
global.db = db;

// configure middleware
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.use(fileUpload()); // configure fileupload
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
    
    
/ passenger views
app.get('/', getHomePage);
app.get('/backend', getBackendPage);
app.get('/video', getVideoPage);
app.get('/ebook', getEbookPage);
app.get('/music/:id', getMusicPage);
app.get('/game', getGamePage);
app.get('/shop', getShopPage);

// backend views video
app.get('/edit-video/:id', editVideoPage);
app.post('/edit-video/:id', editVideo);
app.get('/add-video', addVideoPage);
app.post('/add-video', addVideo);
app.get('/delete-video/:id', deleteVideo);


// login screen
app.post('/auth', function (request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        db.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function (error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('/');
            } else {
                response.send('Incorrect Username and/or Password!');
            }
            response.end();
        });
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
});

var auth = function(req,res,next){
    if (req.session.loggedin){
        return next();
    } else{
        return res.sendStatus(401);
    }
};

app.get('/list-video', auth, function (req, res) {
    res.redirect('/list-video');
});

  app.listen(port, () => {
    console.log(`Server running on port: http://localhost:${port}`);
});  

2 个答案:

答案 0 :(得分:0)

将受保护的页面移动到其他目录(公共静态文件所在的文件夹之外),并在身份验证中间件之后提供express.static,如下所示:

app.use('/', express.static(path.join(__dirname, 'public'))); //notice I have no auth middleware
app.use('/mysecretpages', auth, express.static(path.join(__dirname, 'secret'))); //notice I DO have auth middleware

答案 1 :(得分:0)

将其更改为:

var auth = function(req,res,next){
    if (!req.session.loggedin){
        return res.redirect("/login");
    } else{
        return next();
    }
};

app.get('/list-video', auth);

这样,如果用户未通过身份验证,您将重定向到登录页面,如果已通过身份验证,则继续。