Files
go-ohif-proxy/internal/auth/google.go
2025-04-07 11:14:18 +07:00

79 lines
2.1 KiB
Go

package auth
import (
"context"
"fmt"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/healthcare/v1"
"google.golang.org/api/option"
)
// TODO: Ganti Auth dengan lib Goth
// GoogleClient handles authentication with Google APIs
type GoogleClient struct {
credentialsPath string
tokenSource *google.Credentials
}
// NewGoogleClient creates a new Google authentication client
func NewGoogleClient(credentialsPath string) (*GoogleClient, error) {
client := &GoogleClient{
credentialsPath: credentialsPath,
}
// Initialize on creation to validate credentials
if _, err := client.getToken(); err != nil {
return nil, fmt.Errorf("failed to initialize Google client: %w", err)
}
return client, nil
}
// GetAccessToken returns a valid access token for Google APIs
func (c *GoogleClient) GetAccessToken() (string, error) {
tokenSource, err := c.getToken()
if err != nil {
return "", err
}
// Retrieve the token using the Token() method
token, err := tokenSource.Token()
if err != nil {
return "", fmt.Errorf("failed to retrieve token: %w", err)
}
return token.AccessToken, nil
}
// GetHealthcareClient returns a configured Healthcare API client
func (c *GoogleClient) GetHealthcareClient(ctx context.Context) (*healthcare.Service, error) {
opts := []option.ClientOption{
option.WithCredentialsFile(c.credentialsPath),
option.WithScopes(healthcare.CloudPlatformScope),
}
return healthcare.NewService(ctx, opts...)
}
// getToken retrieves a token from the credentials file
func (c *GoogleClient) getToken() (oauth2.TokenSource, error) { // Change return type to oauth2.TokenSource
if c.tokenSource != nil {
return c.tokenSource.TokenSource, nil // Access the TokenSource field
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
credentials, err := google.FindDefaultCredentials(ctx, healthcare.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("failed to get default credentials: %w", err)
}
c.tokenSource = credentials
return credentials.TokenSource, nil // Return the TokenSource field
}