-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
350 lines (289 loc) · 8.1 KB
/
auth.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
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package pkg
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
var boldText = lipgloss.NewStyle().Bold(true)
func DeviceLogin(ctx *AppContext) error {
openApiPathname, err := fetchConfigUrl(ctx)
if err != nil {
return err
}
authTokenUrl, err := fetchOpenApiConfig(ctx, openApiPathname)
if err != nil {
return err
}
wellKnownConfig, err := fetchWellKnown(authTokenUrl)
if err != nil {
return err
}
viper.Set("token_endpoint", wellKnownConfig.TokenEndpoint)
err = viper.WriteConfig()
if err != nil {
return err
}
err = deviceLogin(wellKnownConfig, ctx.ClientId, 8)
if err != nil {
return err
}
return nil
}
func ClientCredentialsLogin(ctx *AppContext, clientId string, clientSecret string) error {
openApiPathname, err := fetchConfigUrl(ctx)
if err != nil {
return err
}
authTokenUrl, err := fetchOpenApiConfig(ctx, openApiPathname)
if err != nil {
return err
}
wellKnownConfig, err := fetchWellKnown(authTokenUrl)
if err != nil {
return err
}
viper.Set("token_endpoint", wellKnownConfig.TokenEndpoint)
err = viper.WriteConfig()
if err != nil {
return err
}
err = ClientCredentialLogin(wellKnownConfig.TokenEndpoint, clientId, clientSecret)
if err != nil {
return err
}
return nil
}
func fetchConfigUrl(ctx *AppContext) (string, error) {
client := http.Client{}
URL, _ := ctx.CreateUrl("/ds/api", nil)
request, err := http.NewRequest(http.MethodGet, URL, nil)
if err != nil {
return "", err
}
response, err := client.Do(request)
if err != nil {
return "", err
}
if response.StatusCode == http.StatusNoContent {
linkHeader := response.Header.Get("Link")
result, err := parseLinkHeader(linkHeader)
if err != nil {
return "", err
}
return result, nil
}
return "", fmt.Errorf("host is not configured correctly")
}
func parseLinkHeader(link string) (string, error) {
var result string
links := strings.Split(link, ",")
for _, link := range links {
segments := strings.Split(link, ";")
if len(segments) < 2 {
continue
}
urlSegment := strings.TrimSpace(segments[0])
url := strings.Trim(urlSegment, "<>")
result = url
}
if result == "" {
return result, fmt.Errorf("unable to find OpenAPI configuration")
}
return result, nil
}
type TokenRequestError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type TokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int16 `json:"expires_in"`
RefreshExpiresIn int32 `json:"refresh_expires_in"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
SessionState string `json:"session_state"`
Scope string `json:"scope"`
}
type OpenApi struct {
Components struct {
SecuritySchemes struct {
OpenId struct {
OpenIdConnectUrl string `yaml:"openIdConnectUrl"`
} `yaml:"openid"`
Oauth2 struct {
Flows struct {
ClientCredentials struct {
TokenUrl string `yaml:"tokenUrl"`
} `yaml:"clientCredentials"`
} `yaml:"flows"`
} `yaml:"oauth2"`
} `yaml:"securitySchemes"`
} `yaml:"components"`
}
func fetchOpenApiConfig(ctx *AppContext, openApiPathname string) (string, error) {
client := http.Client{}
URL, _ := ctx.CreateUrl(openApiPathname, nil)
request, err := http.NewRequest(http.MethodGet, URL, nil)
if err != nil {
return "", err
}
request.Header.Set("Content-Type", "text/yaml")
response, err := client.Do(request)
if err != nil {
return "", err
}
var openApiConfig OpenApi
body, err := io.ReadAll(response.Body)
yaml.Unmarshal(body, &openApiConfig)
if err != nil {
return "", err
}
return openApiConfig.Components.SecuritySchemes.OpenId.OpenIdConnectUrl, nil
}
type AuthDetails struct {
Token string
}
type DeviceData struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationUri string `json:"verification_uri"`
VerificationUriComplete string `json:"verification_uri_complete"`
}
func deviceLogin(wellKnownConfig WellKnownConfig, clientId string, timeout time.Duration) error {
data := url.Values{}
data.Set("client_id", clientId)
URL := wellKnownConfig.DeviceAuthorizationEndpoint
request, err := NewApiPost[DeviceData](&AppContext{}, URL, strings.NewReader(data.Encode()))
if err != nil {
return err
}
request.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := request.Do()
if err != nil {
return err
}
urlLine := fmt.Sprintf("\n\nPlease sign in at %s", response.Data.VerificationUri)
fmt.Println(urlLine)
fmt.Println("Input the following code", boldText.Render(response.Data.UserCode))
fmt.Print("\nWaiting for authentication handshake...")
for i := 0; i < 60; i++ {
err := pollAuthStatus(wellKnownConfig.TokenEndpoint, clientId, response.Data.DeviceCode)
if err == nil {
return nil
}
time.Sleep(time.Second * timeout)
}
return fmt.Errorf("login request timed out")
}
type WellKnownConfig struct {
ClientCredentials string `json:"client_credentials"`
TokenEndpoint string `json:"token_endpoint"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
}
func fetchWellKnown(url string) (WellKnownConfig, error) {
request, err := NewApiGet[WellKnownConfig](&AppContext{}, url)
if err != nil {
return WellKnownConfig{}, err
}
response, err := request.Do()
if err != nil {
return WellKnownConfig{}, err
}
return response.Data, nil
}
func pollAuthStatus(URL string, clientId string, deviceCode string) error {
data := url.Values{}
data.Set("device_code", deviceCode)
data.Set("client_id", clientId)
data.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
request, err := NewApiPost[TokenResponse](&AppContext{}, URL, strings.NewReader(data.Encode()))
if err != nil {
return err
}
request.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.Request.Header.Set("Accepts", "application/json")
response, err := request.Do()
if err != nil {
return err
}
SaveConfig(&response.Data)
return nil
}
func RefreshToken(ctx *AppContext) error {
tokenEndpoint := viper.GetString("token_endpoint")
refreshToken := viper.GetString("refresh_token")
if refreshToken == "" {
return nil
}
data := make(url.Values)
data.Set("client_id", ctx.ClientId)
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
request, err := http.NewRequest(http.MethodPost, tokenEndpoint, strings.NewReader(data.Encode()))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := new(http.Client)
response, err := client.Do(request)
if err != nil {
return err
}
body, err := io.ReadAll(response.Body)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
var data TokenResponse
json.Unmarshal(body, &data)
ctx.ApiKey = data.AccessToken
viper.Set("api_key", data.AccessToken)
viper.Set("refresh_token", data.RefreshToken)
err = viper.WriteConfig()
if err != nil {
return err
}
return nil
}
var errorResponse ApiErrorResponse
err = json.Unmarshal(body, &errorResponse)
if err != nil {
return fmt.Errorf(string(body))
}
return errorResponse.GetError()
}
func ClientCredentialLogin(tokenEndpoint string, clientId string, clientSecret string) error {
data := make(url.Values)
data.Set("client_id", clientId)
data.Set("client_secret", clientSecret)
data.Set("grant_type", "client_credentials")
ctx := &AppContext{}
r, err := NewApiPost[TokenResponse](ctx, tokenEndpoint, strings.NewReader(data.Encode()))
if err != nil {
return err
}
r.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := r.Do()
if err != nil {
return err
}
return SaveConfig(&response.Data)
}
func SaveConfig(data *TokenResponse) error {
viper.Set("api_key", data.AccessToken)
viper.Set("refresh_token", data.RefreshToken)
viper.Set("refresh_expires_in", data.RefreshExpiresIn)
err := viper.WriteConfig()
if err != nil {
return err
}
return nil
}