|
| 1 | +package gcloud |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "golang.org/x/oauth2/google" |
| 6 | + "google.golang.org/api/idtoken" |
| 7 | + "google.golang.org/api/option" |
| 8 | + "google.golang.org/grpc/credentials/oauth" |
| 9 | +) |
| 10 | + |
| 11 | +// LoadGoogleCredentials loads the Google credentials |
| 12 | +func LoadGoogleCredentials(ctx context.Context) (*google.Credentials, error) { |
| 13 | + credentials, err := google.FindDefaultCredentials(ctx) |
| 14 | + if err != nil { |
| 15 | + return nil, FailedToLoadGoogleCredentialsError |
| 16 | + } |
| 17 | + return credentials, nil |
| 18 | +} |
| 19 | + |
| 20 | +// LoadServiceAccountCredentials loads the service account credentials |
| 21 | +func LoadServiceAccountCredentials( |
| 22 | + ctx context.Context, url string, credentials *google.Credentials, |
| 23 | +) (*oauth.TokenSource, error) { |
| 24 | + // Check if the credentials are nil |
| 25 | + if credentials == nil { |
| 26 | + return nil, NilGoogleCredentialsError |
| 27 | + } |
| 28 | + |
| 29 | + // Create a new token source |
| 30 | + tokenSource, err := idtoken.NewTokenSource( |
| 31 | + ctx, |
| 32 | + url, |
| 33 | + option.WithCredentials(credentials), |
| 34 | + ) |
| 35 | + if err != nil { |
| 36 | + return nil, FailedToCreateTokenSourceError |
| 37 | + } |
| 38 | + |
| 39 | + return &oauth.TokenSource{TokenSource: tokenSource}, nil |
| 40 | +} |
0 commit comments