Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, 30 August 2017

Introducing Firebase Admin SDK for Go

Hiranya Jayathilaka
Hiranya Jayathilaka
Software Engineer

The Firebase Admin SDK for Go is now generally available. This is the fourth programming language to join our growing family of Admin SDKs, which already includes support for Java, Python and Node.js. Firebase Admin SDKs enable application developers to programmatically access Firebase services from trusted environments. They complement the Firebase client SDKs, which enable end users to access Firebase from their web browsers and mobile devices. The initial release of the Firebase Admin SDK for Go comes with some Firebase Authentication features: custom token minting and ID token verification.

Initializing the Admin SDK for Go

Similar to the other Firebase Admin SDKs, the Go Admin SDK can be initialized with a variety of authentication credentials and client options. The following code snippet shows how to initialize the SDK using a service account credential obtained from the Firebase console or the Google Cloud console:

import (
"golang.org/x/net/context"

firebase "firebase.google.com/go"
"google.golang.org/api/option"
)

opt := option.WithCredentialsFile("path/to/key.json")
app, err := firebase.NewApp(context.Background(), nil, opt)

If you are running your code on Google infrastructure, such as Google App Engine or Google Compute Engine, the SDK can auto-discover application default credentials from the environment. In this case you do not have to explicitly specify any credentials when initializing the Go Admin SDK:

import (
"golang.org/x/net/context"

firebase "firebase.google.com/go"
)

app, err := firebase.NewApp(context.Background(), nil)

Minting Custom Tokens and Verifying ID Tokens

The initial release of the Firebase Admin SDK for Go comes with support for minting custom tokens and verifying Firebase ID tokens. The custom token minting allows you to authenticate users using your own user store or authentication mechanism:

client, err := app.Auth()
if err != nil {
return err
}

claims := map[string]interface{}{
"premium": true,
"package": "gold",
}
token, err := client.CustomToken("some-uid", claims)

The resulting custom token can be sent to a client device, where it can be used to initiate an authentication flow using a Firebase client SDK. On the other hand, the ID token verification facilitates securely identifying the currently signed in user on your server:

client, err := app.Auth()
if err != nil {
return err
}

decoded, err := client.VerifyIDToken(idToken)
uid := decoded.UID

To learn more about using the Firebase Admin SDK for Go, see our Admin SDK setup guide.

What's Next?

We plan to further expand the capabilities of the Go Admin SDK by implementing other useful APIs such as user management and Firebase Cloud Messaging. This SDK is also open source. Therefore we welcome you to browse our Github repo and get involved in the development process by reporting issues and sending pull requests. To all Golang gophers out there, happy coding with Firebase!

Share:

Thursday, 6 July 2017

Accessing Database from the Python Admin SDK

Diego Giorgini
Hiranya Jayathilaka
Software Engineer

Last April, we announcedthe general availability of the Firebase Admin SDK for Python. The initial release of this SDK supported two important features related to Firebase Authentication: minting custom tokens, and verifying ID tokens. Now, we are excited to announce that database support is available in the Firebase Admin SDK for Python starting from version 2.1.0.

Due to the way it's implemented, there are several notable differences between this API and the database APIs found in our other Admin SDKs (Node.js and Java). The most prominent of these differences is the lack of support for realtime event listeners. The Python Admin SDK currently does not provide a way to add event listeners to a database reference in order to receive realtime update notifications. Instead, all data retrieval operations are provided as blocking methods. However, despite these differences there's a lot that can be achieved using this API.

The database module of the Python Admin SDK facilitates both basic data manipulation operations and advanced queries. To begin interacting with the database from a Python environment, initialize the SDK with the Realtime Database URL:

import firebase_admin
from firebase_admin import credentials

cred = credentials.Cert('path/to/serviceKey.json')
firebase_admin.initialize_app(cred, {
'databaseURL' : 'https://my-db.firebaseio.com'
})

Then obtain a database reference from the db module of the SDK. Database references expose common database operations as Python methods (get(), set(), push(), update() and delete()):

from firebase_admin import db

root = db.reference()
# Add a new user under /users.
new_user = root.child('users').push({
'name' : 'Mary Anning',
'since' : 1700
})

# Update a child attribute of the new user.
new_user.update({'since' : 1799})

# Obtain a new reference to the user, and retrieve child data.
# Result will be made available as a Python dict.
mary = db.reference('users/{0}'.format(new_user.key)).get()
print 'Name:', mary['name']
print 'Since:', mary['since']

In the Firebase Realtime Database, all data values are stored as JSON. Note how the Python Admin SDK seamlessly converts between JSON and Python's native data types.

To execute an advanced query, call one of the order_by_* methods available on the database reference. This returns a query object, which can be used to specify additional parameters. You can use this API to execute limit queries and range queries against your data, and retrieve sorted results.

from firebase_admin import db

dinos = db.reference('dinosaurs')

# Retrieve the five tallest dinosaurs in the database sorted by height.
# 'result' will be a sorted data structure (list or OrderedDict).
result = dinos.order_by_child('height').limit_to_last(5).get()

# Retrieve the 5 shortest dinosaurs that are taller than 2m.
result = dinos.order_by_child('height').start_at(2).limit_to_first(5).get()

# Retrieve the score entries whose values are between 50 and 60.
result = db.reference('scores').order_by_value() \
.start_at(50).end_at(60).get()

Take a look at the Admin SDK documentation for more information about this new API. Also check out our Github repo, and help us further improve the Admin SDK by reporting issues and contributing patches. In fact, it was your continuing feedback that motivated us to build and release this API in such a short period. Happy coding with Firebase!

Share:

Wednesday, 5 April 2017

Bringing Firebase Admin To Python

Diego Giorgini
Hiranya Jayathilaka
Software Engineer


After announcing the Firebase Admin SDKs for Node.js and Java at the Firebase Dev Summit in Berlin last year, we received many feature requests to bring the platform to Python developers as well. Now, we're pleased to announce that first release of the Firebase Admin Python SDK, focusing on Firebase Auth token minting and verification. 

What are the Admin SDKs?


The Firebase Admin SDKs provide developers with programmatic, second-party auth access to Firebase services from trusted environments. Second-party here refers to the fact that the SDKs are granted elevated permissions that allow them to do more than a normal, untrusted client device can. The Admin SDKs get these elevated permissions since they are authenticated with a service account, a special Google account that can be used by applications to access Google services programmatically. The Admin SDKs are meant to complement the existing Firebase web and mobile clients which provide third-party, end-user access to Firebase services on client devices.


What is available in the Admin Python SDK?


As with the other Firebase Admin SDKs, the Python SDK can be initialized using a variety of built-in credential types. The following code shows how to authenticate the SDK using your own service account key file:
import firebase_admin
from firebase_admin import credentials

cred = credentials.Certificate("path/to/service.json")
firebase_admin.initialize_app(cred)

If you are running your code on Google infrastructure, such as Google App Engine or Google Compute Engine, the SDK can auto-discover the credential, allowing you to initialize the SDK with no arguments:
firebase_admin.initialize_app()

The Python Admin SDK contains Firebase Auth custom token minting and ID token verification. The custom token minting gives you complete control over authentication by allowing you to authenticate users or devices using your own authentication system.

uid = "some-uid"
additional_claims = {
"premiumAccount": True
}

custom_token = auth.create_custom_token(uid, additional_claims)

ID token verification allows you to securely identify the currently signed-in user on your server.

decoded_token = auth.verify_id_token(id_token)
uid = decoded_token["uid"]

The best place to start is with our Admin SDKs setup guide. The guide will walk you through how to download the SDK, generate a service account key file, and use that key file to initialize the Admin SDK.


What is coming next?

We plan to continue to build out the Admin Python SDK to include features already available in the other Admin SDKs, such as a user management API and an FCM API to send messages. We also plan to bring these token minting and verification features to even more languages. To see what APIs are available in each of the Admin SDKs, see our new feature matrix.

To all those Python developers out there, happy hacking!
Share: