connected-to-google

This commit is contained in:
mario
2025-04-07 15:46:07 +07:00
parent f340bc5916
commit 9b8e0260f3
15 changed files with 282 additions and 286 deletions

View File

@@ -3,6 +3,7 @@ package auth
import (
"context"
"fmt"
"os"
"time"
"golang.org/x/oauth2"
@@ -11,12 +12,10 @@ import (
"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
tokenSource oauth2.TokenSource
}
// NewGoogleClient creates a new Google authentication client
@@ -26,24 +25,33 @@ func NewGoogleClient(credentialsPath string) (*GoogleClient, error) {
}
// Initialize on creation to validate credentials
if _, err := client.getToken(); err != nil {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Try reading the credentials file
credBytes, err := os.ReadFile(credentialsPath)
if err != nil {
return nil, fmt.Errorf("failed to read credentials file: %w", err)
}
// Create credentials from the JSON key file
creds, err := google.CredentialsFromJSON(ctx, credBytes, healthcare.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("failed to initialize Google client: %w", err)
}
client.tokenSource = creds.TokenSource
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
}
_, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Retrieve the token using the Token() method
token, err := tokenSource.Token()
token, err := c.tokenSource.Token()
if err != nil {
return "", fmt.Errorf("failed to retrieve token: %w", err)
return "", fmt.Errorf("failed to get access token: %w", err)
}
return token.AccessToken, nil
@@ -58,21 +66,3 @@ func (c *GoogleClient) GetHealthcareClient(ctx context.Context) (*healthcare.Ser
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
}