Node.js - middleware res.redirect problem

I am trying to use authenticateUser () middleware before loading all of my pages. Instead of including it in every call (as in app.get ('/', authenticateUser, function () ...)), I tried to configure it with app.use (authenticateUser) right before calling app.use ( app.router).

However, this did not work. authenticateUser is basically:

if (req.session.loginFailed) { next() else { if (req.session.user_id) { ... if (userAuthenticated) { next(); } else { req.session.loginFailed = true; console.log('setting loginFailed to true'); res.redirect('/login'); } } } 

And then in app.get ('/ login') I set req.session.loginFailed as false,

This should work, but I only want to call it app.get () or app.post (), etc. for one of my actual pages. I think its call is called many times for many different requests (because when loading one page, "setting loginFailed to true" is called many times)

Is there a better way to do this? Or should I just call it before every page on my site?

+6
source share
1 answer

You do too many checks there, in my opinion. Only one route should process the user's login (check for the user and transfer it and save the username in the session, if it succeeded), and you should assign auth middleware only on routes that require authorization (not all).

I gave a simplified example so that you can understand my point:

Entry route

 app.post('/login', function (req, res) { var variables_set = (req.body.user && req.body.pass); if (variables_set && (req.body.user === 'username') && (req.body.pass === 'password')) { req.session.username = req.body.user; } else { res.redirect('/login?failed=true'); } }); 

Middleware

 if (!req.session.username) { res.redirect('/login'); } else { next(); } 

In the Alex Young Nodepad application you can see a more complete example: https://github.com/alexyoung/nodepad (tutorials for this application are here: http://dailyjs.com/tags.html#lmawa )

+9
source

Source: https://habr.com/ru/post/905087/


All Articles