Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I link auth users to collection in Firestore?

I'm trying to connect a user to the user collection in firestore. I'm using cloud functions, but I don't think I'm implementing it correctly.

firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(() => {
        console.log('user created')
        exports.createUserDoc = functions.auth.user().onCreate((user) => {
            console.log("hi")
            const userId = user.uid;

            const account = {
                posts: []
            }
            return admin.firestore().collection("Users").doc(userId).add(account)
        })

But my console.log(hi) isn't showing up. Am I approaching this correctly? Any advice helps!

like image 719
Rachele Avella Avatar asked Feb 01 '19 18:02

Rachele Avella


2 Answers

Right now what i have done is when a user creates an account i will log the login information into the database.
The document name is set to the user UID that firebase give the user. Now you can simply request the data from the database with the user UID as being your .doc(user.uid).

This is the full code.

  var htmlEmail = document.getElementById('email').value;
  var htmlPass = document.getElementById('password').value;
  var htmlUser = document.getElementById('username').value.toLowerCase();
  var auth = firebase.auth();


  var promise = auth.createUserWithEmailAndPassword(htmlEmail, htmlPass);
  // If there is any error stop the process.
  promise.catch(function (error) {
      var errorCode = error.code;
      console.log(`GOT ERROR: ` + errorCode)
      if (errorCode == 'auth/weak-password') return // password to weak. Minimal 6 characters
      if (errorCode == 'auth/email-already-in-use') return // Return a email already in use error
  });

  // When no errors create the account
  promise.then(function () {
      var userUid = auth.currentUser.uid;
      var db = firebase.firestore();

      db.collection('users').doc(userUid).set({
          email: htmlEmail,
          emailVertified: false,
          name: htmlUser,
          online: false,
          onlock: false,
          password: htmlPass
      });

Then when the user logs you can simply request the data over the user.uid.

var auth = firebase.auth();
firebase.auth().onAuthStateChanged(function (user) {

    // Lay connection with the database.
    var firestore = firebase.firestore();
    var db = firestore.collection('users').doc(user.uid);

    // Get the user data from the database.
    db.get().then(function (db) {
        // Catch error if exists. 
        promise.catch(function (error) {
            // Return error
        });

        promise.then(function () {
            // continue when success
        });
    });
});

There could just be there are better ways. (still learning myself). But this does the trick for me and works very well.

There are 2 things to keep in mind !

  1. I would recommend Firestore over the real time database as it is faster and more secure.
  2. Make sure your database rules are set correctly, so that no one can view / leak your database information. (as you are logging users personal info). If not set correctly users will be able to view your database and even purge all data.

Hope it helps :)

If you find a better way yourself please let us know in here. We could learn from that also !

like image 173
Gyzimo Avatar answered Oct 03 '22 19:10

Gyzimo


In a simplified way you can do this, everytime a user will signup this function will create a firestore collection with the specific parameters.

signupWithEmail: async (_, { email, password, name }) => {
    var user = firebase.auth().createUserWithEmailAndPassword(email, 
    password).then(cred => {
    return 
    firebase.firestore().collection('USERS').doc(cred.user.uid).set({ 
    email,
    name
      })
    })
    return { user }
    }
like image 39
Ali Shirazee Avatar answered Oct 03 '22 18:10

Ali Shirazee