Skip to content

Commit

Permalink
use google.golang.org/api/option to init app (#47)
Browse files Browse the repository at this point in the history
* use google's option to init service account

* change fetch key to use app's http client
  • Loading branch information
acoshift authored Sep 9, 2017
1 parent 5526738 commit 0ac4300
Show file tree
Hide file tree
Showing 748 changed files with 593,740 additions and 51 deletions.
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ before_install:
- go get github.com/mattn/goveralls

script:
- mkdir -p private
- echo $SERVICE_ACCOUNT > private/service_account.json
- $HOME/gopath/bin/goveralls -service=travis-ci
28 changes: 23 additions & 5 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
SERVICE_ACCOUNT=$(shell cat private/service_account.json)
PROJECT_ID=$(shell cat private/project_id)
DATABASE_URL=$(shell cat private/database_url)
API_KEY=$(shell cat private/api_key)

test:
env \
SERVICE_ACCOUNT='$(SERVICE_ACCOUNT)' \
PROJECT_ID='$(PROJECT_ID)' \
DATABASE_URL='$(DATABASE_URL)' \
API_KEY='$(API_KEY)' \
Expand Down
20 changes: 8 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,15 @@ package main
import (
"io/ioutil"

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

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

if err != nil {
panic(err)
Expand All @@ -132,16 +131,15 @@ package main
import (
"io/ioutil"

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

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

if err != nil {
panic(err)
Expand Down Expand Up @@ -171,16 +169,15 @@ package main
import (
"io/ioutil"

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

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

if err != nil {
panic(err)
Expand Down Expand Up @@ -227,18 +224,17 @@ package main
import (
"io/ioutil"

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

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

if err != nil {
panic(err)
Expand Down
45 changes: 30 additions & 15 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ package firebase
import (
"context"
"crypto/rsa"
"encoding/json"
"net/http"

jwtgo "github.com/dgrijalva/jwt-go"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
"google.golang.org/api/option"
"google.golang.org/api/transport"
)

// App holds information about application configuration
type App struct {
projectID string
jwtConfig *jwt.Config
privateKey *rsa.PrivateKey
clientEmail string
databaseURL string
databaseAuthVariable interface{}
client *http.Client
Expand All @@ -24,14 +27,15 @@ type App struct {
// AppOptions is the firebase app options for initialize app
type AppOptions struct {
ProjectID string
ServiceAccount []byte
DatabaseURL string
DatabaseAuthVariableOverride interface{}
APIKey string
}

// InitializeApp initializes firebase application with options
func InitializeApp(ctx context.Context, options AppOptions) (*App, error) {
func InitializeApp(ctx context.Context, options AppOptions, opts ...option.ClientOption) (*App, error) {
opts = append([]option.ClientOption{option.WithScopes(scopes...)}, opts...)

var err error

app := App{
Expand All @@ -41,21 +45,32 @@ func InitializeApp(ctx context.Context, options AppOptions) (*App, error) {
apiKey: options.APIKey,
}

if options.ServiceAccount != nil {
app.jwtConfig, err = google.JWTConfigFromJSON(options.ServiceAccount, scopes...)
if err != nil {
return nil, err
}
app.privateKey, err = jwtgo.ParseRSAPrivateKeyFromPEM(app.jwtConfig.PrivateKey)
if err != nil {
return nil, err
}
app.client = app.jwtConfig.Client(ctx)
} else {
app.client, err = google.DefaultClient(ctx, scopes...)
app.client, _, err = transport.NewHTTPClient(ctx, opts...)
if err != nil {
app.client = http.DefaultClient
}

cred, err := transport.Creds(ctx, opts...)
if err != nil {
return nil, err
}

if len(app.projectID) == 0 {
app.projectID = cred.ProjectID
}

// load private key from google credential
var serviceAccount struct {
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
}
json.Unmarshal(cred.JSON, &serviceAccount)
if len(serviceAccount.PrivateKey) > 0 {
app.privateKey, err = jwtgo.ParseRSAPrivateKeyFromPEM([]byte(serviceAccount.PrivateKey))
if err != nil {
return nil, err
}
app.clientEmail = serviceAccount.ClientEmail
}

return &app, nil
Expand Down
23 changes: 10 additions & 13 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@ package firebase_test

import (
"context"
"io/ioutil"
"os"
"testing"

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

type config struct {
ProjectID string `yaml:"projectId"`
ServiceAccount []byte `yaml:"serviceAccount"`
DatabaseURL string `yaml:"databaseURL"`
DatabaseAuthVariableOverride interface{} `yaml:"DatabaseAuthVariableOverride"`
APIKey string `yaml:"apiKey"`
Expand All @@ -23,19 +22,17 @@ func initApp(t *testing.T) *firebase.App {

// load config from env
c := config{
ProjectID: os.Getenv("PROJECT_ID"),
ServiceAccount: []byte(os.Getenv("SERVICE_ACCOUNT")),
DatabaseURL: os.Getenv("DATABASE_URL"),
APIKey: os.Getenv("API_KEY"),
ProjectID: os.Getenv("PROJECT_ID"),
DatabaseURL: os.Getenv("DATABASE_URL"),
APIKey: os.Getenv("API_KEY"),
}

// if service account is in separate file service_account.json
if len(c.ServiceAccount) <= 0 {
serviceAccount, _ := ioutil.ReadFile("private/service_account.json")
c.ServiceAccount = serviceAccount
}

app, _ := firebase.InitializeApp(context.Background(), firebase.AppOptions(c))
app, _ := firebase.InitializeApp(context.Background(), firebase.AppOptions{
ProjectID: c.ProjectID,
DatabaseURL: c.DatabaseURL,
DatabaseAuthVariableOverride: c.DatabaseAuthVariableOverride,
APIKey: c.APIKey,
}, option.WithCredentialsFile("private/service_account.json"))
return app
}

Expand Down
7 changes: 3 additions & 4 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"

Expand Down Expand Up @@ -49,8 +48,8 @@ func (auth *Auth) CreateCustomToken(userID string, claims interface{}) (string,
}
now := time.Now()
payload := &customClaims{
Issuer: auth.app.jwtConfig.Email,
Subject: auth.app.jwtConfig.Email,
Issuer: auth.app.clientEmail,
Subject: auth.app.clientEmail,
Audience: customTokenAudience,
IssuedAt: now.Unix(),
ExpiresAt: now.Add(time.Hour).Unix(),
Expand Down Expand Up @@ -115,7 +114,7 @@ func (auth *Auth) VerifyIDToken(idToken string) (*Token, error) {
func (auth *Auth) fetchKeys() error {
auth.keysMutex.Lock()
defer auth.keysMutex.Unlock()
resp, err := http.Get(keysEndpoint)
resp, err := auth.app.client.Get(keysEndpoint)
if err != nil {
return err
}
Expand Down
10 changes: 10 additions & 0 deletions vendor/golang.org/x/text/.gitattributes

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions vendor/golang.org/x/text/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions vendor/golang.org/x/text/AUTHORS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions vendor/golang.org/x/text/CONTRIBUTING.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions vendor/golang.org/x/text/CONTRIBUTORS

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 0ac4300

Please sign in to comment.