parse-server icon indicating copy to clipboard operation
parse-server copied to clipboard

server-side login (replacing parse-express-cookie-session)

Open mchun opened this issue 10 years ago • 22 comments

My app was relying on 'parse-express-cookie-session' offered by Parse to do server-side login, i.e.:

  app.post('/login', function(req, res) {
    Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
      res.redirect('/');
    }, function(error) {
      res.render('login', { flash: error.message });
    });
  });

  app.post('/logout', function(req, res) {
    Parse.User.logOut();
    res.redirect('/');
  });

I used Parse.User.Current() to check if the user is logged in on server-side.

Now, I replaced the 'parse-express-cookie-session' by 'express-session'. And do the login/logout in this way:

  app.post('/login', function(req, res) {
    Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
      req.session.user=user;
      res.redirect('/');
    }, function(error) {
      res.render('login', { flash: error.message });
    });
  });

  app.post('/logout', function(req, res) {
    req.session.user = null;
    res.redirect('/');
  });

I then see if the user is logged in by checking req.session.user = null . But I cannot access it inside cloudcode. Perhaps this is not a right way to do(?) as it is recommended to use req.user, but I have no idea how to make it work, req.user is always null. Any help from you guys? It would be great to even have a small sample app offered by Parse showing simple server-side login like Anyimg as there should be similar cases around like me.

mchun avatar Feb 19 '16 02:02 mchun

or server-side login is no longer possible?

mchun avatar Feb 19 '16 08:02 mchun

What I did was to manually add the features of the parse-express-cookie-session. Below is one way of doing it. However I would change some things such as using Parse.Cloud.httpRequest instead of Parse._request and using secure cookies before going into production. An even better way would be to use jwt so that you don't have to send a login request on each page load. Would love to see an implementation of that.

// Login adds the sessionToken in a cookie
app.post('/login', function(req, res) {
    Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
        var val = JSON.stringify({sessionToken: user.getSessionToken()});
        var opts = {path: '/', httpOnly: true};
        res.cookie('parse.session', val, opts);
        res.redirect('/');
    }).then(null, function(error) {
        res.clearCookie('parse.session');
        res.render('pages/login', { flash: error.message });
    });
});
 // Middleware adding current user to `req.user` or redirecting to login if not logged in
app.use(function (req, res, next) {
    var cookie = null;
    new Parse.Promise.as().then(function() {
        cookie = JSON.parse(req.cookies['parse.session']);
        return Parse._request('GET', 'users/me', {}, {sessionToken: cookie.sessionToken});
    }).then(function (userData) {
        userData.sessionToken = cookie.sessionToken;
        req.user = Parse.Object.fromJSON(userData);
        next();
    }).then(null, function () {
        res.clearCookie('parse.session');
        return res.redirect('/login');
    });
});

simonbengtsson avatar Feb 19 '16 12:02 simonbengtsson

I see how you reconstruct the res.user, but in that case, the request.user still seems to be null in cloudcode afterSave trigger function.

Parse.Cloud.afterSave("Comment", function(request) {
   ...
};

I can get the userid by using request.object.get('createdBy').id inside the trigger function, but I guess its better to stick with request.user as these functions are shared across different clients. Any suggestions from Parse team?

mchun avatar Feb 19 '16 13:02 mchun

That is a separate issue as parse server is supposed to set the user in that case. Try updating to 2.1.1 as some related fixes was applied in #373. Also make sure you are not making the request with the master key and that you are using a valid session token. You won't get any warnings/errors if the session token is invalid.

simonbengtsson avatar Feb 19 '16 15:02 simonbengtsson

I tried your code and created a post request using $.post with request cookie : parse.session=%7B%22sessionToken%22%3A%22r%3A9f8ff4a551392d021759e81c58a3a8f8%22%7D

But the request.user is still undefined in aftersave trigger function. *I'm already using 2.1.1 parse-server

{ triggerName: 'afterSave',
  object: ParseObjectSubclass { className: 'Comment', _objCount: 152, id: 'sSGLWMDJRe' },
  master: false }

mchun avatar Feb 19 '16 18:02 mchun

The code I posted above is a way to replace the parse-express-cookie-session middleware and will only work with your server side code, i.e. your expressjs routes.

For your cloud code (cloud functions, afterSave, beforeSave etc) you need to make the request with the header X-Parse-Session-Token to get the req.user object. When you said $.post I assume you are using jQuery? Is it a reason you are not using the parse js sdk? Anyway, the request using jQuery and the rest api would look something like this:

$.post({
    url: 'http://localhost:1337/parse/classes/Comment',
    data: JSON.stringify({text: "New comment"}),
    headers: {
        'X-Parse-Application-Id': 'appId',
        'X-Parse-Session-Token': 'r:2bc226c69d8f23b6c4ed906d79a129d3',
        'Content-Type': 'application/json'
    }
});

and with the parse js sdk:

var comment = new Parse.Object('Comment');
comment.set('text', 'New comment');
comment.save(null, {sessionToken: "r:2bc226c69d8f23b6c4ed906d79a129d3");

simonbengtsson avatar Feb 20 '16 23:02 simonbengtsson

Hi Simon, thanks very much for your help. Yes, I am using jQuery on client side to minimize the dependency upon Parse JS SDK, but I am not using the rest api directly, i.e.

app.post('/c', requireUser, function(req, res){ var comment = new Comment(); comment.set("comment",req.body.comment); var post = new Post(); post.id = req.body.postID; comment.set("post",post); comment.set("createdBy",req.user); comment.save(null,{sessionToken:req.user.get('sessionToken')}).then(function(comment){ res.json({comment:comment, parseUser: req.user}); }, function(error){ console.log(error); res.json({error:error}) }); });

I have just added null,{sessionToken:req.user.get('sessionToken')} inside comment.save as above. It is now able to detect req.user inside trigger functions! Thanks to your answer!

mchun avatar Feb 21 '16 15:02 mchun

Glad to hear you solved it. What do you think of changing the title of this issue to Server-side login (replacing parse-express-cookie-session)? You should probably also close the issue.

simonbengtsson avatar Feb 21 '16 21:02 simonbengtsson

Thanks for helping @simonbengtsson!

drew-gross avatar Feb 22 '16 01:02 drew-gross

But what's the problem of using Parse._request instead of Parse.Cloud.httpRequest in production? I am facing difficulties to convert Parse._request to Parse.Cloud.httpRequest...

mchun avatar Feb 22 '16 03:02 mchun

Parse._request is not documented and might potensially be removed in a futute update to the sdk. Post here if you manage to do it, otherwise I will translate it at some point and update the answer.

simonbengtsson avatar Feb 22 '16 08:02 simonbengtsson

Seems Parse.Cloud.httpRequest can only be executed inside cloudcode? Otherwise, it always returns [TypeError: Cannot read property 'statusCode' of undefined] I also tried Parse.User.become(sessionToken) but with no success.

mchun avatar Feb 22 '16 11:02 mchun

Parse.Cloud.httpRequest should be available everywhere. What code are you using? Parse.User.become() is disabled for nodejs environments.

simonbengtsson avatar Feb 22 '16 19:02 simonbengtsson

Yup, it can be used everywhere. Figured out the code, need to use full path inside Parse.Cloud.httpRequest, appid and restapikey are also required. Middleware cookie-session is used to secure the cookie. I guess it should be good for production usage?

var cookieSession = require('cookie-session');

app.use(cookieSession({
  name: COOKIE_NAME,
  secret: "SECRET_SIGNING_KEY",
  maxAge: 15724800000
}));

app.use(function (req, res, next) {
    Parse.Cloud.httpRequest({
      url: 'http://localhost:1337/parse/users/me',
      headers: {
        'X-Parse-Application-Id': 'myAppId',
        'X-Parse-REST-API-Key': 'myRestAPIKey',
        'X-Parse-Session-Token': req.session.token
      }
    }).then(function (userData) {
        req.user = Parse.Object.fromJSON(userData.data);
        next();
    }).then(null, function () {
        return res.redirect('/login');
    });
});

In login / logout part:

  app.post('/login', function(req, res) {
    Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
      req.session.user = user;
      req.session.token = user.getSessionToken();
      res.redirect('/');
    }, function(error) {
      req.session = null;
      res.render('login', { flash: error.message });
    });
  });

  app.post('/logout', function(req, res) {
    req.session = null;
    res.redirect('/');
  });

mchun avatar Feb 29 '16 08:02 mchun

Might be a dumb question, but what is the "name" and "secret"? Do I just make those up? @mchun

mnearents avatar Mar 19 '16 21:03 mnearents

Name is the name of your cookie. Secret is the signing key. You may refer to the documentation here. https://www.npmjs.com/package/cookie-session And yes, they can be any string.

mchun avatar Mar 20 '16 02:03 mchun

So just to be totally clear, since I feel like we've covered a few things in this thread… @mchun, your most recent code (https://github.com/ParsePlatform/parse-server/issues/497#issuecomment-190107848) is what you're using for login/session management on the express side of your app?

woodardj avatar Jul 15 '16 02:07 woodardj

@woodardj , yes. That's my production code. But beware that I am still using parse-server 2.1.6 though I guess there's not much changed.

mchun avatar Jul 20 '16 10:07 mchun

Thanks @mchun! I ended up piecing the methodology into an authenticating middleware we already had, but this was super useful as a starting point. I am curious though, we had good luck querying _Session with the JS/Express SDK directly instead of going to the REST endpoint, is there a reason you went that route?

woodardj avatar Jul 23 '16 20:07 woodardj

@mchun I have a browser JS app. And an express server running parse on nodechef. I want to be able to sign the user in through the express route, and then ensure they are logged in with a session on the client. RIght now the client does the login. Your code you posted seems to do this? Can you offer any help. In the final code you post are you still using express session module? How are you then logging in the client, do you parse the session token down. Been looking everywhere for help code on this but can onlt find parts, parse session cookie module looks un-supported and can't find the docs. Would really appreciate some help. Thanks

tillifywebb avatar Aug 16 '16 16:08 tillifywebb