-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclient.go
More file actions
56 lines (46 loc) · 1.87 KB
/
client.go
File metadata and controls
56 lines (46 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package auth
import (
"context"
"fmt"
"os"
kernel "github.com/onkernel/kernel-go-sdk"
"github.com/onkernel/kernel-go-sdk/option"
"github.com/pterm/pterm"
)
// GetAuthenticatedClient returns a Kernel client with appropriate authentication
func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error) {
// Try to use API key first if available
apiKey := os.Getenv("KERNEL_API_KEY")
if apiKey != "" {
pterm.Debug.Println("Using API key authentication")
authOpts := append(opts, option.WithHeader("Authorization", "Bearer "+apiKey))
client := kernel.NewClient(authOpts...)
return &client, nil
}
// Fallback to OAuth tokens if no API key is available
tokens, err := LoadTokens()
if err == nil {
// Check if access token is expired and refresh if needed
if tokens.IsExpired() && tokens.RefreshToken != "" {
pterm.Debug.Println("Access token expired, attempting refresh...")
refreshedTokens, refreshErr := RefreshTokens(context.Background(), tokens)
if refreshErr != nil {
pterm.Warning.Printf("Failed to refresh tokens: %v\n", refreshErr)
pterm.Info.Println("Please run 'kernel login' to re-authenticate")
return nil, fmt.Errorf("expired credentials, please re-authenticate: %w", refreshErr)
}
// Save refreshed tokens
if saveErr := SaveTokens(refreshedTokens); saveErr != nil {
pterm.Warning.Printf("Failed to save refreshed tokens: %v\n", saveErr)
}
tokens = refreshedTokens
pterm.Debug.Println("Successfully refreshed access token")
}
// Use JWT token for authentication via Authorization header
authOpts := append(opts, option.WithHeader("Authorization", "Bearer "+tokens.AccessToken))
client := kernel.NewClient(authOpts...)
return &client, nil
}
// No authentication available
return nil, fmt.Errorf("no authentication available. Please run 'kernel login' or set KERNEL_API_KEY environment variable")
}