Skip to content

Instantly share code, notes, and snippets.

@voidfiles
Created March 11, 2020 02:30
Show Gist options
  • Save voidfiles/a3566637bc6a446678691bb4ad8f3fc7 to your computer and use it in GitHub Desktop.
Save voidfiles/a3566637bc6a446678691bb4ad8f3fc7 to your computer and use it in GitHub Desktop.
Create a go lang firestore test connection with custom JWT claims
package main
type TestingToken struct {
jwt string
}
func (t token) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"authorization": "bearer " + t.token,
}, nil
}
func (t token) RequireTransportSecurity() bool {
return false
}
func createInsecureJWT(uid, role string) TestingToken {
header := `{"alg":"none","kid":"fakekid","typ":"JWT"}`
body := fmt.Sprintf(`{"iat":%d,"eat":%d,"sub":"%s","uid":"%s","role":"%s"}`, time.Now().Unix(), time.Now().Unix()+10000, uid, uid, role)
jwt := fmt.Sprintf(
"%s.%s.%s",
base64.RawURLEncoding.EncodeToString([]byte(header)),
base64.RawURLEncoding.EncodeToString([]byte(body)),
"",
)
return TestingToken{jwt: t}
}
func getClient() *firestore.Client {
ctx := context.Background()
token := createInsecureJWT("ab", "admin")
conn, err := grpc.Dial(
os.Getenv("FIRESTORE_EMULATOR_HOST"),
grpc.WithInsecure(),
grpc.WithPerRPCCredentials(token),
)
if err != nil {
log.Fatal(err)
}
client, err := firestore.NewClient(
ctx,
"testproject",
option.WithGRPCConn(conn),
)
if err != nil {
log.Fatal(err)
}
return client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment