firebase

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2020 License: Apache-2.0 Imports: 32 Imported by: 0

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

View Source
var (
	// AuthErrInvalidArgument represents the default api error that
	// an invalid argument was provided to an Authentication method.
	AuthErrInvalidArgument = &APIError{
		Code:    "auth/argument-error",
		Message: "Invalid argument provided.",
	}
	// AuthErrEmailAlreadyExists represents the default api error that
	// the provided email is already in use by an existing user.
	AuthErrEmailAlreadyExists = &APIError{
		Code:    "auth/email-already-exists",
		Message: "The email address is already in use by another account.",
	}
	// AuthErrInternalError represents the default api error that
	// the Authentication server encountered an unexpected error while
	// trying to process the request.
	AuthErrInternalError = &APIError{
		Code:    "auth/internal-error",
		Message: "An internal error has occurred.",
	}
	// AuthErrInvalidCredential represents the default api error that
	// the credential used to authenticate the Admin SDKs cannot be used
	// to perform the desired action.
	AuthErrInvalidCredential = &APIError{
		Code:    "auth/invalid-credential",
		Message: "Invalid credential object provided.",
	}
	// AuthErrInvalidDisabledField represents the default api error that
	// the provided value for the disabled user property is invalid
	AuthErrInvalidDisabledField = &APIError{
		Code:    "auth/invalid-disabled-field",
		Message: "The disabled field must be a boolean.",
	}
	// AuthErrInvalidDisplayName represents the default api error that
	// the provided value for the displayName user property is invalid
	AuthErrInvalidDisplayName = &APIError{
		Code:    "auth/invalid-display-name",
		Message: "The displayName field must be a valid string.",
	}
	// AuthErrInvalidEmailVerified represents the default api error that
	// the provided value for the emailVerified user property is invalid.
	AuthErrInvalidEmailVerified = &APIError{
		Code:    "auth/invalid-email-verified",
		Message: "The emailVerified field must be a boolean.",
	}
	// AuthErrInvalidEmail represents the default api error that
	// the provided value for the email user property is invalid
	AuthErrInvalidEmail = &APIError{
		Code:    "auth/invalid-email",
		Message: "The email address is improperly formatted.",
	}
	// AuthErrInvalidPassword represents the default api error that
	// the provided value for the password user property is invalid.
	AuthErrInvalidPassword = &APIError{
		Code:    "auth/invalid-password",
		Message: "The password must be a string with at least 6 characters.",
	}
	// AuthErrInvalidPhotoURL represents the default api error that
	// the provided value for the photoURL user property is invalid.
	AuthErrInvalidPhotoURL = &APIError{
		Code:    "auth/invalid-photo-url",
		Message: "The photoURL field must be a valid URL.",
	}
	// AuthErrInvalidUID represents the default api error that the provided uid is invalid.
	// It must be a non-empty string with at most 128 characters.
	AuthErrInvalidUID = &APIError{
		Code:    "auth/invalid-uid",
		Message: "The uid must be a non-empty string with at most 128 characters.",
	}
	// AuthErrMissingUID represents the default api error that
	// a uid identifier is required for the current operation.
	AuthErrMissingUID = &APIError{
		Code:    "auth/missing-uid",
		Message: "A uid identifier is required for the current operation.",
	}
	// AuthErrOperationNotAllowed represents the default api error that
	// the provided sign-in provider is disabled for your Firebase project.
	AuthErrOperationNotAllowed = &APIError{
		Code: "auth/operation-not-allowed",
		Message: `The given sign-in provider is disabled for this Firebase project.
		Enable it in the Firebase console, under the sign-in method tab of the Auth section.`,
	}
	// AuthErrProjectNotFound represents the default api error that
	// no Firebase project was found for the credential used to initialize the SDK.
	AuthErrProjectNotFound = &APIError{
		Code:    "auth/project-not-found",
		Message: "No Firebase project was found for the provided credential.",
	}
	// AuthErrInsufficientPermission represents the default api error that
	// the credential used to initialize the SDK has insufficient permission
	// to access the requested Authentication resource.
	AuthErrInsufficientPermission = &APIError{
		Code: "auth/insufficient-permission",
		Message: `Credential implementation provided to initializeApp() via the "credential" property has insufficient permission to access the requested resource.
		 See https://firebase.google.com/docs/admin/setup for details on how to authenticate this SDK with appropriate permissions.
		 `,
	}
	// AuthErrUIDAlreadyExists represents the default api error that
	// the provided uid is already in use by an existing user.
	AuthErrUIDAlreadyExists = &APIError{
		Code:    "auth/uid-already-exists",
		Message: "The user with the provided uid already exists.",
	}
	// AuthErrUserNotFound represents the default api error that
	// there is no existing user record corresponding to the provided identifier.
	AuthErrUserNotFound = &APIError{
		Code:    "auth/user-not-found",
		Message: "There is no user record corresponding to the provided identifier.",
	}
	// AuthErrInvalidPassword represents the default api error that
	// the provided value for the password user property is invalid.
	AuthErrInvalidPhoneNumber = &APIError{
		Code:    "auth/invalid-phone-number",
		Message: "The phoneNumber must be a string.",
	}
)

The default auth errors definitions. For any advance information, see https://firebase.google.com/docs/auth/admin/errors

View Source
var SystemClock = &CurrentClock{}

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    string
	Message string
}

APIError defines the data model of Firebase API errors.

func (*APIError) Error

func (e *APIError) Error() string

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) CheckRevoked added in v1.0.2

func (auth *Auth) CheckRevoked(cookie string) (bool, error)

CheckRevoked checks if the cookie has not been revoked

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) CreateSessionCookie added in v1.0.2

func (auth *Auth) CreateSessionCookie(idToken string, duration *time.Duration) (*string, error)

CreateSessionCookie attempts to create a session cookie for the given user id

func (*Auth) CreateUser

func (auth *Auth) CreateUser(properties UserProperties) (*UserRecord, error)

CreateUser creates a new user with the properties provided.

func (*Auth) DeleteUser

func (auth *Auth) DeleteUser(uid string) error

DeleteUser deletes the user identified by the provided user id and returns nil error when the user is found and successfully deleted.

func (*Auth) GetUser

func (auth *Auth) GetUser(uid string) (*UserRecord, error)

GetUser looks up the user identified by the provided user id and returns a user record for the given user if that user is found.

func (*Auth) GetUserByEmail

func (auth *Auth) GetUserByEmail(email string) (*UserRecord, error)

GetUserByEmail looks up the user identified by the provided email and returns a user record for the given user if that user is found.

func (*Auth) RevokeRefreshTokens added in v1.0.2

func (auth *Auth) RevokeRefreshTokens(uid string) error

RevokeRefreshTokens revokes all session cookie refresh tokens for the user

func (*Auth) UpdateUser

func (auth *Auth) UpdateUser(uid string, properties UserProperties) (*UserRecord, error)

UpdateUser updates an existing user with the properties provided.

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.

func (*Auth) VerifySessionCookie added in v1.0.2

func (auth *Auth) VerifySessionCookie(cookie string) (*UserRecord, error)

VerifySessionCookie checks if the cookie is valid

func (*Auth) VerifySessionCookieAndCheckRevoked added in v1.0.2

func (auth *Auth) VerifySessionCookieAndCheckRevoked(cookie string) (*UserRecord, error)

VerifySessionCookieAndCheckRevoked checks if the cookie is valid and has not been revoked

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 Clock added in v1.0.2

type Clock interface {
	Now() time.Time
}

Clock is used to query the current local time.

type CurrentClock added in v1.0.2

type CurrentClock struct{}

Clock returns the current system time.

func (*CurrentClock) Now added in v1.0.2

func (s *CurrentClock) Now() time.Time

Now returns the current system time by calling time.Now().

type GoogleServiceAccountCredential

type GoogleServiceAccountCredential struct {
	// ProjectID is the project ID.
	ProjectID string
	// PrivateKey is the RSA256 private key.
	PrivateKey *rsa.PrivateKey
	// PrivateKeyString is the private key represented in string.
	PrivateKeyString string
	// 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 MockClock added in v1.0.2

type MockClock struct {
	Timestamp time.Time
}

MockClock can be used to mock current time during tests.

func (*MockClock) Now added in v1.0.2

func (m *MockClock) Now() time.Time

Now returns the timestamp set in the MockClock.

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 {
	Issuer   string                 `json:"iss"`
	Audience string                 `json:"aud"`
	Expires  int64                  `json:"exp"`
	IssuedAt int64                  `json:"iat"`
	Subject  string                 `json:"sub,omitempty"`
	UID      string                 `json:"uid,omitempty"`
	Claims   map[string]interface{} `json:"-"`
}

Token represents a decoded Firebase ID token.

Token provides typed accessors to the common JWT fields such as Audience (aud) and Expiry (exp). Additionally it provides a UID field, which indicates the user ID of the account to which this token belongs. Any additional JWT claims can be accessed via the Claims map of Token.

func (*Token) AuthTime added in v1.0.2

func (t *Token) AuthTime() int64

IssuedAt returns the time this token was issued

func (*Token) Email

func (t *Token) Email() string

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

func (*Token) GetClaims added in v1.0.2

func (t *Token) GetClaims() Claims

Claims returns all of the claims on this token.

func (*Token) IsEmailVerified

func (t *Token) IsEmailVerified() bool

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

func (*Token) Name

func (t *Token) Name() string

Name returns the user's display name.

func (*Token) Picture

func (t *Token) Picture() string

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

func (*Token) SetClaims added in v1.0.2

func (t *Token) SetClaims(claims map[string]interface{})

type UserInfo

type UserInfo struct {
	UID         string
	ProviderID  string
	DisplayName string
	PhoneNumber string
	Email       string
	PhotoURL    string
}

UserInfo defines the data model for Firebase interface representing a user's info from a third-party identity provider such as Google or Facebook.

type UserMetadata

type UserMetadata struct {
	CreatedAt    time.Time
	LastSignedIn time.Time
}

UserMetadata defines the data model for Firebase interface representing a user's metadata.

type UserProperties

type UserProperties map[string]interface{}

UserProperties defines the input user properties in a create or edit user API.

Note that user attributes without setup in create actions will remain in default values. And attributes without setup in edit actions are remaining unchanged.

func (UserProperties) SetDisabled

func (p UserProperties) SetDisabled(disabled bool) UserProperties

SetDisabled sets whether or not the user is disabled

func (UserProperties) SetDisplayName

func (p UserProperties) SetDisplayName(displayName string) UserProperties

SetDisplayName sets the users' display name. Only passing an empty string in edit actions removes the display name in the user record.

func (UserProperties) SetEmail

func (p UserProperties) SetEmail(email string) UserProperties

SetEmail sets the user's primary email. Must be a valid email address.

func (UserProperties) SetEmailVerified

func (p UserProperties) SetEmailVerified(emailVerified bool) UserProperties

SetEmailVerified sets whether or not the user's primary email is verified.

func (UserProperties) SetPassword

func (p UserProperties) SetPassword(password string) UserProperties

SetPassword sets the user's raw, unhashed password. Must be at least six characters long.

func (UserProperties) SetPhoneNumber

func (p UserProperties) SetPhoneNumber(phoneNumber string) UserProperties

The user's new primary phone number. Must be a valid E.164 spec compliant phone number.

func (UserProperties) SetPhotoURL

func (p UserProperties) SetPhotoURL(photoURL string) UserProperties

SetPhotoURL sets the user's photo URL. Only passing an empty string in edit actions removes the photo URL in the user record.

func (UserProperties) SetUID

func (p UserProperties) SetUID(uid string) UserProperties

SetUID sets the uid to assign to the newly created user. Must be a string between 1 and 128 characters long, inclusive. If not provided, a random uid will be automatically generated.

Note that this property takes no effects in update user actions.

func (UserProperties) SetValidSince added in v1.0.2

func (p UserProperties) SetValidSince(valid time.Time) UserProperties

type UserRecord

type UserRecord struct {
	UID                    string
	DisplayName            string
	Email                  string
	EmailVerified          bool
	PhotoURL               string
	ProviderData           []*UserInfo
	TokensValidAfterMillis int64 // milliseconds since epoch.
	Disabled               bool
	Metadata               *UserMetadata
	PhoneNumber            string
}

UserRecord defines the data model for Firebase interface representing a user.

Jump to

Keyboard shortcuts

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