marrrrrrk
marrrrrrk

Reputation: 75

Firebase Authentication creates user but does not add their Info to database

I am new to using firebase and ios development in general. I am having an issue with adding user's info to the firestore database even though they are being added as authenticated users. Any Suggestions?

Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                if err != nil {
                    self.errorLabel.text = "Error Creating User"
                    self.errorLabel.alpha = 1
                } else {
                    let db = Firestore.firestore()

                    db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "uid":result!.user.uid]) { (error) in

                        if error != nil {

                            self.errorLabel.text = "error saving user data"
                            self.errorLabel.alpha = 1
                        }
                    }

                    self.transitionScreens()

                }
            }
        }
    }

Upvotes: 1

Views: 2208

Answers (2)

ked
ked

Reputation: 2456

Check out the following different rules you can give access to users depending on the data

service cloud.firestore {
  match /databases/{database}/documents {
  //allows all users to read and write, but dangerous as any one can flood your database
    match /public_collection/{document=**} {
        allow read, write: if true;
    }
//only read access
    match /public_read_collection/{document=**} {
        allow read: if true;
        allow write: if false;
    }
//prefered for storing users personal info, users can access only their data
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }
//any authenticated user can access or write data
    match /posts/{documentId} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80914

Change your code to the following:

// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
    "firstname": firstname,
    "lastname": lastname,
    "uid": result!.user.uid
]) { err in
    if let err = err {
        print("Error adding document: \(err)")
    } else {
        print("Document added with ID: \(ref!.documentID)")
    }
}

Using this print statement print("Error adding document: \(err)") you can know exactly what the error is.

Also change your security rules to the following:

// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Upvotes: 3

Related Questions