Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse - why does user.getSessionToken() return undefined

I'm using cloud function to fetch user's sessionToken. The documentation says, this method only returns correct value when a user object is fetched with the master key. However, even if I use the master key, I still get the undefined result. What's wrong with my code?

Parse.Cloud.define("hello", function(request, response) {
    Parse.Cloud.useMasterKey();
    Parse.Promise.as().then(function(){
        var query = new Parse.Query(Parse.User);
        return query.first({useMasterKey:true});
    }).then(function(user){
        return user.fetch({useMasterKey:true});
    }).then(function(user){
        response.success(user.getSessionToken());
    });
});
like image 868
Henry H Miao Avatar asked Mar 21 '26 08:03

Henry H Miao


1 Answers

That won't work because the user is not logged in when you fetch him via cloud code. For getSessionToken to work you need to already have a logged in user. Because, otherwise how would CloudCode know which session of your user you want to get? (if he is logged in multiple devices) Also your code is returning the first user in the database, is that realy what you want?

Either way, you need to log the user in via cloud code and then return the session token. However I had some trouble doing that without the password (just by calling user.logIn(), it should work so give it a try) so the only solution I found was to change the password of the user and then log him in. Why do you need to fetch the user's session token? If you don't mind changing the user's password you can do something like:

var password; //create new random passowrd
query.first({useMasterKey: true}).then(function(user){
    user.set("password", password);
    return user.save();
}).then(function(user){
    return Parse.User.logIn(user.get("username"), password);
}).then(function(user){
    return user.getSessionToken();
});
like image 119
Felix Dumit Avatar answered Mar 22 '26 20:03

Felix Dumit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!