D
D
Danil2016-10-26 11:28:14
JavaScript
Danil, 2016-10-26 11:28:14

How to rewrite such a piece of code?

There is a piece of code that is repeated many times in different routes:

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

myRouter.get('/:query', function(req, res) {
     if (auth.isLogin(req, res)){
          //my code there
     }
})

How can I properly rewrite this so that I don't have to write an if every time?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2016-10-26
@Veneomin

Apparently, this is express. In this case, make a middleware that will have this check, and do a redirect or return a 401. Something like this:

var auth = require('../config/authenticate.js');
function authMiddleware(req, res, next) {
    if (!auth.isLogin(req, res)) {
        res.redirect('/login'); // или res.status(401).send('Залогиньтесь')
    } else {
        next(); // продолжаем обработку запроса
    }
}

myRouter.use(authMiddleware);

Checking rights is done in much the same way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question