Question

Hi Guys I'm learning node.js with expressjs framework. Now I want create a simple site with two page(login page and logged page). With this exercise my main goal is to authorized only the logged user to see the logged page.
I want prevent that a user not registered can see the logged page using www.mysite.com/logged
So in app.js I have added this

app.get('/logged', routes.logged);

Then in index.js(that it's located in ./routes folder) I have wrote this

exports.logged = function(req, res) {
if(req.session.isLogged) {
        res.status(200);
        res.render('logged', {Title: req.session.name});
} else {
    res.status(403);
    res.render('403');
}
}

But when I try to access to the logged page via www.example.com/logged I always get 500 Error Internal server error
The error that I receive is this:

Express
500 Error: Failed to lookup view "TypeError: Cannot read property 'commonUserId' of undefined" in views directory "C:\Users\Fabio\Desktop\SitoStatistica\views"
at Function.app.render (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\response.js:798:7)
at Object.handle (C:\Users\Fabio\Desktop\SitoStatistica\app.js:32:6)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:188:17)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:190:11)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:190:11)
at pass (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:110:24)
at nextRoute (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:100:7)
at callbacks (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:167:11)
at callbacks (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:170:9)

@pero

Was it helpful?

Solution

Implementing your own authentication system is not a good ideal.

For NodeJS authentication, you should take a look at PassportJS

Authentication then turn out to be very simple:

app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                failureRedirect: '/login' }));

then

app.get('/logged', function (req, res, next) {
    if (req.isAuthenticated()) {
        return res.redirect('/login');
    }
    return res.render('login');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top