4human-org / murphy-ecommerce-backend

Backend Repo for the Murphy E-Commerce App
2 stars 1 forks source link

Going from Authentication to Firestore Database (individual id’s for each user when they are created) #32

Closed kailahulse closed 5 months ago

Calesi19 commented 5 months ago

We are going to need to use Cloud Functions. We can have a serverless cloud function that triggers whenever the "onCreate" event happens when the user decides to create new account using firebase auth.

// from gpt
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.createUserDocument = functions.auth.user().onCreate((user) => {
  // user parameter contains the auth user details
  const uid = user.uid;
  const email = user.email; // Assuming the user registered with an email

  // Reference to Firestore to create a new document in the users collection
  const db = admin.firestore();
  const userRef = db.collection('users').doc(uid);

  return userRef.set({
    email: email,
    // Add other fields as necessary
  })
  .then(() => {
    console.log(`Successfully created user document for UID: ${uid}`);
    return null;
  })
  .catch(error => {
    console.error("Error creating user document:", error);
    throw new functions.https.HttpsError('unknown', 'Failed to create user document', error);
  });
});

There's also a firebase extension that does this same thing.

Image

Calesi19 commented 5 months ago

I installed the extension and it works as expected. It was an easy install. I tested it and it works perfectly.

Screenshot 2024-04-27 at 12 08 08 PM

The extension can be re-configured to allow for more fields.

Screenshot 2024-04-27 at 12 11 10 PM

When a new account is created, a new document is formed in the firestore database with the UID as the ID of the document.

Screenshot 2024-04-27 at 12 13 30 PM