-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
172 lines (155 loc) · 4.44 KB
/
main.go
File metadata and controls
172 lines (155 loc) · 4.44 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/go-authgate/sdk-go/credstore"
"github.com/go-authgate/cli/tui"
"github.com/spf13/cobra"
)
// exitCodeError carries a non-zero exit code through Cobra's error chain
// without printing a redundant message (the command already wrote to stderr).
type exitCodeError int
func (e exitCodeError) Error() string { return "" }
func main() {
if err := buildRootCmd().Execute(); err != nil {
var exitErr exitCodeError
if errors.As(err, &exitErr) {
os.Exit(int(exitErr))
}
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func buildRootCmd() *cobra.Command {
rootCmd := &cobra.Command{
Use: "authgate-cli",
Short: "OAuth 2.0 authentication CLI",
Version: getVersion(),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := loadConfig()
uiManager := tui.SelectManager()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
resolveEndpoints(ctx, cfg)
if code := run(ctx, uiManager, cfg); code != 0 {
return exitCodeError(code)
}
return nil
},
}
registerFlags(rootCmd)
rootCmd.AddCommand(buildVersionCmd())
rootCmd.AddCommand(buildTokenCmd())
return rootCmd
}
func buildVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(getVersion())
},
}
}
func run(ctx context.Context, ui tui.Manager, cfg *AppConfig) int {
clientMode := "public (PKCE)"
if !cfg.IsPublicClient() {
clientMode = "confidential"
}
ui.ShowHeader(clientMode, cfg.ServerURL, cfg.ClientID)
var storage *credstore.Token
var flow string
// Try to reuse or refresh existing tokens.
existing, err := cfg.Store.Load(cfg.ClientID)
if err != nil && !errors.Is(err, credstore.ErrNotFound) {
fmt.Fprintf(os.Stderr, "Error: Failed to load tokens: %v\n", err)
return 1
}
if err == nil {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventExistingTokens})
if time.Now().Before(existing.ExpiresAt) {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventTokenStillValid})
storage = &existing
flow = "cached"
} else {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventTokenExpired})
newStorage, err := refreshAccessToken(ctx, cfg, existing.RefreshToken)
if err != nil {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventRefreshFailed, Err: err})
} else {
storage = newStorage
flow = "refreshed"
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventRefreshSuccess})
}
}
} else {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventNoExistingTokens})
}
// No valid tokens — select and run the appropriate flow.
if storage == nil {
storage, flow, err = authenticate(ctx, ui, cfg)
if err != nil {
// Error details are already displayed by the UI manager
// Just exit with error code
return 1
}
}
// Display token info.
ui.ShowTokenInfo(toTUITokenStorage(storage, flow, cfg.Store.String()))
// Verify token and fetch UserInfo in parallel (independent API calls).
var (
verifyInfo string
verifyErr error
userInfo *UserInfo
userErr error
wg sync.WaitGroup
)
wg.Add(2)
go func() {
defer wg.Done()
verifyInfo, verifyErr = verifyToken(ctx, cfg, storage.AccessToken)
}()
go func() {
defer wg.Done()
userInfo, userErr = fetchUserInfo(ctx, cfg, storage.AccessToken)
}()
wg.Wait()
if verifyErr != nil {
ui.ShowVerification(false, verifyErr.Error())
} else {
ui.ShowVerification(true, verifyInfo)
}
if userErr != nil {
ui.ShowUserInfo(false, userErr.Error())
} else {
ui.ShowUserInfo(true, formatUserInfo(userInfo))
}
// Demonstrate auto-refresh on 401.
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventAutoRefreshDemo})
if err := makeAPICallWithAutoRefresh(ctx, cfg, storage, ui); err != nil {
if errors.Is(err, ErrRefreshTokenExpired) {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventRefreshTokenExpired})
storage, _, err = authenticate(ctx, ui, cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Re-authentication failed: %v\n", err)
return 1
}
if err := makeAPICallWithAutoRefresh(ctx, cfg, storage, ui); err != nil {
fmt.Fprintf(os.Stderr, "API call failed after re-authentication: %v\n", err)
return 1
}
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventReAuthSuccess})
} else {
fmt.Fprintf(os.Stderr, "API call failed: %v\n", err)
}
}
return 0
}