-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
74 lines (65 loc) · 1.81 KB
/
token.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/int128/kubelogin/pkg/di"
"github.com/int128/kubelogin/pkg/infrastructure/browser"
"github.com/int128/kubelogin/pkg/infrastructure/clock"
"github.com/int128/kubelogin/pkg/infrastructure/logger"
)
type ExecCredentialConfig struct {
Kind string `json:"kind"`
APIVersion string `json:"apiVersion"`
Spec struct {
Interactive bool `json:"interactive"`
} `json:"spec"`
Status struct {
ExpirationTimestamp string `json:"expirationTimestamp"`
Token string `json:"token"`
} `json:"status"`
}
func GetToken() (string, error) {
// Create a pipe
r, w, err := os.Pipe()
if err != nil {
return "", fmt.Errorf("failed to create pipe: %w", err)
}
defer r.Close()
defer w.Close()
// Create a Cmd instance
clockReal := &clock.Real{}
loggerInterface := logger.New()
browserBrowser := &browser.Browser{}
cmdInterface := di.NewCmdForHeadless(clockReal, os.Stdin, w, loggerInterface, browserBrowser)
// Perform OIDC login
args := []string{
"oidc-login",
"get-token",
"--oidc-issuer-url=https://id.snucse.org/o",
"--oidc-client-id=kubernetes-oidc",
"--oidc-client-secret=kubernetes-oidc",
"--oidc-use-pkce",
}
version := "HEAD"
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
code := cmdInterface.Run(ctx, args, version)
if code != 0 {
return "", fmt.Errorf("failed to get token. Exit code: %d", code)
}
// Read the token from the pipe
data, err := io.ReadAll(r)
if err != nil {
return "", fmt.Errorf("failed to read token: %w", err)
}
// Parse the result in JSON format
var result ExecCredentialConfig
if err := json.Unmarshal(data, &result); err != nil {
return "", fmt.Errorf("failed to parse token: %w", err)
}
return result.Status.Token, nil
}