Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase user authentication in python

I'm trying to acsess data on firebase from python (2.7).

Here are my rules (on firebseio.com):

{
    "rules": {
        "user": {
          "$uid": {
            ".read": "auth != null && auth.uid == $uid",
            ".write": "auth != null && auth.uid == $uid"
          }
        }
    }
}

Here is a screenshot of my databse:

enter image description here

And last, my python code:

from firebase import firebase
from firebase.firebase import FirebaseApplication, FirebaseAuthentication

DSN = 'https://<my name>.localhost'
EMAIL = '[email protected]'
authentication = FirebaseAuthentication(EMAIL, True, True, extra={'id': '<the user id>'})
firebase = FirebaseApplication(DSN, authentication)
firebase.authentication = authentication
print authentication.extra

user = authentication.get_user()
print user.firebase_auth_token

Now I cant figer out how to get data and send data to and from firebase. I tryed useing the line: result = firebase.get('/users', None, {'print': 'pretty'}), But it gives me this error:

ConnectionError: HTTPSConnectionPool(host='<my name>.localhost', port=443): Max retries exceeded with url: /users/.json?print=pretty&auth=<the token code of the user> (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x02A913B0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))

Can Anyone provide me with a working code?

Thanks in advance,

Zvi Karp

like image 457
Zvi Karp Avatar asked Apr 03 '16 18:04

Zvi Karp


People also ask

Can you use Firebase with Python?

Supported Python VersionsWe currently support Python 3.7+. Firebase Admin Python SDK is also tested on PyPy and Google App Engine environments.

What is get auth () in Firebase?

Firebase Auth is a service that allows your app to sign up and authenticate a user against multiple providers such as (Google, Facebook, Twitter, GitHub and more).

Is Firebase Auth JWT?

Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.


1 Answers

Here are the steps we took to get authentication working.

(1) First you need a Firebase Secret. After you have a project in Firebase, then click Settings. Then click Database and choose to create a secret. settings

Copy your secret. It will go into your code later.

secret

(2) You need your firebase URL. It will have the format like this: https://.firebaseio.com Copy this too.

(3) Get a Firebase REST API for Python. We used this one: https://github.com/benletchford/python-firebase-gae Navigate to above your lib directory and run this command which will place the firebase code into your lib directory:

git clone http://github.com/benletchford/python-firebase-gae lib/firebase

(4) In your "main.py" file (or whatever you are using) add this code:

from google.appengine.ext import vendor
vendor.add('lib')

from firebase.wrapper import Firebase

FIREBASE_SECRET = 'YOUR SECRET FROM PREVIOUS STEPS'
FIREBASE_URL = 'https://[…].firebaseio.com/'

(5) Add this code to the MainHandler (assuming you are using AppEngine):

class MainHandler(webapp2.RequestHandler):
    def get(self):
        fb = Firebase(FIREBASE_URL + 'users.json', FIREBASE_SECRET)

        new_user_key = fb.post({
            "job_title": "web developer",
            "name": "john smith",
        })
        self.response.write(new_user_key)
        self.response.write('<br />')

        new_user_key = fb.post({
            "job_title": "wizard",
            "name": "harry potter",
        })
        self.response.write(new_user_key)
        self.response.write('<br />')

        fb = Firebase(FIREBASE_URL + 'users/%s.json' % (new_user_key['name'], ), FIREBASE_SECRET)
        fb.patch({
            "job_title": "super wizard",
            "foo": "bar",
        })

        fb = Firebase(FIREBASE_URL + 'users.json', FIREBASE_SECRET)
        self.response.write(fb.get())
        self.response.write('<br />')

Now when you navigate to your Firebase Realtime Database, you should see entries for Harry Potter as a user and others.

like image 91
Praxiteles Avatar answered Sep 23 '22 18:09

Praxiteles