Git Product home page Git Product logo

firebase-admin-go's People

Contributors

178inaba avatar avishalom avatar bamnet avatar brokeyourbike avatar castor-rtzr avatar chemidy avatar doris-ge avatar ernsheong avatar functionary avatar fzambia avatar galadros avatar google-oss-bot avatar hiranya911 avatar jacobhayes avatar jasperkuperus avatar jessejacksonanz avatar jonathanedey avatar jprobinson avatar lahirumaramba avatar m1 avatar maku693 avatar michaljemala avatar palsivertsen avatar pragatimodi avatar rockwotj avatar rsgowman avatar samtstern avatar scruffyprodigy avatar shogo82148 avatar thatfiredev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-admin-go's Issues

FR: `messaging.Aps` implements custom MarshalJSON but no UnmarshalJSON

[REQUIRED] Step 2: Describe your environment

  • Operating System version: MacOS 10.14
  • Library version: v3.5.0
  • Firebase Product:messaging

[REQUIRED] Step 3: Describe the problem

messaging.Aps implements a custom JSON marshaler, causing the Go JSON marshaler to use the custom implementation. Since the custom marshaler mutates the data, the resulting data cannot be unmarshaled back into the struct.

This prevents preparing APNS payloads and storing them in a database or queue for later dispatch.

Steps to reproduce:

  1. Build an APNS Payload with a ThreadID
  2. Call json.Marshal(apnsPayload)
  3. Call json.Unmarshal(apnsPayload, &target)
  4. See that fields such as target.APNS.Payload.Aps.ThreadID is empty.

Relevant Code:

// MarshalJSON marshals an Aps into JSON (for internal use only).
func (a *Aps) MarshalJSON() ([]byte, error) {
	m := a.standardFields()
	for k, v := range a.CustomData {
		m[k] = v
	}
	return json.Marshal(m)
}

Solution:

Either make the custom JSON marshaler actually internal only by changing the names so that the Go JSON Marshaler cannot see the methods, or implement an unmarshaler

// UnmarshalJSON unmarshals an Aps from JSON (for internal use only).
func (a *Aps) UnmarshalJSON(data []byte) error {
	m := make(map[string]interface{})
	a.CustomData = make(map[string]interface{})
	err := json.Unmarshal(data, &m)
	if err != nil {
		return err
	}
	for k, v := range m {
		switch k {
		case "alert":
			if v != nil {
				switch alert := m["alert"].(type) {
				case interface{}:
					a.Alert = alert.(*ApsAlert)
				case string:
					a.AlertString = alert
				}
			}
		case "content-available":
			if v == 1 {
				a.ContentAvailable = true
			}
		case "mutable-content":
			if v == 1 {
				a.MutableContent = true
			}
		case "badge":
			if v != nil {
				floatFromMap := m["badge"].(float64)
				intFromMap := int(floatFromMap)
				intPointer := &intFromMap
				a.Badge = intPointer
			}

		case "sound":
			if v != nil {
				a.Sound = m["sound"].(string)
			}

		case "category":
			if v != nil {
				a.Category = m["category"].(string)
			}

		case "thread-id":
			if v != nil {
				a.ThreadID = m["thread-id"].(string)
			}

		default:
			a.CustomData[k] = v
		}
	}
	return nil
}

Installing Firebase Error

Environment
OS: macOS High Sierra 10.13.4
go version go1.8.3 darwin/amd64

Problem
I have an error when installing the SDK when I run the command:

go get firebase.google.com/go

I get

# google.golang.org/grpc/transport
src/google.golang.org/grpc/transport/http_util.go:570: f.fr.SetReuseFrames undefined (type *http2.Framer has no field or method SetReuseFrames)

When I build I get the exact same error as above.

go test -test.short firebase.google.com/go/...

I get

# google.golang.org/grpc/transport src/google.golang.org/grpc/transport/http_util.go:570: f.fr.SetReuseFrames undefined (type *http2.Framer has no field or method SetReuseFrames) FAIL firebase.google.com/go [build failed] FAIL firebase.google.com/go/auth [build failed] FAIL firebase.google.com/go/db [build failed] FAIL firebase.google.com/go/iid [build failed] FAIL firebase.google.com/go/integration/auth [build failed] FAIL firebase.google.com/go/integration/db [build failed] FAIL firebase.google.com/go/integration/firestore [build failed] FAIL firebase.google.com/go/integration/iid [build failed]

Automatically retry 503 errors for RTDB

RTDB occasionally will service 503 status codes if the service is temporarily overloaded - currently the HTTPClient doesn't retry those operations, which are safe to be retried.

FR: Token verification clock skew

  • Operating System version: Win 10
  • Firebase SDK version: ?
  • Library version: v3.5.0
  • Firebase Product: auth

Steps to reproduce:

When I attempt to validate a token that was just created, it fails due to the token being created in the future. This is presumably due to my clock being a couple milliseconds behind the firebase servers.

Relevant Code:

My server code

                tokenStr := "something just posted from the browser"
		token, err = authClient.VerifyIDToken(context.Background(), tokenStr)
		if err != nil{
			log.Printf("invalid token: %s", err)
		}

Firebase auth.go code

          else if payload.IssuedAt > clk.Now().Unix() {
		err = fmt.Errorf("ID token issued at future timestamp: %d", payload.IssuedAt)
	} 

The firebase code does a strict clock comparison with no tolerance for time skew.

I've been able to mitigate this by wrapping the call in a function with a backoff retry, but it would be nice if there was a first class method for managing clock skew.


func checkTokenWithSkewBackoff(tokenStr string) (*auth.Token, error) {
	var token *auth.Token
	var err error
	for _, d := range []time.Duration{0 * time.Millisecond, 10 * time.Millisecond, 100 * time.Millisecond, 1000 * time.Millisecond} {
		time.Sleep(d)
		token, err = authClient.VerifyIDToken(context.Background(), tokenStr)
		if err == nil || ! strings.HasPrefix(err.Error(), "ID token issued at future timestamp") {
			return token, err
		}
	}
	return token, err
}

FR: Support Go 1.6

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a GitHub issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: N/A
  • Firebase SDK version: N/A
  • Library version: N/A
  • Firebase Product: all

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

To be compatible with all supported versions on AppEngine (and therefore be able to use in examples in https://github.com/GoogleCloudPlatform/golang-samples), it would be great to support Go 1.6. See previous discussion in #110.

Relevant Code:

Code using import "context", request.WithContext, subtests, etc. will need to be updated.

PR coming up.

CredentialsFromJSON fails without specifying scopes

Setting up firestorm using the google.CredentialsFromJSON is a bit messy. The scopes are specified in a internals files (which I'm not allowed to import). So I've had to copy and pate this code into mine to get the login to work.

scopes
// FirebaseScopes is the set of OAuth2 scopes used by the Admin SDK. var FirebaseScopes = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/datastore", "https://www.googleapis.com/auth/devstorage.full_control", "https://www.googleapis.com/auth/firebase", "https://www.googleapis.com/auth/identitytoolkit", "https://www.googleapis.com/auth/userinfo.email", }

FYI, It works without specifying the scopes when loading from file, but I'm loading my json from an encrypted location, and I don't want to write the unencrypted value to disk.

The following example works, 'j.ServiceAccount' contains json key file text, admit the scopes and it will fail to login.

cred, err := google.CredentialsFromJSON(ctx, j.ServiceAccount,
		"https://www.googleapis.com/auth/cloud-platform",
		"https://www.googleapis.com/auth/datastore",
		"https://www.googleapis.com/auth/devstorage.full_control",
		"https://www.googleapis.com/auth/firebase",
		"https://www.googleapis.com/auth/identitytoolkit",
		"https://www.googleapis.com/auth/userinfo.email")

	if err != nil {
	   //logging
	}

	sa := option.WithCredentials(cred)
	app, err := firebase.NewApp(ctx, nil, sa)
	if err != nil {
		 //logging
	}

	client, err := app.Firestore(ctx)
	if err != nil {
		 //logging
	}
	defer client.Close()

	_, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
		"first": "Ada",
		"last":  "Lovelace",
		"born":  1815,
	})
	if err != nil {
	    //logging
	}

FR: Code Examples

Unfortunately the majority of the documentation linked to in the README does not have Golang examples. Trying to do something as simple as read data from a reference isn't very clear, especially for people new to Go.

It would be fantastic and super helpful if you could include some basic examples in this repo.

Thanks!

Excessive dependencies for this package

Hello,

It appears that compiling this project requires pulling in quite a few dependencies. After looking at the code a bit, it appears that things like grpc, opencencus, and some of the cloud APIs should not be necessary for simple usage (I am only using this package to call VerifyIDToken).

Could this package be refactored so that users don't need to compile a ton of packages to get simple functionality?

SDK v3.0.0 requires cloud.google.com/go v0.22.0.

Firebase admin go SDK v3.0.0 requires cloud.google.com/go v0.22.0.

I saw this error because i have a constraint on cloud.google.com/go in my Gopkg.toml.

With v0.21.0 i have an error :

# myproject/vendor/cloud.google.com/go/firestore
vendor/cloud.google.com/go/firestore/query.go:163:40: too few values in struct initializer

Maybe it's time to add a Gopkg.toml to ensure compatibility ?
Or add a note in the Readme ?

How do you access the error code

I'm working at integrating Firebase messaging into our service. We are storing device tokens in our database and using that list to send notifications. For APNS (not using Firebase), we can get an api response that indicates the app has been uninstalled from the device and can remove the token from our database. I can see in the source code for this project that there is an error code for this (registrationTokenNotRegistered) but it is being returned in an error object that is in the internal package (FirebaseError) and returned as a generic error interface. Is there any way to access that Code property from the calling code? I'm new to Go so maybe I'm missing something obvious.

Thank you.

undefined: proto.InternalMessageInfo AND CredentialsFromJSON not declared by package google

  • Operating System version: Mac OS X 10.13.6 (17G65)
  • Firebase SDK version: 3.4.0
  • Library version: ?
  • Firebase Product: Messaging

Steps to reproduce:

I installed Firebase with dep ensure -update and the following entry in my Gopkg.toml:

[[constraint]]
  name = "firebase.google.com/go"
  version = "^v3.4.0"

Running build shows this error:

$ go build ./cmd/...
# github.com/foo/bar/vendor/google.golang.org/genproto/googleapis/rpc/status
vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:28: undefined: proto.InternalMessageInfo

Running gometalinter shows these errors:

vendor/google.golang.org/api/internal/creds.go:32:17:warning: CredentialsFromJSON not declared by package google (interfacer)
vendor/google.golang.org/api/internal/creds.go:32:17:warning: CredentialsFromJSON not declared by package google (unconvert)
vendor/google.golang.org/api/internal/creds.go:32:17:warning: error return value not checked (CredentialsFromJSON not declared by package google) (errcheck)
vendor/google.golang.org/api/internal/creds.go:32:17:warning: unused struct field CredentialsFromJSON not declared by package google (structcheck)

vendor/google.golang.org/api/internal/creds.go:39:17:warning: CredentialsFromJSON not declared by package google (interfacer)
vendor/google.golang.org/api/internal/creds.go:39:17:warning: CredentialsFromJSON not declared by package google (unconvert)
vendor/google.golang.org/api/internal/creds.go:39:17:warning: error return value not checked (CredentialsFromJSON not declared by package google) (errcheck)
vendor/google.golang.org/api/internal/creds.go:39:17:warning: unused struct field CredentialsFromJSON not declared by package google (structcheck)

vendor/google.golang.org/api/option/credentials_go19.go:24:23:warning: Credentials not declared by package google (interfacer)
vendor/google.golang.org/api/option/credentials_go19.go:24:23:warning: Credentials not declared by package google (unconvert)
vendor/google.golang.org/api/option/credentials_go19.go:24:23:warning: error return value not checked (Credentials not declared by package google) (errcheck)
vendor/google.golang.org/api/option/credentials_go19.go:24:23:warning: unused struct field Credentials not declared by package google (structcheck)

vendor/google.golang.org/api/option/credentials_go19.go:27:27:warning: Credentials not declared by package google (interfacer)
vendor/google.golang.org/api/option/credentials_go19.go:27:27:warning: Credentials not declared by package google (unconvert)
vendor/google.golang.org/api/option/credentials_go19.go:27:27:warning: error return value not checked (Credentials not declared by package google) (errcheck)
vendor/google.golang.org/api/option/credentials_go19.go:27:27:warning: unused struct field Credentials not declared by package google (structcheck)

vendor/google.golang.org/api/option/credentials_go19.go:30:36:warning: Credentials not declared by package google (interfacer)
vendor/google.golang.org/api/option/credentials_go19.go:30:36:warning: Credentials not declared by package google (unconvert)
vendor/google.golang.org/api/option/credentials_go19.go:30:36:warning: error return value not checked (Credentials not declared by package google) (errcheck)
vendor/google.golang.org/api/option/credentials_go19.go:30:36:warning: unused struct field Credentials not declared by package google (structcheck)

vendor/google.golang.org/api/transport/go19.go:28:71:warning: Credentials not declared by package google (interfacer)
vendor/google.golang.org/api/transport/go19.go:28:71:warning: Credentials not declared by package google (unconvert)
vendor/google.golang.org/api/transport/go19.go:28:71:warning: error return value not checked (Credentials not declared by package google) (errcheck)
vendor/google.golang.org/api/transport/go19.go:28:71:warning: unused struct field Credentials not declared by package google (structcheck)

vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:34:warning: error return value not checked (InternalMessageInfo not declared by package proto) (errcheck)
vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:34:warning: InternalMessageInfo not declared by package proto (interfacer)
vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:34:warning: InternalMessageInfo not declared by package proto (staticcheck)
vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:34:warning: InternalMessageInfo not declared by package proto (unconvert)
vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:34:warning: unused struct field InternalMessageInfo not declared by package proto (structcheck)

go get firebase.google.com/go ( install Firebase Admin Go SDK failed)

###: Describe the problem
try to setup firebase auth clinet and verify token on golang backend
follow https://firebase.google.com/docs/admin/setup

stop at #go get firebase.google.com/go

error message:

firebase.google.com/go/auth

../firebase.google.com/go/auth/auth.go:82: c.Creds.JSON undefined (type *google.DefaultCredentials has no field or method JSON)
../firebase.google.com/go/auth/auth.go:87: c.Creds.JSON undefined (type *google.DefaultCredentials has no field or method JSON)

: Describe of the environment

  • Operating System version: ubuntu 16.10
  • Firebase SDK version: 3.9.2
  • Firebase Product: auth

Steps to reproduce:

how to install this package

Relevant Code:

import (
	"fmt"
	firebase "firebase.google.com/go"
	"golang.org/x/net/context"
	"google.golang.org/api/option"
)
	//Auth Backend with firebase
	// firebaseClient, err = FirebaseClient()
	opt := option.WithCredentialsFile("firebase-credentials.json")
	app, err := firebase.NewApp(context.Background(), nil, opt)
	if err != nil {
		fmt.Println("failed auth firebase client", err.Error())
		return
	}
	client, err := app.Auth()
	if err != nil {
		return err
	}
	decoded, err := client.VerifyIDToken("eyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXX")
	if err != nil {
		fmt.Errorf("error verifying ID token: %v", err)
	}

	fmt.Printf("Verified ID token: %v\n", decoded)

Allow Users to Specify the Context when Accessing Individual Clients

Currently App holds on to a context.Context, and passes it to all internal packages that need it (e.g. auth.NewClient()). As we add more packages to this SDK, we might want to give users more control over the context passed into individual operations. Therefore functions like app.Auth() should accept a context, and use that instead of the one passed in when creating the App.

FR: CustomToken and VerifyIDToken Should Accept a Context

These APIs currently do not accept a context, which is not correct. In our next major release (3.x), we should change these to accept a context like the other APIs in this package. This is unfortunately a breaking change, and hence cannot be released anytime soon.

Messaging returns 'invalid-argument' when APNs and Data map

  • Operating System version: Google App Engine
  • Firebase SDK version: 3.1.0
  • Firebase Product: Messaging

Firebase cloud messaging client seems to throw an 'invalid-argument' error when Message struct contains both a Data map and an APNS Config.

Relevant Code:

&messaging.Message{
                 Token: ClientToken,
		Data: map[string]string{
			"type": "sms",
			"from": "xxxxxxxxxxx",
			"to":   "xxxxxxxxxxx",
		},
		APNS: &messaging.APNSConfig{
			Headers: map[string]string{
				"apns-priority": "10",
			},
			Payload: &messaging.APNSPayload{
				Aps: &messaging.Aps{
					Alert: &messaging.ApsAlert{
						Title: fmt.Sprintf("Text message - %s", fromFormatted),
						Body:  q.Get("Body"),
					},
					Sound:            "default",
					ContentAvailable: true,
				},
			},
		},
	})

Sending this message results in the following error:

request contains an invalid argument; code: invalid-argument

The notification is received successfully by removing the Data map as so:

&messaging.Message{
                 Token: ClientToken,
		APNS: &messaging.APNSConfig{
			Headers: map[string]string{
				"apns-priority": "10",
			},
			Payload: &messaging.APNSPayload{
				Aps: &messaging.Aps{
					Alert: &messaging.ApsAlert{
						Title: fmt.Sprintf("Text message - %s", fromFormatted),
						Body:  q.Get("Body"),
					},
					Sound:            "default",
					ContentAvailable: true,
				},
			},
		},
	})

Not sure whether this is the intended behaviour and explanation is missing from the docs, or this is not intended and a problem with the SDK. Currently I am only sending notifications to my iOS app, but in the case I need to send to multiple apps I believe I would need to add the CustomData to each notification type, eg. Android.Data, WebPush.Data, Aps.CustomData

No function to use existing instance of app/client?

i can't find a function to use existing instance of client/app,

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

do we initialized the instance everytime we want to use it,
i thought that we just initialized the instance once

Invalid endpoint URL for topic unsubscribe

This relates to messaging package, where topic unsubscribe action uses wrong op. This causes incorrect endpoint to be hit, i.e. iid/v1:batchAdd instead of iid/v1:batchRemove.

Issue when install package

Hi Firebase,
I using command go get firebase.google.com/go to install package, but it have some issue.

src/google.golang.org/genproto/googleapis/rpc/status/status.pb.go:114:28: undefined: proto.InternalMessageInfo

FR: Get IDTokens from test users

Is there any way to get ID tokens from test users without having to use the c++ sdk or the node client? Just curious for testing purposes. Mocking an auth flow would be super nice

Please provide a byte array option for firebase.NewApp

Describe your environment

  • Operating System version: _____Docker
  • Firebase SDK version: _____Go HEAD of master branch
  • Library version: _____Go HEAD of master branch
  • Firebase Product: _____ (auth, database, storage, etc) auth

Describe the problem

Please allow the credentials to be provided to "firebase.NewApp" as a byte array in addition to a file via the options. The reason I'm asking is because we store the file encrypted with KMS and would prefer not to write out the decrypted service account to a file and instead keep it in memory.

Steps to reproduce:

N/A

Relevant Code:

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

Installing Firebase Error

Environment

OS: macOS High Sierra 10.13.4
go version go1.10.1 darwin/amd64

Problem

I have an error when installing the SDK when I run the command:

go get firebase.google.com/go

I get:

# google.golang.org/api/internal
src/google.golang.org/api/internal/creds.go:36:10: undefined: google.CredentialsFromJSON

When I build I get the exact same error as above.

FR: Add subtitle for iOS push notifications

Describe your environment

  • Messaging/Notifications

Describe the problem

We cannot send push notifications with subtitle for iOS due to ApsAlert struct lacking a subtitle field.

FCM API and the APNS itself do support this field on iOS 9+ (and it's safely ignored on older versions).

Unable to set multiple client options

  • Operating System version: OSX 10.13.6
  • Firebase SDK version: Unable to determine
  • Firebase Product: Auth

Note: Running in GAE Standard dev environment under dev_appserver.py

I am attempting to verify firebase tokens, but I am not able to set up my ClientOption to use urlfetch by calling WithHTTPClient when I am already using WithCredentialsFile

See example:

gaeCtx := appengine.NewContext(r)

opt := option.WithCredentialsFile("/path/to/my-app-service-account-file.json")
// opt := option.WithHTTPClient(urlfetch.Client(gaeCtx)) <--- How do I set this as well as WithCredentialsFile?

app, err := firebase.NewApp(goStdCtx.Background(), nil, opt)
if err != nil {
  log.Errorf(gaeCtx, "unable to initialise firebase application")
}

client, err := app.Auth(gaeCtx)
if err != nil {
  log.Errorf(gaeCtx, "unable to initialise firebase authentication client")
}

...

I am aware that when I deploy to GAE I will not need WithCredentialsFile but I want to be able to set both WithCredentialsFile and WithHTTPClient when running in development

sender id does not match regisration token

I have an error

http error status: 403; reason: sender id does not match regisration token; code: mismatched-credential

everything made as said in documentation, i can send push notification from firebase web interface, but not from server.

my code is

func PushHandler(message <- chan Helpers.PushChannelMessage)  {
	log.Println("PushHandler INIT")
	ctx := context.Background()
	opt := option.WithCredentialsFile("XXXX.json")
	config := &firebase.Config{ProjectID: "XXXX"}
	app, err := firebase.NewApp(ctx, config, opt)
	if err != nil {
		log.Println(err)
		return
	}
	client, err := app.Messaging(ctx)
	for {
		c:= <- message
		fmt.Println("PushChan",c)
		if err == nil {
			message := &messaging.Message{
				Data: map[string]string{
					"score": "850",
					"time":  "2:45",
				},
				Token: c.Token,
			}
			response, err := client.SendDryRun(ctx, message)
			if err != nil {
				log.Println(err)
				continue
			}
			fmt.Println("Successfully sent message:", response)
		}else{
			log.Println("error pushchan ->>", err)
		}
	}
}

http.DefaultClient is not available in App Engine

  • Operating System version: Google App Engine
  • Firebase SDK version: 3.2.0
  • Firebase Product: Auth

http.DefaultClient is not available in App Engine

Steps to reproduce:

Import firebase into any application running in google app engine.

func init() {
  c := context.Background()
  app, err := firebase.NewApp(c, &firebase.Config{ProjectID: "example_id"})
  if err != nil {
    return nil, err
  }
  client, err := app.Auth(c)
  if err != nil {
    return nil, err
  }
  token := "example_token"
  _, err := a.client.VerifyIDToken(c, token)
}

Relevant Code:

	return &Client{	 	return &Client{
 		is:        is,
		keySource: newHTTPKeySource(idTokenCertURL, hc),	
 		projectID: conf.ProjectID,
 		signer:    signer,
 		version:   "Go/Admin/" + conf.Version,
 	}, nil

was changed to

	return &Client{	 	return &Client{
 		is:        is,
		keySource: newHTTPKeySource(idTokenCertURL, http.DefaultClient),
 		projectID: conf.ProjectID,
 		signer:    signer,
 		version:   "Go/Admin/" + conf.Version,
 	}, nil

1d2a52c#diff-3ba8fa87da15d764efcb8ea0c83f6e97R132

FR: Extend Or Customize Expiration of CustomToken + CustomTokenWithClaims

Looking at this section:

// CustomTokenWithClaims is similar to CustomToken, but in addition to the user ID, it also encodes
// all the key-value pairs in the provided map as claims in the resulting JWT.
func (c *Client) CustomTokenWithClaims(ctx context.Context, uid string, devClaims map[string]interface{}) (string, error) {
	iss, err := c.signer.Email(ctx)
	if err != nil {
		return "", err
	}

	if len(uid) == 0 || len(uid) > 128 {
		return "", errors.New("uid must be non-empty, and not longer than 128 characters")
	}

	var disallowed []string
	for _, k := range reservedClaims {
		if _, contains := devClaims[k]; contains {
			disallowed = append(disallowed, k)
		}
	}
	if len(disallowed) == 1 {
		return "", fmt.Errorf("developer claim %q is reserved and cannot be specified", disallowed[0])
	} else if len(disallowed) > 1 {
		return "", fmt.Errorf("developer claims %q are reserved and cannot be specified", strings.Join(disallowed, ", "))
	}

	now := clk.Now().Unix()
	info := &jwtInfo{
		header: jwtHeader{Algorithm: "RS256", Type: "JWT"},
		payload: &customToken{
			Iss:    iss,
			Sub:    iss,
			Aud:    firebaseAudience,
			UID:    uid,
			Iat:    now,
			Exp:    now + tokenExpSeconds,
			Claims: devClaims,
		},
	}
	return info.Token(ctx, c.signer)
}

Does it make sense for us to be able to adjust the expiration time?

Unable to set endpoint for messaging

I try to set the base url for the client library so that during testing I can run requests against a FCM mock instead of doing internet requests. However, even with the following code, I can see the attempts to reach the official base url:

ctx := context.Background()
opts := []option.ClientOption{option.WithEndpoint("http://localhost:1234/")}
// opts = append(opts, option.WithoutAuthentication())
app, _ := firebase.NewApp(ctx, nil, opts...)
c, _ := firebaseApp.Messaging(ctx)

_, _ = c.Send(cox, nil)
POST /v1/projects/dummy-project-id/messages:send HTTP/1.1
Host: fcm.googleapis.com
User-Agent: Go-http-client/1.1
Content-Length: 71
Content-Type: application/json
Accept-Encoding: gzip
{"message":{"notification":{"title":"foo","body":"bar"},"token":"123"}}
HTTP/2.0 401 Unauthorized
Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35"
Cache-Control: private
Content-Type: application/json; charset=UTF-8
Date: Mon, 05 Nov 2018 18:37:10 GMT
Server: ESF
Vary: Origin
Vary: X-Origin
Vary: Referer
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

Question about FcmErrorCode

environment

  • Firebase SDK version: v3.4.0
  • Firebase Product: messaging

question

I have looked FCM HTTP v1 API error response looks like:

HTTP/2.0 404 Not Found
Content-Type: application/json; charset=UTF-8
Date: Fri, 28 Sep 2018 07:27:19 GMT

{
  "error": {
    "code": 404,
    "message": "Requested entity was not found.",
    "status": "NOT_FOUND",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "UNREGISTERED"
      }
    ]
  }
}

Currently messaging/messaging.go is looked at details with expression: d.Type == "type.googleapis.com/google.firebase.fcm.v1.FcmErrorCode".
Is v1.FcmErrorCode key correct?
https://github.com/firebase/firebase-admin-go/blob/master/messaging/messaging.go#L628

FR - make Message Data interface{} instead map[string]string to allow other data types

Describe your environment

  • Firebase SDK version: 3.3.0
  • Firebase Product: Messaging/Notifications

Describe the problem

Steps to reproduce:

We cannot use reuse a struct in the message data and instead we create a new map[string]string to be send as Data of FCM Message Data . So we have to trim out boolean, int , float into string and reprocess them again on swift and android code from string to correct datatypes.

This is terrible approach unwrapping structs at golang code and wrapping back string json into android/iOS pojos in client code.

Relevant Code:

// TODO(you): code here to reproduce the problem
article := Article{}
article.Title = "Awww"
article.Message = "This is so much work."
article.Source = "New Delhi"
article.Debug = true
article.Version = 1

articleData := map[string]string{
		"debug"      :   "true",
		"version"    :   "1",
		"source"     :   article.Source,
		"title"      :   article.Title,
		"message" :   article.Message,
}
		
message := &messaging.Message{
		Data:         articleData,
		Topic:        "debug",
		Notification: &messaging.Notification{Title: article.Title, Body: article.Message},
	}


We should be instead be able to use 

message := &messaging.Message{
		Data:         article,
		Topic:        "debug",
		Notification: &messaging.Notification{Title: article.Title, Body: article.Message},
	}

FR: enable custom token creation on App Engine without a JSON credentials file

In the App Engine standard environment, the code could likely be much simpler and easier to configure if it relied on appengine.ServiceAccount and appengine.SignBytes to generate custom auth tokens.

I imagine this would require a refactor to accept a "context" for most methods and also some additional finagling to prevent duplicate code across build tags, but it would definitely get me to lean on this library more.

An example of using the GAE tools to generate a custom token: https://github.com/GoogleCloudPlatform/golang-samples/blob/master/docs/appengine/firebase/tictactoe/firebase.go#L45-L69

I'm definitely interested in helping out by working on a PR if there's interest in this functionality.

firebase.NewApp with credentials from memory instead of from file

Describe your environment

  • Operating System version: _____Docker
  • Firebase SDK version: _____Go HEAD of master branch
  • Library version: _____Go HEAD of master branch
  • Firebase Product: _____ (auth, database, storage, etc) auth

Describe the problem

Is there a way to provide the credentials to "firebase.NewApp" as a byte array instead of a file via option.WithCredentialsFile? The reason I'm asking is because we store the file encrypted with KMS and would prefer not to write out the decrypted service account to a file and instead keep it in memory.

Steps to reproduce:

N/A

Relevant Code:

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

FR: Support getting multiple user records at once by email

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a GitHub issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: -
  • Firebase SDK version: -
  • Library version: 2.7.0
  • Firebase Product: auth (auth, database, storage, etc)

[REQUIRED] Step 3: Describe the problem

Firebase auth admin SDK does not support getting multiple user records at once.

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

Relevant Code:

// TODO(you): code here to reproduce the problem

Old GCM tokens result in The credential used to authenticate this SDK does not have permission .....

whenever I try to send a notification with an old GCM token I get:

{"code":"messaging/mismatched-credential","message":"The credential used to authenticate this SDK does not have permission to send messages to the device corresponding to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project."}}}

When I use a normal FCM token it works fine. So there is actually no authentication issue.

If it does not matter if i use admin.messaging().sendToDevice(.. or admin.messaging().subscribeToTopic(.. In both the same error. No error when FCM token is used.

For now i have no idea how to still support old GCM tokens.

FR: Add channel ID to AndroidConfig

Describe your environment

  • Messaging/Notifications

Describe the problem

If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

If needed I can implement this feature.

auth/Client.VerifyIDToken should verify (some) fields before checking signature

Field validation in auth/Client.VerifyIDToken(), like checking Expires and IssuedAt, should be done before the, potentially expensive, operation verifyToken. Deep down verifyToken uses locking and issues a http request. Although this is not the biggest overhead, it would be nice if e.g. expired tokens where not dependent on sub-requests to Firebase API (an expired token is not valid no matter the signature)

Import context from golang.org/x/net

[REQUIRED] Step 2: Describe your environment

  • Operating System version: N/A
  • Firebase SDK version: N/A
  • Library version: Master
  • Firebase Product: all

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

go version 1.6
go get -u firebase.google.com/go

Log from a failed Travis build:

get "firebase.google.com/go": found meta tag main.metaImport{Prefix:"firebase.google.com/go", VCS:"git", RepoRoot:"https://github.com/firebase/firebase-admin-go"} at https://firebase.google.com/go?go-get=1
firebase.google.com/go (download)
package context: unrecognized import path "context" (import path does not begin with hostname)

https://travis-ci.org/GoogleCloudPlatform/golang-samples/jobs/351066691#L1064

Relevant Code:

import "context" should be import "golang.org/x/net/context".

This is mentioned in the v.2.5.0 changelog, but looks like there are some references remaining: https://github.com/firebase/firebase-admin-go/search?utf8=%E2%9C%93&q=context&type=.

This is blocking GoogleCloudPlatform/golang-samples#418.

I'll work on a PR.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.