How to use the _linkWith method on an existing user? (Parse Server)

1.1k Views Asked by At

I'm trying to authorize a user through facebook, for this I use the _linkWith method.

I can use the _linkWith method on a new user. For example, this code works:

//I get the data with Facebook SDK
var data = {
  authData: {
    id: <user_id>,
    access_token: <user_access_token>
  }
};

const user = new Parse.User();
user._linkWith('facebook', { authData: data.authData })
  .then(user => {
    //Make something with the user
  })
  .catch(error => console.log(error));

But I want to give the user the opportunity to first register by email and password, and then log in via facebook, or, conversely, first register via facebook, and then login by email and password. But I can not use the _linkWith method on an existing user. This code does not work:

const randomstring = require('randomstring');

//I get the data with Facebook SDK
var data = {
  email: <user_email>,
  authData: {
    id: <user_id>,
    access_token: <user_access_token>
  }
};

const query = new Parse.Query(Parse.User);
query.equalTo('email', data.email);
query.first({ useMasterKey: true })
  .then(async user => {
    if (!user) {
      user = new Parse.User();
      user.set('password', randomstring.generate());
      user.set('username', data.email);
      user.set('email', data.email);
      user = await user.signUp(null);
    }
    user._linkWith('facebook', { authData: data.authData })
      .then(user => {
        //Make something with the user
      })
      .catch(error => console.log(error));
  })
  .catch(error => console.log(error));

When I run this code, I get the error "Can not modify user 8BNz8oMty7".

My questions:

  1. Is it possible to use the _linkWith method on an existing user, as in the example above?
  2. If yes, how?
  3. If not, how can I authorize a user through facebook using Parse Server? In the end, I want to get a user with sessionToken.
2

There are 2 best solutions below

0
On

To answer you:

  1. Yes, you can only use it on an existing user, but make sure the user is login on his Parse account to be able to do it.

  2. You need to use the linkWith instead of _linkWith as _linkWith has been depreciated.* Moreover you need to use the sessionToken of the user, to be authorised to edit it, as follow:

`

userLoggedIn.linkWith("facebook", {authData: facebookAuthData},{ sessionToken: userLoggedIn.get("sessionToken") })

You can find a complete code example here: https://stackoverflow.com/a/38718115/3562050

*linkWith documentation links :

0
On

A MasterKey / SessionToken options have been added in the Latest Version of the JS SDK and Parse Server