Syed Sehu Mujammil A
Syed Sehu Mujammil A

Reputation: 875

Firebase security rules doesn't allow when creating user

I use Firebase $authWithPassword method for user login. I use the $createUser method to create registration for my users and on its success I update entry on my /users/ path to save the username, uid and some other details. Here is the code

var myDataRef = new Firebase(baseURL + 'datalog/');
var refObj = $firebaseAuth(myDataRef);

refObj.$createUser({
    email: $scope.emailId,
    password: $scope.password
}).then(function(userData) {
    var UserUniqueUrl = new Firebase(baseURL + 'users/' + userData.uid + '/');
    UserUniqueUrl.set({
        'email': $scope.emailId,
        'username': $scope.username,
        'uid': userData.uid,
        'theme': 'default'
    }, function(error) {
        if (error) {
            console.log(error);
        } else {
            console.log('Successfully updated in user table');
        }
    });
}).catch(function(error) {
    if (error.code == 'EMAIL_TAKEN') {
        $scope.regStatusError = 'Email already registered!';
    } else {
        $scope.regStatusError = 'Unable to register! Try again later.';
    }
});

And here is my security rules

{
    "rules": {
        "users": {
            ".read": "auth != null",
            ".write": "auth != null"
        }
    }
}

Now if I try to register it gives me permission denied error which I'm sure is because of the security rules ".read": "auth != null" and ".write": "auth != null". If I change the rules to ".read": true and ".write": true, the registration will work but anyone will be able to see my user data including uid and email id which I don't want to happen. How do i change my rules to fit my need?

This is how my user table will look like enter image description here Any help is appreciated. Thanks.

Upvotes: 8

Views: 1867

Answers (2)

Namwanza Ronald
Namwanza Ronald

Reputation: 376

All you want is to only allow creating a user in your firestore database when the user is authenticated:

match /users/{uid} {
          allow create: if request.auth.uid != null;
} 

However, you can go a head to verify the user's email as:

match /users/{uid} {
          allow create: if request.auth.uid != null
              && request.auth.token.email_verified == true
}

Please note that uid will match your IDs of your documents.

Upvotes: 0

Cyrus Zei
Cyrus Zei

Reputation: 2660

yeah, you need to change your rules to something like this

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

this should fix it

Upvotes: -3

Related Questions