Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift + Firebase Security not working

I have two users created in my Firebase console, both have a different username and email address.

I want them to be able to store their score online in the database. This is the structure:

AppName
  - GameStats
    - DBW9WQEs2sQn9CuPTE9t7Q1qWSz2
      - Score : 0986
    - Li75C2BYW7bQnKqMmrqLAZ67HUy4
      - Score : 44131

To access this value and keep it synced I am using this:

let baseRef = FIRDatabase.database().reference(withPath: "GameStats/" + user.uid + "")
let scoreRef = scoreRef.child("Score")

scoreRef.observe(.value, with: { snapshot in
   print(snapshot.value)
})

I wanted to test whether the two users could access other information from another user. I changed the line to include the other user.uid like so:

let baseRef = FIRDatabase.database().reference(withPath: "GameStats/Li75C2BYW7bQnKqMmrqLAZ67HUy4")

// Logged in User: DBW9WQEs2sQn9CuPTE9t7Q1qWSz2

and for some reason it outputs this:

Optional(44131)

If I change the value in the database, it automatically updates the value to the one I put.

This is the wrong user and for some reason it is able to access it.

These are my rules:

  {
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
      "GameStats": {
         "$user_id": {
         ".write": "auth != null && auth.uid === $user_id && auth.provider === 'password'",
         ".read": "auth != null && auth.uid === $user_id && auth.provider === 'password'"
      }
    }
  }
}

Why is the app allowing one user to read another users data and how do I restrict access so that the user can only access the data under their userid?

As @M_G suggested, I took out the .write from the parent and the .read. So my rules are now:

  {
  "rules": {
    // ".read": "auth != null",
    // ".write": "auth != null",
      "GameStats": {
         "$user_id": {
         ".write": "auth != null && auth.uid === $user_id && auth.provider === 'password'",
         ".read": "auth != null && auth.uid === $user_id && auth.provider === 'password'"
       }
     }
  }
}

I now get this output:

[FirebaseDatabase] setValue: or removeValue: at /GameStats/DBW9WQEs2sQn9CuPTE9t7Q1qWSz2 failed: permission_denied - This is for the correct user too. I get this error if wrong user also. 
like image 738
JamesG Avatar asked Oct 04 '16 18:10

JamesG


1 Answers

Firebase document is wrong (for now). In Firebase console, open rule simulator. There is no 'password' option at this time, I think its a bug.

If you have not use multiple authentication or multiple authentication does not matter in your project, dont use provider at your rules. Otherwise you can test this rule for password authentication:

".write": "auth != null && auth.uid === $user_id && auth.token.firebase.identities.email !== null"
like image 115
Muzaffer Avatar answered Oct 03 '22 00:10

Muzaffer