Search code examples
javascriptnode.jsexpressparse-server

Parse Server login return a user, but req.user is undefined


I am trying to set up a simple authentification system with Parse Server:

app.js

...

app.get('/login', (req, res) => {
    res.render('login.ejs');
});

app.post('/login', (req, res) => {
    console.log('POST /login\t' + util.inspect(req.body));
    driver.login(req, (err, user) => {
        //Here, user is defined
        if(err) {
            res.redirect('/login');
        } else {
            res.redirect('/user');
        }
    });
});

...

driver.js:

...

function login(req, callback) {
    var username = req.body.username,
        password = req.body.password;
    Parse.User.logIn(username, password, {
        success: (user) => {
            callback();
        },
        error: (user, error) => {
            callback(JSON.stringify(error));
        }
    });
}

function isLoggedIn(req, callback) {
    console.log('isLoggedIn?');
    console.log(util.inspect(req.user)); //undefined
    if(req.user) {
        callback();
    } else {
        callback('Not logged in');
    }
}

...

When I access /login, I can login just fine, and get redirected to /user without any error, but on /user, which use isLoggedIn as a middleware, req.user is undefined.

I have seen others with the same problem when searching, but the post where either old (<2015), using another part of the JSSDK (react/browser), or just didn t get any answer.

I know I could use session, and recreate the user each time based on that, but it feels really hackish, is it really the supported way?


Solution

  • You have two routes to go, either have a REST-full server, which means users are not persistent between route calls, STATE-full and use sessions.

    Luckily there is a really good nodejs authentication middleware already build that will handle all this session managment. This is called passportJS. Documentation can be found here: http://passportjs.org/docs

    You can not only have authentication through local logins, but have support for authentication with google, facebook, github and many more. This is done through what are called Strategies. You use google-strategy for having google oauth, facebook-stradegy for facebook oauth, etc.

    What you would be looking for is a local-strategy, which is called this because you want to authenticate with local user credentials. This strategy can be found here: https://www.npmjs.com/package/passport-local

    you will need both passport and passport local and to install simply run

    npm install passport passport-local
    

    From there, just go through the documentation I have linked above for how to set everything up.