简体   繁体   中英

Node.JS authorization

I want to create a simple application with auth system. When someone visits my page server must return authorization html page, than visitor can fill the inputs and send login and password through socket.io to server. And if the values are correct, server sends second html page to client. I know that I can use this code and redirect on client side:

app.get('/page1', function(req, res){
    res.sendFile(__dirname + '/page1.html');
});
app.get('/page2', function(req, res){
    res.sendFile(__dirname + '/page2.html');
});

But I want users to always stay on the same address, it must always be example.com/

You can use express middleware for authentication.

function authCheck(req,res,next){
    //Your auth check will be here
    if(isValidUser){
       next();
    }
    else{
      res.sendFile(__dirname + '/login.html');
    }
}

app.get('/afterlogin', authCheck, function(req, res){
    res.sendFile(__dirname + '/afterlogin.html');
});

You can use Passport for authentication provider.

Then you can register some authentication middleware like so:

// auth.js

module.exports = {
    isGuest: (req, res, next) => {
        if (req.isAuthenticated()) {
            res.redirect('/');
        } else {
            next();
        }
    },
    isAuthenticated: (req, res, next) => {
        if (req.isAuthenticated()) {
            next()
        } else {
            res.redirect('/users/login')
        }
    },
};

Then you can apply the middleware on your routes like so:

// users.js

let express = require('express'),
    router = express.Router(),
    usersController = require('../controllers/usersController'),
    auth = require('../middlewares/auth');

router.get('/register', auth.isGuest, (req, res) => {
    usersController.showRegisterPage(req, res);
});

router.post('/register', auth.isGuest, (req, res) => {
    usersController.register(req, res);
});

router.get('/login', auth.isGuest, (req, res) => {
    usersController.showLoginPage(req, res);
});

router.post('/login', auth.isGuest, (req, res) => {
    usersController.login(req, res);
});

router.post('/logout', (req, res) => {
    usersController.logout(req, res);
});

router.get('/profile/:username', auth.isAuthenticated, (req, res) => {
    usersController.showProfilePage(req, res);
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM