karlcridland
karlcridland

Reputation: 1

Unable to link user id to write to a database with firebase

I'm trying to set up a database where information can be read by anyone and only written by users that are signed in. I've tested read and write operations with public permissions and it does both, so there are no problems with a connection from the database to the app but when I use the permissions below I get an error message.

When I run authTest() it returns the correct email, I've tested this in other classes and it's consistent. Please help, what am I missing?

{
  "rules": {
    ".read": true,
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
  }
}
import Foundation
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase

class LogIn{

    var username = String()
    var password = String()

    init(){
        Auth.auth().signIn(withEmail: username, password: password) { [weak self] user, error in
            guard let strongSelf = self else { return }
            strongSelf.isLoading()
            Database.database().reference().child("test").setValue("hello")
        }
    }

    func authTest() -> String{
        return Auth.auth().currentUser!.email!
    }
}

Upvotes: 0

Views: 95

Answers (1)

ked
ked

Reputation: 2456

By default database permissions are false link, so when you are trying to write data to

Database.database().reference().child("test").setValue("hello")

it gives permission denied error, so update your database rules as follows

{
  "rules": {
    ".read": true,
    "test":{
      ".write": "auth.uid != null"
     }
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
  }
}

Whenever you write data to new sibling path you should update the rules accordingly

Upvotes: 1

Related Questions