Automatically link 3rd party oauth if already signed up with email amd password

Hi everyone, I am new here and migrating my Flutter app from Firebase to Parse. I don’t know JS much :sweat_smile:. I have created couple of cloud code for my need with the help of documentation.
But I don’t know how can I automatically link oauth users with existing email/pass in first login.
I need some help regarding this. Any hint or snippet or suggestions are appreciated.

Would you mind to share what you’ve tried so far? It might be easier for someone to help.

Actually I don’t know anything about JS. I am searching for snippet or some information that can be useful. Sorry if is not ok. I have found this from documentation.

Parse.Cloud.beforeLogin(async request => {
    const { object: user } = request;

    // I don't know ...
    // how to get user info form request
    // how to get authdata
    // and nothing about JS    

    await user.linkWith(
        providerName,
        { authData: user.authData },
        { useMasterKey: true }
    );
});

I think first step is make sure oauth is working properly. Have you already set it up and it is working fine?

Yes oauth working properly. I am using Google to sign in. I want to transfer my user data to Parse from Firebase. To do so I need to create user in Parse and upload their data. So I am thinking of creating user with their email and random strong password and when they sign in with Google they will automatically link to their account.

And what currently happens if you try to sign up via google using an existing email account? Duplicated user error message?

1 Like

Yes exactly, email address already exists kind of error.

I’ve never tried that before, but I’d try to create a cloud code function which receives Google auth data and e-mail. This cloud code function could first check if the user exists (using master key). In the case it exists, you can use linkWith function to link the user to Google. It would be something like:

Parse.Cloud.define('googleSignIn', async ({ params: { email, id, access_token } }) => {
  const users = await new Parse.Query(Parse.User).equalTo({ email }).find({ useMasterKey: true });
  let user;
  if (users.length <= 0) {
    user = new Parse.User();
    user.set('email', email);
    user.set('username', username);
  } else {
    user = users[0];
  }
  const authData = { id, access_token };
  return user.linkWith('google', { authData });
});
1 Like

Thank you I will try this. Do I need to call this function or it is automatically triggered when login with Google using SDK? And another question how we are getting username inside if block?

Sorry for the code. It would be something like user.set('username', email);. You will have to call the function from the client code.

1 Like

No problem, many thanks for helping :blush: