init
This commit is contained in:
78
internal/auth/google.go
Normal file
78
internal/auth/google.go
Normal file
@@ -0,0 +1,78 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user