firebase

package module
v0.0.0-...-e956944 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2017 License: Apache-2.0 Imports: 18 Imported by: 3

README

Firebase Server SDK for Golang

This is the Server SDK written in Golang for the 2016 newly announced Firebase suite of services.

Note that this is not an official SDK written by Google/Firebase. Firebase only offers the Server SDK in Java and Node.js. This is simply an attempt to implement the Firebase Server SDK by reverse engineering the official ones. If you decide to use this SDK, be warned that you may need to migrate at some point in the future when Google decides to release an official go SDK.

This SDK, like its Java and Node counterparts, supports the following functions needed on the application server:

  • Authentication
    • Create custom tokens suitable for integrating custom auth systems with Firebase apps.
    • Verify ID tokens, which are used to pass the signed-in user from a client app to a backend server.
  • Realtime Database
    • This is a lot more involved so stay tuned.
    • For now you can use firego or Go Firebase, which are based on the Firebase REST API. These libraries are not real-time but they will allow you to read from and write to the Firebase database. Note that if you use firego, I recommend using my forked branch, which allows you to use the application default token source (which refreshes itself).
  • Cloud Messaging (FCM)
    • This is not offered even in the official Server SDKs, but it would be convenient to include this feature.
    • If you wish to use a separate client library for this feature, you can try wuman/go-gcm or google/go-gcm.

Installation

Install the package with go:

go get github.com/wuman/firebase-server-sdk-go

Import the package to your go file:

import (
	firebase "github.com/wuman/firebase-server-sdk-go"
)

Documentation

You can find documentation on godoc.org.

Initialize Firebase

Once you have created a Firebase console project and downloaded a JSON file with your service account credentials, you can initialize the SDK with this code snippet:

firebase.InitializeApp(&firebase.Options{
	ServiceAccountPath: "path/to/serviceAccountCredentials.json",
})

Create Custom Tokens

To create a custom token, pass the unique user ID used by your auth system to the CreateCustomToken() method:

auth, _ := firebase.GetAuth()
token, err := auth.CreateCustomToken(userId, nil)

You can also optionally specify additional claims to be included in the custom token. These claims will be available in the auth/request.auth objects in your Security Rules. For example:

auth, _ := firebase.GetAuth()
developerClaims = make(firebase.Claims)
developerClaims["premium_account"] = true
token, err := auth.CreateCustomToken(userId, &developerClaims)

Verify ID Tokens

To verify and decode an ID Token with the SDK, pass the ID Token to the VerifyIDToken method. If the ID Token is not expired and is properly signed, the method decodes the ID Token.

auth, _ := firebase.GetAuth()
decodedToken, err := auth.VerifyIDToken(idTokenString)
if err == nil {
	uid, found := decodedToken.Uid()
}

To-Do List

  • add travis CI
  • add sample
  • remove dependency on JWT library jose to keep the SDK lean (low priority)

Developed By

LICENSE

Copyright 2016 David Wu

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Overview

Package firebase provides authentication utilities for applications servers to integrate with Firebase.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the entry point of the SDK. It holds common configuration and state for Firebase APIs. Most applications don't need to directly interact with App.

func GetApp

func GetApp() (*App, error)

GetApp retrieves the default instance of the App, creating it if necessary.

func GetAppWithName

func GetAppWithName(name string) (*App, error)

GetAppWithName retrieves an instance of the App with a given name, creating it if necessary.

func InitializeApp

func InitializeApp(o *Options) (*App, error)

InitializeApp initializes the default App instance.

func InitializeAppWithName

func InitializeAppWithName(o *Options, name string) (*App, error)

InitializeAppWithName initializes an App with a unique given name.

It is an error to initialize an app with an already existing name. Starting and ending whitespace characters in the name are ignored (trimmed).

func (*App) Name

func (app *App) Name() string

Name returns the name of the App.

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth is the entry point for all server-side Firebase Authentication actions.

You can get an instance of Auth via GetInstance(*App) and then use it to perform a variety of authentication-related operations, including generating custom tokens for use by client-side code, verifying Firebase ID Tokens received from clients, or creating new App instances that are scoped to a particular authentication UID.

func GetAuth

func GetAuth() (*Auth, error)

GetAuth gets the Auth instance for the default App.

func GetAuthWithApp

func GetAuthWithApp(app *App) (*Auth, error)

GetAuthWithApp gets an instance of Auth for a specific App.

func (*Auth) CreateCustomToken

func (a *Auth) CreateCustomToken(uid string, developerClaims *Claims) (string, error)

CreateCustomToken creates a Firebase Custom Token associated with the given UID and additionally containing the specified developerClaims. This token can then be provided back to a client application for use with the signInWithCustomToken authentication API.

The UID identifies the user to other Firebase services (Firebase Database, Storage, etc.) and should be less than 128 characters. The developer claims are optional, additional claims to be stored in the token. The claims must be serializable to JSON.

func (*Auth) VerifyIDToken

func (a *Auth) VerifyIDToken(tokenString string) (*Token, error)

VerifyIDToken parses and verifies a Firebase ID Token.

A Firebase application can identify itself to a trusted backend server by sending its Firebase ID Token (accessible via the getToken API in the Firebase Authentication client) with its request.

The backend server can then use the VerifyIDToken() method to verify the token is valid, meaning: the token is properly signed, has not expired, and it was issued for the project associated with this Auth instance (which by default is extracted from your service account).

func (*Auth) VerifyIDTokenWithTransport

func (a *Auth) VerifyIDTokenWithTransport(tokenString string, transport http.RoundTripper) (*Token, error)

VerifyIDToken parses and verifies a Firebase ID Token.

Same as VerifyIDToken but with the possibility to define the Transport to be use by http.Client This have to be use in Google App Engine standard environment with the fetchUrl transport.

type Certificates

type Certificates struct {
	// URL to retrieve the public certificates, meant to be initialized only once.
	URL string
	// Transport is the network transport, meant to be initialized only once.
	Transport http.RoundTripper
	// lock for the certs and the exp
	sync.RWMutex
	// contains filtered or unexported fields
}

Certificates holds a collection of public certificates that are fetched from a given URL. The certificates can be reloaded when the cached certs are expired.

func (*Certificates) Cert

func (c *Certificates) Cert(kid string) (*x509.Certificate, error)

Cert returns the public certificate for the given key ID.

type Claims

type Claims map[string]interface{}

Claims to be stored in a custom token (and made available to security rules in Database, Storage, etc.). These must be serializable to JSON (e.g. contains only Maps, Arrays, Strings, Booleans, Numbers, etc.).

type GoogleServiceAccountCredential

type GoogleServiceAccountCredential struct {
	// ProjectID is the project ID.
	ProjectID string
	// PrivateKey is the RSA256 private key.
	PrivateKey *rsa.PrivateKey
	// ClientEmail is the client email.
	ClientEmail string
}

GoogleServiceAccountCredential is the credential for a GCP Service Account.

func (*GoogleServiceAccountCredential) UnmarshalJSON

func (c *GoogleServiceAccountCredential) UnmarshalJSON(data []byte) error

UnmarshalJSON is the custom unmarshaler for GoogleServiceAccountCredential. Private key is parsed from PEM format.

type Options

type Options struct {
	// ServiceAccountPath is the path to load the Service Account.
	ServiceAccountPath string
	// ServiceAccountCredential is the credential for the Service Account.
	ServiceAccountCredential *GoogleServiceAccountCredential
}

Options is storage for configurable Firebase options.

type Token

type Token struct {
	// contains filtered or unexported fields
}

Token is a parsed read-only ID Token struct. It can be used to get the uid and other attributes of the user provided in the token.

func (*Token) Claims

func (t *Token) Claims() Claims

Claims returns all of the claims on this token.

func (*Token) Email

func (t *Token) Email() (string, bool)

Email returns the email address for this user, or nil if it's unavailable.

func (*Token) IsEmailVerified

func (t *Token) IsEmailVerified() (bool, bool)

IsEmailVerified indicates if the email address returned by Email() has been verified as good.

func (*Token) Issuer

func (t *Token) Issuer() (string, bool)

Issuer returns the issuer for this token.

func (*Token) Name

func (t *Token) Name() (string, bool)

Name returns the user's display name.

func (*Token) Picture

func (t *Token) Picture() (string, bool)

Picture returns the URI string of the user's profile photo.

func (*Token) UID

func (t *Token) UID() (string, bool)

UID returns the uid for this token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL