firebase

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2017 License: MIT Imports: 22 Imported by: 0

README

go-firebase-admin

Build Status Coverage Status Go Report Card GoDoc MIT Licence

Table of Contents

Overview

Firebase Admin SDK for Golang

On Wednesday, May 17, 2017 Google announced at Google IO : Open sourcing the Firebase SDKs. But for now, there is no official Admin SDK for Golang, only Java, Node and Python Admin SDKs.

So welcome go-firebase-admin SDK :)

Note

If you decide to use this unofficial SDK still in development,
please use any package manager to fix version, there will be a lot of breaking changes.

Installation

Install the package with go:

go get github.com/acoshift/go-firebase-admin

Features

This go-firebase-admin SDK supports the following functions :

  • Authentication

  • User Management API

    • GetUser : fetching the profile information of users by their uid
    • GetUsers : fetching list of profile information of users by their uid
    • GetUserByEmail : fetching the profile information of users by their email
    • GetUsersByEmail : fetching list of profile information of users by their email
    • GetUserByPhoneNumber : fetching the profile information of users by their phoneNumber
    • GetUsersByPhoneNumber : fetching list of profile information of users by their phoneNumber
    • ListUsers : fetching the profile information of users
    • CreateUser : create a new Firebase Authentication user
    • UpdateUser : modifying an existing Firebase user's data.
    • DeleteUser : deleting existing Firebase user by uid
    • SendPasswordResetEmail : send password reset for the given user
    • VerifyPassword : verifies given email and password
  • Realtime Database API

    • not documented
  • Cloud Messaging API

    • SendToDevice : Send Message to individual device
    • SendToDevices : Send multicast Message to a list of devices
    • SendToDeviceGroup : Send Message to a device group
    • SendToTopic : Send Message to a topic
    • SendToCondition : Send a message to devices subscribed to the combination of topics
    • SubscribeDeviceToTopic : subscribe a device to a topic
    • SubscribeDevicesToTopic : subscribe devices to a topic
    • UnSubscribeDeviceFromTopic : Unsubscribe a device to a topic
    • UnSubscribeDevicesFromTopic : Unsubscribe devices to a topic

To-Do List

  • update documentation
  • add examples
  • add tests

Documentation

You can find more details about go-firebase-admin on godoc.org.

Usage

You need a service_account.json file, if you don't have an admin SDK service_account.json, please check this guide

You need a Firebase API Key for FCM, whose value is available in the Cloud Messaging tab of the Firebase console Settings panel

Initialize Firebase Admin SDK

package main

import (
  "io/ioutil"

  "google.golang.org/api/option"
  "github.com/acoshift/go-firebase-admin"
)

func main() {
  // Init App with service_account
  firApp, err := firebase.InitializeApp(context.Background(), firebase.AppOptions{
    ProjectID:      "YOUR_PROJECT_ID",
  }, option.WithCredentialsFile("service_account.json"))

  if err != nil {
    panic(err)
  }

}
Authentication
package main

import (
  "io/ioutil"

  "google.golang.org/api/option"
  "github.com/acoshift/go-firebase-admin"
)

func main() {
  // Init App with service_account
  firApp, err := firebase.InitializeApp(context.Background(), firebase.AppOptions{
    ProjectID:      "YOUR_PROJECT_ID",
  }, option.WithCredentialsFile("service_account.json"))

  if err != nil {
    panic(err)
  }

  // Firebase AUth
  firAuth := firApp.Auth()

  // VerifyIDToken
  claims, err := firAuth.VerifyIDToken("My token")

  // CreateCustomToken
  myClaims := make(map[string]string)
  myClaims["name"] = "go-firebase-admin"
  myClaims["ID"] = "go-go-go"

  cutomToken, err := firAuth.CreateCustomToken(claims.UserID, myClaims)

}
Database
package main

import (
  "io/ioutil"

  "google.golang.org/api/option"
  "github.com/acoshift/go-firebase-admin"
)

func main() {
  // Init App with service_account
  firApp, err := firebase.InitializeApp(context.Background(), firebase.AppOptions{
    ProjectID:      "YOUR_PROJECT_ID",
  }, option.WithCredentialsFile("service_account.json"))

  if err != nil {
    panic(err)
  }

  // Firebase Database
  firDatabase := firApp.Database()

  type dinosaurs struct {
    Appeared int64   `json:"appeared"`
    Height   float32 `json:"height"`
    Length   float32 `json:"length"`
    Order    string  `json:"order"`
    Vanished int64   `json:"vanished"`
    Weight   int     `json:"weight"`
  }

  r := firDatabase.Ref("test/path")
  err = r.Child("bruhathkayosaurus").Set(&dinosaurs{-70000000, 25, 44, "saurischia", -70000000, 135000})
  if err != nil {
    panic(err)
  }

  // Remove
  err = r.Remove()
  if err != nil {
    panic(err)
  }

  // Snapshot
  snapshot, err := r.OrderByChild("height").EqualTo(0.6).OnceValue()
  if err != nil {
    panic(err)
  }

}
Messaging
package main

import (
  "io/ioutil"

  "google.golang.org/api/option"
  "github.com/acoshift/go-firebase-admin"
)

func main() {
  // Init App with service_account
  firApp, err := firebase.InitializeApp(context.Background(), firebase.AppOptions{
    ProjectID:      "YOUR_PROJECT_ID",
    DatabaseURL:    "YOUR_DATABASE_URL",
    APIKey:         "YOUR_API_KEY",
  }, option.WithCredentialsFile("service_account.json"))

  if err != nil {
    panic(err)
  }

  // FCM
  firFCM := firApp.FCM()

  // SendToDevice
  resp, err := firFCM.SendToDevice(context.Background(), "mydevicetoken",
		firebase.Message{Notification: firebase.Notification{
			Title: "Hello go firebase admin",
			Body:  "My little Big Notification",
			Color: "#ffcc33"},
		})

  if err != nil {
    panic(err)
  }

  // SendToDevices
  resp, err := firFCM.SendToDevices(context.Background(), []string{"mydevicetoken"},
		firebase.Message{Notification: firebase.Notification{
			Title: "Hello go firebase admin",
			Body:  "My little Big Notification",
			Color: "#ffcc33"},
		})

  if err != nil {
    panic(err)
  }

  // SubscribeDeviceToTopic
  resp, err := firFCM.SubscribeDeviceToTopic(context.Background(), "mydevicetoken", "/topics/gofirebaseadmin")
  // it's possible to ommit the "/topics/" prefix
  resp, err := firFCM.SubscribeDeviceToTopic(context.Background(), "mydevicetoken", "gofirebaseadmin")

  if err != nil {
    panic(err)
  }

  // UnSubscribeDeviceFromTopic
  resp, err := firFCM.UnSubscribeDeviceFromTopic(context.Background(), "mydevicetoken", "/topics/gofirebaseadmin")
  // it's possible to ommit the "/topics/" prefix
  resp, err := firFCM.UnSubscribeDeviceFromTopic(context.Background(), "mydevicetoken", "gofirebaseadmin")

  if err2 != nil {
    panic(err)
  }

}

Licence

MIT License

Copyright (c) 2016 Thanatat Tamtan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package firebase is the unofficial firebase admin sdk: https://firebase.google.com/docs/auth/admin/

Index

Constants

View Source
const (
	Google   string = "google.com"
	Facebook string = "facebook.com"
	Github   string = "github.com"
	Twitter  string = "twitter.com"
)

Providers

Variables

View Source
var (
	// ErrRequireServiceAccount
	ErrRequireServiceAccount = errors.New("firebase: requires service account")

	// ErrRequireUID
	ErrRequireUID = errors.New("firebaseauth: require user id")

	// ErrNotImplemented
	ErrNotImplemented = errors.New("firebase: feature not yet implemented")

	// ErrUserNotFound
	ErrUserNotFound = errors.New("firebaseauth: user not found")

	// ErrAuthentication
	ErrAuthentication = errors.New("firebase: Authentication Error")
)

Error constants

View Source
var (
	// ErrMissingRegistration
	//
	// Check that the request contains a registration token (in the registration_id in or
	// registration_ids field in JSON).
	ErrMissingRegistration = errors.New("firebaseFCM: missing registration token")

	// ErrInvalidRegistration
	//
	// Check the format of the registration token you pass to the server. Make sure it matches
	// the registration token the client app receives from registering with Firebase Notifications.
	// Do not truncate or add additional characters.
	ErrInvalidRegistration = errors.New("firebaseFCM: invalid registration token")

	// ErrNotRegistered
	//
	// An existing registration token may cease to be valid in a number of scenarios, including:
	//
	// If the client app unregisters with FCM.
	//
	// If the client app is automatically unregistered, which can happen if the user uninstalls
	// the application. For example, on iOS, if the APNS Feedback Service reported the APNS
	// token as invalid.
	//
	// If the registration token expires (for example, Google might decide to refresh
	// registration tokens, or the APNS token has expired for iOS devices).
	//
	// If the client app is updated but the new version is not configured to receive messages.
	// For all these cases, remove this registration token from the app server and stop using it
	// to send messages.
	ErrNotRegistered = errors.New("firebaseFCM: unregistered device")

	// ErrInvalidPackageName
	//
	// Make sure the message was addressed to a registration token whose package name
	// matches the value passed in the request.
	ErrInvalidPackageName = errors.New("firebaseFCM: invalid package name")

	// ErrMismatchSenderID
	//
	// A registration token is tied to a certain group of senders. When a client app registers for
	// FCM, it must specify which senders are allowed to send messages. You should use one
	// of those sender IDs when sending messages to the client app. If you switch to a different
	// sender, the existing registration tokens won't work.
	ErrMismatchSenderID = errors.New("firebaseFCM: mismatched sender id")

	// ErrInvalidParameters
	//
	// Check that the provided parameters have the right name and type.
	ErrInvalidParameters = errors.New("firebaseFCM: invalid parameters")

	// ErrMessageTooBig
	//
	// Check that the total size of the payload data included in a message does not exceed
	// FCM limits: 4096 bytes for most messages, or 2048 bytes in the case of messages to
	// topics. This includes both the keys and the values.
	ErrMessageTooBig = errors.New("firebaseFCM: message is too big")

	// ErrInvalidDataKey
	//
	// Check that the payload data does not contain a key (such as from, or gcm, or any value
	// prefixed by google) that is used internally by FCM. Note that some words (such as
	// collapse_key) are also used by FCM but are allowed in the payload, in which case the
	// payload value will be overridden by the FCM value.
	ErrInvalidDataKey = errors.New("firebaseFCM: invalid data key")

	// ErrInvalidTTL
	//
	// Check that the value used in time_to_live is an integer representing a duration in
	// seconds between 0 and 2,419,200 (4 weeks).
	ErrInvalidTTL = errors.New("firebaseFCM: invalid time to live")

	// ErrUnavailable
	//
	// The server couldn't process the request in time. Retry the same request, but you must:
	//
	// Honor the Retry-After header if it is included in the response from the
	// FCM Connection Server.
	//
	// Implement exponential back-off in your retry mechanism. (e.g. if you waited one
	// second before the first retry, wait at least two second before the next one, then 4
	// seconds and so on). If you're sending multiple messages, delay each one
	// independently by an additional random amount to avoid issuing a new request for all
	// messages at the same time.
	//
	// Senders that cause problems risk being blacklisted.
	ErrUnavailable = errors.New("firebaseFCM: timeout")

	// ErrInternalServerError
	//
	// The server encountered an error while trying to process the request. You could retry the
	// same request following the requirements listed in "Timeout" (see row above). If the
	// error persists, please report the problem in the android-gcm group.
	ErrInternalServerError = errors.New("firebaseFCM: internal server error")

	// ErrDeviceMessageRateExceeded
	//
	// The rate of messages to a particular device is too high. If an iOS app sends messages at
	// a rate exceeding APNs limits, it may receive this error message
	//
	// Reduce the number of messages sent to this device and use exponential backoff to retry
	// sending.
	ErrDeviceMessageRateExceeded = errors.New("firebaseFCM: device message rate exceeded")

	// ErrTopicsMessageRateExceeded
	//
	// The rate of messages to subscribers to a particular topic is too high. Reduce the number
	// of messages sent for this topic and use exponential backoff to retry sending.
	ErrTopicsMessageRateExceeded = errors.New("firebaseFCM: topics message rate exceeded")

	// ErrInvalidApnsCredential
	//
	// A message targeted to an iOS device could not be sent because the required APNs SSL
	// certificate was not uploaded or has expired. Check the validity of your development and
	// production certificates.
	ErrInvalidApnsCredential = errors.New("firebaseFCM: invalid APNs credential")
)

Official FCM Error constants see https://firebase.google.com/docs/cloud-messaging/admin/errors see https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes

View Source
var (
	ServerValueTimestamp interface{} = struct {
		SV string `json:".sv"`
	}{"timestamp"}
)

ServerValue

Functions

This section is empty.

Types

type App

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

App holds information about application configuration

func InitializeApp

func InitializeApp(ctx context.Context, options AppOptions, opts ...option.ClientOption) (*App, error)

InitializeApp initializes firebase application with options

func (*App) Auth

func (app *App) Auth() *Auth

Auth creates new Auth instance each instance has the same firebase app instance but difference public keys instance better create only one instance

func (*App) Database

func (app *App) Database() *Database

Database creates new Database instance

func (*App) FCM added in v0.0.3

func (app *App) FCM() *FCM

FCM creates new FCM instance

type AppOptions

type AppOptions struct {
	ProjectID                    string
	DatabaseURL                  string
	DatabaseAuthVariableOverride interface{}
	APIKey                       string
}

AppOptions is the firebase app options for initialize app

type Auth

type Auth struct {
	Leeway time.Duration
	// contains filtered or unexported fields
}

Auth type

func (*Auth) CreateAuthURI added in v0.0.2

func (auth *Auth) CreateAuthURI(ctx context.Context, providerID string, continueURI string, sessionID string) (string, error)

CreateAuthURI creates auth uri for provider sign in returns auth uri for redirect

func (*Auth) CreateCustomToken

func (auth *Auth) CreateCustomToken(userID string, claims interface{}) (string, error)

CreateCustomToken creates a custom token used for client to authenticate with firebase server using signInWithCustomToken See https://firebase.google.com/docs/auth/admin/create-custom-tokens

func (*Auth) CreateUser

func (auth *Auth) CreateUser(ctx context.Context, user *User) (string, error)

CreateUser creates an user and return created user id if not provides UserID, firebase server will auto generate it

func (*Auth) DeleteUser

func (auth *Auth) DeleteUser(ctx context.Context, userID string) error

DeleteUser deletes an user by user id

func (*Auth) GetUser

func (auth *Auth) GetUser(ctx context.Context, uid string) (*UserRecord, error)

GetUser retrieves an user by user id

func (*Auth) GetUserByEmail

func (auth *Auth) GetUserByEmail(ctx context.Context, email string) (*UserRecord, error)

GetUserByEmail retrieves user by email

func (*Auth) GetUserByPhoneNumber added in v0.0.4

func (auth *Auth) GetUserByPhoneNumber(ctx context.Context, phoneNumber string) (*UserRecord, error)

GetUserByPhoneNumber retrieves user by phoneNumber

func (*Auth) GetUsers

func (auth *Auth) GetUsers(ctx context.Context, userIDs []string) ([]*UserRecord, error)

GetUsers retrieves users by user ids

func (*Auth) GetUsersByEmail

func (auth *Auth) GetUsersByEmail(ctx context.Context, emails []string) ([]*UserRecord, error)

GetUsersByEmail retrieves users by emails

func (*Auth) GetUsersByPhoneNumber added in v0.0.4

func (auth *Auth) GetUsersByPhoneNumber(ctx context.Context, phoneNumbers []string) ([]*UserRecord, error)

GetUsersByPhoneNumber retrieves users by phoneNumber

func (*Auth) ListUsers

func (auth *Auth) ListUsers(maxResults int64) *ListAccountCursor

ListUsers creates list account cursor for retrieves accounts MaxResults can change later after create cursor

func (*Auth) SendPasswordResetEmail

func (auth *Auth) SendPasswordResetEmail(ctx context.Context, email string) error

SendPasswordResetEmail sends password reset for the given user Only useful for the Email/Password provider

func (*Auth) UpdateUser

func (auth *Auth) UpdateUser(ctx context.Context, user *User) error

UpdateUser updates an existing user

func (*Auth) VerifyAuthCallbackURI added in v0.0.2

func (auth *Auth) VerifyAuthCallbackURI(ctx context.Context, callbackURI string, sessionID string) (*UserInfo, error)

VerifyAuthCallbackURI verifies callback uri after user redirect back from CreateAuthURI returns UserInfo if success

func (*Auth) VerifyIDToken

func (auth *Auth) VerifyIDToken(idToken string) (*Token, error)

VerifyIDToken validates given idToken return Claims for that token only valid token See https://firebase.google.com/docs/auth/admin/verify-id-tokens

func (*Auth) VerifyPassword added in v0.0.2

func (auth *Auth) VerifyPassword(ctx context.Context, email, password string) (string, error)

VerifyPassword verifies given email and password, return user id if success

type CancelFunc

type CancelFunc func()

CancelFunc is the function for cancel "On"

type ChildSnapshot

type ChildSnapshot struct {
	PrevChildKey string
}

ChildSnapshot type

type DataSnapshot

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

DataSnapshot type

func (*DataSnapshot) Bytes

func (snapshot *DataSnapshot) Bytes() []byte

Bytes returns snapshot raw data

func (*DataSnapshot) Exists

func (snapshot *DataSnapshot) Exists() bool

Exists returns true if this DataSnapshot contains any data

func (*DataSnapshot) Key

func (snapshot *DataSnapshot) Key() string

Key returns the location of this DataSnapshot

func (*DataSnapshot) Ref

func (snapshot *DataSnapshot) Ref() *Reference

Ref returns the Reference for the location generated this DataSnapshot

func (*DataSnapshot) Val

func (snapshot *DataSnapshot) Val(v interface{}) error

Val extracts a value from a DataSnapshot

type Database

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

Database type

func (*Database) GoOffline added in v0.0.3

func (database *Database) GoOffline()

GoOffline Disconnects from the server (all Database operations will be completed offline).

See https://firebase.google.com/docs/reference/admin/node/admin.database.Database#goOffline

func (*Database) GoOnline added in v0.0.3

func (database *Database) GoOnline()

GoOnline Reconnects to the server and synchronizes the offline Database state with the server state.

See https://firebase.google.com/docs/reference/admin/node/admin.database.Database#goOnline

func (*Database) Ref

func (database *Database) Ref(path string) *Reference

Ref returns a Reference representing the location in the Database corresponding to the provided path. If no path is provided, the Reference will point to the root of the Database. See https://firebase.google.com/docs/reference/admin/node/admin.database.Database#ref

func (*Database) RefFromURL

func (database *Database) RefFromURL(url string) (*Reference, error)

RefFromURL returns a Reference representing the location in the Database corresponding to the provided Firebase URL.

An error is returned if the URL is not a valid Firebase Database URL or it has a different domain than the current Database instance.

Note that all query parameters (orderBy, limitToLast, etc.) are ignored and are not applied to the returned Reference. See https://firebase.google.com/docs/reference/admin/node/admin.database.Database#refFromURL

type ErrInvalidMessage added in v0.0.3

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

ErrInvalidMessage is the invalid Message error

func (*ErrInvalidMessage) Error added in v0.0.3

func (err *ErrInvalidMessage) Error() string

Error implements error interface

type ErrTokenInvalid

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

ErrTokenInvalid is the invalid token error

func (*ErrTokenInvalid) Error

func (err *ErrTokenInvalid) Error() string

Error implements error interface

type FCM added in v0.0.3

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

FCM type

func (*FCM) NewFcmSendEndpoint added in v0.0.3

func (fcm *FCM) NewFcmSendEndpoint(endpoint string)

NewFcmSendEndpoint set fcmSendEndpoint URL

func (*FCM) NewFcmTopicAddEndpoint added in v0.0.3

func (fcm *FCM) NewFcmTopicAddEndpoint(endpoint string)

NewFcmTopicAddEndpoint set fcmTopicAddEndpoint URL

func (*FCM) NewFcmTopicRemoveEndpoint added in v0.0.3

func (fcm *FCM) NewFcmTopicRemoveEndpoint(endpoint string)

NewFcmTopicRemoveEndpoint set fcmTopicRemoveEndpoint URL

func (*FCM) SendToCondition added in v0.0.3

func (fcm *FCM) SendToCondition(ctx context.Context, condition string, payload Message) (*Response, error)

SendToCondition Send a message to devices subscribed to the combination of topics specified by the provided condition. see https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_a_condition

func (*FCM) SendToDevice added in v0.0.3

func (fcm *FCM) SendToDevice(ctx context.Context, registrationToken string, payload Message) (*Response, error)

SendToDevice Send Message to individual device see https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_individual_devices

func (*FCM) SendToDeviceGroup added in v0.0.3

func (fcm *FCM) SendToDeviceGroup(ctx context.Context, notificationKey string, payload Message) (*Response, error)

SendToDeviceGroup Send Message to a device group see https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_a_device_group

func (*FCM) SendToDevices added in v0.0.3

func (fcm *FCM) SendToDevices(ctx context.Context, registrationTokens []string, payload Message) (*Response, error)

SendToDevices Send multicast Message to a list of devices see https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_individual_devices

func (*FCM) SendToTopic added in v0.0.3

func (fcm *FCM) SendToTopic(ctx context.Context, notificationKey string, payload Message) (*Response, error)

SendToTopic Send Message to a topic see https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_a_topic

func (*FCM) SubscribeDeviceToTopic added in v0.0.3

func (fcm *FCM) SubscribeDeviceToTopic(ctx context.Context, registrationToken string, topic string) (*Response, error)

SubscribeDeviceToTopic subscribe to a device to a topic by providing a registration token for the device to subscribe see https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#subscribe_to_a_topic

func (*FCM) SubscribeDevicesToTopic added in v0.0.3

func (fcm *FCM) SubscribeDevicesToTopic(ctx context.Context, registrationTokens []string, topic string) (*Response, error)

SubscribeDevicesToTopic subscribe devices to a topic by providing a registrationtokens for the devices to subscribe see https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#subscribe_to_a_topic

func (*FCM) UnSubscribeDeviceFromTopic added in v0.0.3

func (fcm *FCM) UnSubscribeDeviceFromTopic(ctx context.Context, registrationToken string, topic string) (*Response, error)

UnSubscribeDeviceFromTopic Unsubscribe a device to a topic by providing a registration token for the device to unsubscribe see https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#unsubscribe_from_a_topic

func (*FCM) UnSubscribeDevicesFromTopic added in v0.0.3

func (fcm *FCM) UnSubscribeDevicesFromTopic(ctx context.Context, registrationTokens []string, topic string) (*Response, error)

UnSubscribeDevicesFromTopic Unsubscribe devices to a topic by providing a registrationtokens for the devices to unsubscribe see https://firebase.google.com/docs/cloud-messaging/admin/manage-topic-subscriptions#unsubscribe_from_a_topic

type ListAccountCursor

type ListAccountCursor struct {
	MaxResults int64
	// contains filtered or unexported fields
}

ListAccountCursor type

func (*ListAccountCursor) Next

func (cursor *ListAccountCursor) Next(ctx context.Context) ([]*UserRecord, error)

Next retrieves next users from cursor which limit to MaxResults then move cursor to the next users

type Message added in v0.0.3

type Message struct {

	// To this parameter specifies the recipient of a message.
	//
	// The value can be a device's registration token, a device group's notification key, or a single topic
	// (prefixed with /topics/). To send to multiple topics, use the condition parameter.
	To string `json:"to,omitempty"`

	// This parameter specifies the recipient of a multicast message, a message sent to more than
	// one registration token.
	//
	// The value should be an array of registration tokens to which to send the multicast message.
	// The array must contain at least 1 and at most 1000 registration tokens. To send a message to a
	// single device, use the to parameter.
	//
	// Multicast messages are only allowed using the HTTP JSON format.
	RegistrationIDs []string `json:"registration_ids,omitempty"`

	// This parameter specifies a logical expression of conditions that determine the message target.
	//
	// Supported condition: Topic, formatted as "'yourTopic' in topics". This value is case-insensitive.
	//
	// Supported operators: &&, ||. Maximum two operators per topic message supported.
	Condition string `json:"condition,omitempty"`

	// This parameter identifies a group of messages (e.g., with collapse_key: "Updates
	// Available") that can be collapsed, so that only the last message gets sent when delivery can
	// be resumed. This is intended to avoid sending too many of the same messages when the
	// device comes back online or becomes active.
	//
	// Note that there is no guarantee of the order in which messages get sent.
	//
	// Note: A maximum of 4 different collapse keys is allowed at any given time. This means a FCM
	// connection server can simultaneously store 4 different send-to-sync messages per client app. If
	// you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server
	// will keep.
	CollapseKey string `json:"collapse_key,omitempty"`

	// Sets the priority of the message. Valid values are "normal" and "high." On iOS, these correspond
	// to APNs priorities 5 and 10.
	//
	// By default, notification messages are sent with high priority, and data messages are sent with
	// normal priority. Normal priority optimizes the client app's battery consumption and should be
	// used unless immediate delivery is required. For messages with normal priority, the app may
	// receive the message with unspecified delay.
	//
	// When a message is sent with high priority, it is sent immediately, and the app can wake a
	// sleeping device and open a network connection to your server.
	//
	// For more information, see Setting the priority of a message.
	// See https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message
	Priority string `json:"priority,omitempty"`

	// On iOS, use this field to represent content-available in the APNs payload. When a
	// notification or message is sent and this is set to true, an inactive client app is awoken. On
	// Android, data messages wake the app by default. On Chrome, currently not supported.
	ContentAvailable bool `json:"content_available,omitempty"`

	// Currently for iOS 10+ devices only. On iOS, use this field to represent mutable-content in the
	// APNS payload. When a notification is sent and this is set to true, the content of the notification
	// can be modified before it is displayed, using a Notification Service app extension. This
	// parameter will be ignored for Android and web.
	// See https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension
	MutableContent bool `json:"mutable_content,omitempty"`

	// This parameter specifies how long (in seconds) the message should be kept in FCM storage if
	// the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4
	// weeks. For more information, see Setting the lifespan of a message.
	// See https://firebase.google.com/docs/cloud-messaging/concept-options#ttl
	TimeToLive int `json:"time_to_live,omitempty"`

	// This parameter specifies the package name of the application where the registration tokens
	// must match in order to receive the message.
	RestrictedPackageName string `json:"restricted_package_name,omitempty"`

	// This parameter, when set to true, allows developers to test a request without actually sending
	// a message.
	//
	// The default value is false.
	DryRun bool `json:"dry_run,omitempty"`

	// Data parameter specifies the custom key-value pairs of the message's payload.
	//
	// For example, with data:{"score":"3x1"}:
	//
	// On iOS, if the message is sent via APNS, it represents the custom data fields.
	// If it is sent via FCM connection server, it would be represented as key value dictionary
	// in AppDelegate application:didReceiveRemoteNotification:.
	//
	// On Android, this would result in an intent extra named score with the string value 3x1.
	//
	// The key should not be a reserved word ("from" or any word starting with "google" or "gcm").
	// Do not use any of the words defined in this table (such as collapse_key).
	//
	// Values in string types are recommended. You have to convert values in objects
	// or other non-string data types (e.g., integers or booleans) to string.
	//
	Data interface{} `json:"data,omitempty"`

	// This parameter specifies the predefined, user-visible key-value pairs of the notification payload.
	// See Notification payload support for detail. For more information about notification message
	// and data message options, see Message types.
	Notification Notification `json:"notification,omitempty"`
}

Message is the FCM message See https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

func (*Message) Validate added in v0.0.3

func (payload *Message) Validate() error

Validate returns an error if the payload message is not valid.

type Notification added in v0.0.3

type Notification struct {

	// The notification's title.
	//
	// This field is not visible on iOS phones and tablets.
	Title string `json:"title,omitempty"`

	// The notification's body text.
	Body string `json:"body,omitempty"`

	// The notification's channel id (new in Android O).
	// See https://developer.android.com/preview/features/notification-channels.html
	//
	// The app must create a channel with this ID before any notification with this key is received.
	//
	// If you don't send this key in the request, or if the channel id provided has not yet been
	// created by your app, FCM uses the channel id specified in your app manifest.
	AndroidChannelID string `json:"android_channel_id,omitempty"`

	// The notification's icon.
	//
	// Sets the notification icon to myicon for drawable resource myicon. If you don't send this
	// key in the request, FCM displays the launcher icon specified in your app manifest.
	Icon string `json:"icon,omitempty"`

	// The sound to play when the device receives the notification.
	//
	// Sound files can be in the main bundle of the client app or in the Library/Sounds folder of the
	// app's data container. See the iOS Developer Library for more information.
	// See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10
	Sound string `json:"sound,omitempty"`

	// The value of the badge on the home screen app icon.
	//
	// If not specified, the badge is not changed.
	//
	// If set to 0, the badge is removed.
	Badge string `json:"badge,omitempty"`

	// Identifier used to replace existing notifications in the notification drawer.
	//
	// If not specified, each request creates a new notification.
	//
	// If specified and a notification with the same tag is already being shown, the new
	// notification replaces the existing one in the notification drawer.
	Tag string `json:"tag,omitempty"`

	// The notification's icon color, expressed in #rrggbb format.
	Color string `json:"color,omitempty"`

	// The action associated with a user click on the notification.
	//
	// If specified, an activity with a matching intent filter is launched when a user clicks on the
	// notification.
	ClickAction string `json:"click_action,omitempty"`

	// The key to the body string in the app's string resources to use to localize the body text to
	// the user's current localization.
	//
	// See String Resources for more information.
	// https://developer.android.com/guide/topics/resources/string-resource.html
	BodyLocKey string `json:"body_loc_key,omitempty"`

	// Variable string values to be used in place of the format specifiers in body_loc_key to use
	// to localize the body text to the user's current localization.
	//
	// See Formatting and Styling for more information.
	// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
	BodyLocArgs string `json:"body_loc_args,omitempty"`

	// The key to the title string in the app's string resources to use to localize the title text to
	// the user's current localization.
	//
	// See String Resources for more information.
	// https://developer.android.com/guide/topics/resources/string-resource.html
	TitleLocKey string `json:"title_loc_key,omitempty"`

	// Variable string values to be used in place of the format specifiers in title_loc_key to use
	// to localize the title text to the user's current localization.
	//
	// See Formatting and Styling for more information.
	// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
	TitleLocArgs string `json:"title_loc_args,omitempty"`
}

Notification notification message payload

type OldChildSnapshot

type OldChildSnapshot struct {
}

OldChildSnapshot type

type Query

type Query interface {
	Ref() *Reference
	EndAt(value interface{}) Query
	EqualTo(value interface{}) Query
	IsEqual(other Query) bool
	LimitToFirst(limit int) Query
	LimitToLast(limit int) Query
	OrderByChild(path interface{}) Query
	OrderByKey() Query
	OrderByPriority() Query
	OrderByValue() Query
	StartAt(value interface{}) Query
	OnValue(event chan *DataSnapshot) CancelFunc
	OnChildAdded(event chan *ChildSnapshot) CancelFunc
	OnChildRemoved(event chan *OldChildSnapshot) CancelFunc
	OnChildChanged(event chan *ChildSnapshot) CancelFunc
	OnChildMoved(event chan *ChildSnapshot) CancelFunc
	OnceValue() (*DataSnapshot, error)
	OnceChildAdded() *ChildSnapshot
	OnceChildRemove() *OldChildSnapshot
	OnceChildChanged() *ChildSnapshot
	OnceChildMoved() *ChildSnapshot
	String() string
}

Query is the query interface

type Reference

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

Reference represents a specific location in Database

func (Reference) Child

func (ref Reference) Child(path string) *Reference

Child returns a Reference for relative path

func (Reference) EndAt

func (ref Reference) EndAt(value interface{}) Query

EndAt implements Query interface

func (Reference) EqualTo

func (ref Reference) EqualTo(value interface{}) Query

EqualTo implements Query interface

func (*Reference) IsEqual

func (ref *Reference) IsEqual(other Query) bool

IsEqual returns true if current and provided query is the same location, same query params, and same App instance

func (*Reference) Key

func (ref *Reference) Key() string

Key returns the last path of Reference

func (Reference) LimitToFirst

func (ref Reference) LimitToFirst(limit int) Query

LimitToFirst implements Query interface

func (Reference) LimitToLast

func (ref Reference) LimitToLast(limit int) Query

LimitToLast implements Query interface

func (*Reference) OnChildAdded

func (ref *Reference) OnChildAdded(event chan *ChildSnapshot) CancelFunc

OnChildAdded implements Query interface

func (*Reference) OnChildChanged

func (ref *Reference) OnChildChanged(event chan *ChildSnapshot) CancelFunc

OnChildChanged implements Query interface

func (*Reference) OnChildMoved

func (ref *Reference) OnChildMoved(event chan *ChildSnapshot) CancelFunc

OnChildMoved implements Query interface

func (*Reference) OnChildRemoved

func (ref *Reference) OnChildRemoved(event chan *OldChildSnapshot) CancelFunc

OnChildRemoved implements Query interface

func (*Reference) OnValue

func (ref *Reference) OnValue(event chan *DataSnapshot) CancelFunc

OnValue implements Query interface

func (*Reference) OnceChildAdded

func (ref *Reference) OnceChildAdded() *ChildSnapshot

OnceChildAdded implements Query interface

func (*Reference) OnceChildChanged

func (ref *Reference) OnceChildChanged() *ChildSnapshot

OnceChildChanged implements Query interface

func (*Reference) OnceChildMoved

func (ref *Reference) OnceChildMoved() *ChildSnapshot

OnceChildMoved implements Query interface

func (*Reference) OnceChildRemove

func (ref *Reference) OnceChildRemove() *OldChildSnapshot

OnceChildRemove implements Query interface

func (*Reference) OnceValue

func (ref *Reference) OnceValue() (*DataSnapshot, error)

OnceValue implements Query interface

func (Reference) OrderByChild

func (ref Reference) OrderByChild(path interface{}) Query

OrderByChild implements Query interface

func (Reference) OrderByKey

func (ref Reference) OrderByKey() Query

OrderByKey implements Query interface

func (Reference) OrderByPriority

func (ref Reference) OrderByPriority() Query

OrderByPriority implements Query interface

func (Reference) OrderByValue

func (ref Reference) OrderByValue() Query

OrderByValue implements Query interface

func (Reference) Parent

func (ref Reference) Parent() *Reference

Parent returns the parent location of Reference

func (Reference) Push

func (ref Reference) Push(value interface{}) (*Reference, error)

Push pushs data to current location

func (Reference) Ref

func (ref Reference) Ref() *Reference

Ref returns a copy

func (*Reference) Remove

func (ref *Reference) Remove() error

Remove removes data from current location

func (*Reference) Root

func (ref *Reference) Root() *Reference

Root returns the root location of database

func (*Reference) Set

func (ref *Reference) Set(value interface{}) error

Set writes data to current location

func (Reference) StartAt

func (ref Reference) StartAt(value interface{}) Query

StartAt implements Query interface

func (*Reference) String

func (ref *Reference) String() string

String returns absolute URL for this location

type Response added in v0.0.3

type Response struct {
	// Unique ID (number) identifying the multicast message.
	MulticastID int64 `json:"multicast_id"`

	// Number of messages that were processed without an error.
	Success int `json:"success"`

	// Number of messages that could not be processed.
	Failure int `json:"failure"`

	// Number of results that contain a canonical registration token. A canonical registration ID is the
	// registration token of the last registration requested by the client app. This is the ID that the server
	// should use when sending messages to the device.
	CanonicalIDs int `json:"canonical_ids"`

	// Array of objects representing the status of the messages processed. The objects are listed in the same
	// order as the request (i.e., for each registration ID in the request, its result is listed in the same index in
	// the response).
	//
	// message_id: String specifying a unique ID for each successfully processed message.
	//
	// registration_id: Optional string specifying the canonical registration token for the client app
	// that the message was processed and sent to. Sender should use this value as the registration token
	// for future requests. Otherwise, the messages might be rejected.
	//
	// error: String specifying the error that occurred when processing the message for the recipient. The
	// possible values can be found in table 9.
	// See https://firebase.google.com/docs/cloud-messaging/http-server-ref#table9
	Results []Result `json:"results"`
}

Response is the FCM server's response See https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

type Result added in v0.0.3

type Result struct {
	// The topic message ID when FCM has successfully received the request and will attempt to deliver to
	// all subscribed devices.
	MessageID string `json:"message_id"`

	// This parameter specifies the canonical registration token for the client app that the message was
	// processed and sent to. Sender should replace the registration token with this value on future
	// requests; otherwise, the messages might be rejected.
	RegistrationID string `json:"registration_id"`

	// Error that occurred when processing the message. The possible values can be found in table 9.
	Error error `json:"error"`
}

Result representing the status of the messages processed. See https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

func (*Result) UnmarshalJSON added in v0.0.3

func (r *Result) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

type Token added in v0.0.5

type Token struct {
	Issuer        string `json:"iss"`
	Name          string `json:"name"`
	ID            string `json:"id"`
	Audience      string `json:"aud"`
	AuthTime      int64  `json:"auth_time"`
	UserID        string `json:"user_id"`
	Subject       string `json:"sub"`
	IssuedAt      int64  `json:"iat"`
	ExpiresAt     int64  `json:"exp"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	PhoneNumber   string `json:"phone_number"`
	Firebase      struct {
		Identities struct {
			Phone []string `json:"phone"`
			Email []string `json:"email"`
		} `json:"identities"`
		SignInProvider string `json:"sign_in_provider"`
	} `json:"firebase"`
}

Token is the firebase access token

func (*Token) Valid added in v0.0.5

func (t *Token) Valid() error

Valid implements jwt-go Claims interface

type Topic added in v0.0.3

type Topic struct {

	// To this parameter specifies the The topic name.
	//
	To string `json:"to,omitempty"`

	// This parameter specifies The array of IID tokens for the app instances you want to add or remove
	RegistrationTokens []string `json:"registration_tokens,omitempty"`
}

Topic is the FCM topic See https://developers.google.com/instance-id/reference/server#manage_relationship_maps_for_multiple_app_instances

func (*Topic) Validate added in v0.0.3

func (payload *Topic) Validate() error

Validate returns an error if the payload topic is not valid.

type UpdateAccount

type UpdateAccount struct {
	// UserID is the existing user id to update
	UserID        string `json:"localId,omitempty"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"emailVerified,omitempty"`
	Password      string `json:"password,omitempty"`
	DisplayName   string `json:"displayName,omitempty"`
	PhotoURL      string `json:"photoUrl,omitempty"`
	Disabled      bool   `json:"disableUser,omitempty"`
}

UpdateAccount use for update existing account

type User

type User struct {
	UserID        string
	Email         string
	EmailVerified bool
	Password      string
	DisplayName   string
	PhotoURL      string
	PhoneNumber   string
	Disabled      bool
}

User use for create new user use Password when create user (plain text) use RawPassword when update user (hashed password)

type UserInfo

type UserInfo struct {
	// The user identifier for the linked provider.
	UserID string
	// The email for the linked provider.
	Email string
	// The display name for the linked provider.
	DisplayName string
	// The phone number for the linked provider.
	PhoneNumber string
	// The photo URL for the linked provider.
	PhotoURL string
	// The linked provider ID (for example, "google.com" for the Google provider).
	ProviderID string
}

UserInfo is the user provider information See https://firebase.google.com/docs/reference/functions/functions.auth.UserInfo

type UserMetadata

type UserMetadata struct {
	// The date the user was created.
	CreatedAt time.Time
	// The date the user last signed in.
	LastSignedInAt time.Time
}

UserMetadata is the metadata for user See https://firebase.google.com/docs/reference/functions/functions.auth.UserMetadata

type UserRecord

type UserRecord struct {
	// The user's uid, unique to the Firebase project
	UserID string
	// The user's primary email, if set.
	Email string
	// Whether or not the user's primary email is verified.
	EmailVerified bool
	// The user's display name.
	DisplayName string
	// The user's primary phone number.
	PhoneNumber string
	// The user's photo URL.
	PhotoURL string
	// Whether or not the user is disabled: true for disabled; false for enabled.
	Disabled bool
	//Additional metadata about the user.
	Metadata UserMetadata
	// An array of providers (for example, Google, Facebook) linked to the user.
	ProviderData []*UserInfo
}

UserRecord is the firebase authentication user See https://firebase.google.com/docs/reference/functions/functions.auth.UserRecord

Jump to

Keyboard shortcuts

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