1

I am farely new to Pyrebase and Firebase and I was wondering why this code isn't working. I want to write to the realtime database, for that the rules are

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

And the python code is:

def login():
    email = input("Enter email: ")
    password = input("Enter password: ")
    user = auth.sign_in_with_email_and_password(email, password)
    user = auth.refresh(user['refreshToken'])
    uid_variable = user['userId']
    print(uid_variable)
    print("Successfully logged in!")
    data = {"test": "test"}
    db.child("userdata").child(uid_variable).set(data)

But when it tries to write to the database it shows:

 [Errno 401 Client Error: Unauthorized for url: https://xxxxxxxxxx-default-rtdb.europe-west1.firebasedatabase.app/userdata/xxxxxxxxxxxxxxxxxxxxxxxx.json] {
  "error" : "Permission denied"
}

I don't seem to find any help anywhere so anything would be appreciated!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kroyz
  • 21
  • 2
  • I am struggling on the same point. It looks like pyrebase is not unable to perform correct authentication on Firebase. If I change the rules for your database to let everyone reads, it works perfectly, but if I set to only authenticated user, it denies reading. – Marcelo Jul 28 '22 at 16:13
  • I made a very simple test by ".read": "auth.uid == null", (which means the pyrebase is not authenticated and I could read everything. I set to ".read": "auth.uid != null",. then it denies. I think this is an issue with pyrebase authenticating process. – Marcelo Jul 28 '22 at 16:15

1 Answers1

0

Depending on what you're using with your backend, this post on how to integrate Firebase Auth with a FastAPI backend using Pyrebase and Firebase Admin shows how you can create a login with Pyrebase using username and password

Based on the code here:

@app.post("/login", include_in_schema=False)
async def login(request: Request):
   req_json = await request.json()
   email = req_json['email']
   password = req_json['password']
   try:
       user = pb.auth().sign_in_with_email_and_password(email, password)
       jwt = user['idToken']
       return JSONResponse(content={'token': jwt}, status_code=200)
   except:
       return HTTPException(detail={'message': 'There was an error logging in'}, status_code=400)

I believe you need to call the auth() function with the pyrebase object you created.

bujian
  • 152
  • 8