简体   繁体   中英

Register user in backend before authenticating with firebase google sign in

How to register user in backend before authenticating with firebase google sign in?

Here is what I am trying to achieve.

  1. User clicks "sign in with google"
  2. User logs in with google account
  3. Popup is closed and user sees a loading screen while a request is sent to backend to register the user with the provided email
  4. If response is ok the user is authenticated and signed in

My issue is that after user logs in the popup, he is immediately signed in by firebase with a session. I am trying to not sign in the user after filling the popup until the request to backend is returned successfully.

Here is the code I am working with:

 async function GoogleSignIn() {
        const result = firebase.auth().signInWithPopup(provider, { updateCurrentUser: false })

        // The signed-in user info.
        const email = result.email

        const response = await fetch(`${API_URL}/api/account/register/`, {
            method: "POST",
            headers: {
                "Content-type": "application/json",
            },
            body: JSON.stringify(email),
        });
    }

You can use firebase blocking functions which will allow you to perform some functions before either creating or signing in a user.

NB// To use blocking functions, you will need to upgrade to firebase identity platform

Check the code below.

const functions = require('firebase-functions');

//before creating a user
exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => {
  const email = user.email;

  try {
    const response = await fetch(`${API_URL}/api/account/register/`, {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(email),
    });
    return response;
  } catch () {
    throw new functions.auth.HttpsError('failed-precondition');
  }
});

//before signing in a user
exports.beforeSignIn = functions.auth.user().beforeSignIn((user, context) => {
  const email = user.email;

  try {
    const response = await fetch(`${API_URL}/api/account/register/`, {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(email),
    });
    return response;
  } catch () {
    throw new functions.auth.HttpsError('failed-precondition');
  }
});

Also check out the firebase documentation for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM