Skip to content

Commit

Permalink
remove requirement for GOOGLE_APPLICATION_CREDENTIALS env var
Browse files Browse the repository at this point in the history
  • Loading branch information
jharshman committed May 24, 2023
1 parent d15814c commit 2c42792
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ $ curl https://raw.githubusercontent.com/jharshman/fwsync/master/install.sh | sh
## Usage

### Authentication
Communication to the GoogleAPIs requires setting the environment variable `GOOGLE_APPLICATION_CREDENTIALS`.
This variable should point to the path of your downloaded service account json. For example, `export GOOGLE_APPLICATION_CREDENTIALS=/Users/bob/bobserviceaccount.json`.
Communication to the GoogleAPIs requires either setting the environment variable `GOOGLE_APPLICATION_CREDENTIALS` or
alternatively running `gcloud auth application-default login`. If using the `GOOGLE_APPLICATION_CREDENTIALS` environment
variable, it must point to the full path to your downloaded service account json.

For example:

`$ export GOOGLE_APPLICATION_CREDENTIALS=/Users/bob/bobserviceaccount.json`

### Init
After installing, you can invoke the CLI by typing `fwsync` in your terminal.
Expand Down
16 changes: 6 additions & 10 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,30 @@ package auth

import (
"context"
"errors"
"os"
"sync"

"github.com/spf13/cobra"
"google.golang.org/api/compute/v1"
"google.golang.org/api/option"
)

var (
GoogleCloudAuthorizedClient *compute.Service
once sync.Once
)

// Auth returns the authentication function.
func Auth() func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
serviceAccountJSONPath := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
if serviceAccountJSONPath == "" {
return errors.New("missing environment variable GOOGLE_APPLICATION_CREDENTIALS")
}
return auth(serviceAccountJSONPath)
return auth()
}
}

func auth(svcAcctFile string) (authErr error) {
// auth will authenticate to the Google APIs using default methods.
// https://cloud.google.com/docs/authentication/application-default-credentials#personal
func auth() (authErr error) {
once.Do(func() {
var cc *compute.Service
cc, authErr = compute.NewService(context.Background(), option.WithCredentialsFile(svcAcctFile))
cc, authErr = compute.NewService(context.Background())
GoogleCloudAuthorizedClient = cc
})
return
Expand Down

0 comments on commit 2c42792

Please sign in to comment.