-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathauth_token.go
More file actions
88 lines (70 loc) · 2.09 KB
/
auth_token.go
File metadata and controls
88 lines (70 loc) · 2.09 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
package main
import (
"context"
"flag"
"fmt"
"github.com/sourcegraph/sourcegraph/lib/errors"
"github.com/sourcegraph/src-cli/internal/oauth"
)
var (
loadOAuthToken = oauth.LoadToken
newOAuthTokenRefresher = func(token *oauth.Token) oauthTokenRefresher {
return oauth.NewTokenRefresher(token)
}
)
type oauthTokenRefresher interface {
GetToken(ctx context.Context) (oauth.Token, error)
}
func init() {
flagSet := flag.NewFlagSet("token", flag.ExitOnError)
header := flagSet.Bool("header", false, "print the token as an Authorization header")
usageFunc := func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "Print the current authentication token.\n")
fmt.Fprintf(flag.CommandLine.Output(), "Use --header to print a complete Authorization header instead.\n\n")
flagSet.PrintDefaults()
}
handler := func(args []string) error {
if err := flagSet.Parse(args); err != nil {
return err
}
token, err := resolveAuthToken(context.Background(), cfg)
if err != nil {
return err
}
token = formatAuthTokenOutput(token, cfg.AuthMode(), *header)
fmt.Println(token)
return nil
}
authCommands = append(authCommands, &command{
flagSet: flagSet,
handler: handler,
usageFunc: usageFunc,
})
}
func resolveAuthToken(ctx context.Context, cfg *config) (string, error) {
if err := cfg.requireCIAccessToken(); err != nil {
return "", err
}
if cfg.accessToken != "" {
return cfg.accessToken, nil
}
oauthToken, err := loadOAuthToken(ctx, cfg.endpointURL)
if err != nil {
return "", errors.Wrap(err, "error loading OAuth token; set SRC_ACCESS_TOKEN or run `src login`")
}
token, err := newOAuthTokenRefresher(oauthToken).GetToken(ctx)
if err != nil {
return "", errors.Wrap(err, "refreshing OAuth token")
}
return token.AccessToken, nil
}
func formatAuthTokenOutput(token string, mode AuthMode, header bool) string {
if !header {
return token
}
if mode == AuthModeAccessToken {
return fmt.Sprintf("Authorization: token %s", token)
}
return fmt.Sprintf("Authorization: Bearer %s", token)
}