Skip to content

Commit 38739ee

Browse files
committed
add --header flag to src auth token to print auth header
- for access token print `Authorization: token <token>` - for oauth token print `Authorization: Bearer <token>`
1 parent d206288 commit 38739ee

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

cmd/src/auth_token.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type oauthTokenRefresher interface {
2323

2424
func init() {
2525
flagSet := flag.NewFlagSet("token", flag.ExitOnError)
26+
header := flagSet.Bool("header", false, "print the token as an Authorization header")
2627
usageFunc := func() {
2728
fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n")
2829
flagSet.PrintDefaults()
@@ -38,6 +39,7 @@ func init() {
3839
return err
3940
}
4041

42+
token = formatAuthTokenOutput(token, cfg.AuthMode(), *header)
4143
fmt.Println(token)
4244
return nil
4345
}
@@ -66,3 +68,15 @@ func resolveAuthToken(ctx context.Context, cfg *config) (string, error) {
6668

6769
return token.AccessToken, nil
6870
}
71+
72+
func formatAuthTokenOutput(token string, mode AuthMode, header bool) string {
73+
if !header {
74+
return token
75+
}
76+
77+
if mode == AuthModeAccessToken {
78+
return fmt.Sprintf("Authorization: token %s", token)
79+
}
80+
81+
return fmt.Sprintf("Authorization: Bearer %s", token)
82+
}

cmd/src/auth_token_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,53 @@ func TestResolveAuthToken(t *testing.T) {
103103
})
104104
}
105105

106+
func TestFormatAuthTokenOutput(t *testing.T) {
107+
tests := []struct {
108+
name string
109+
token string
110+
mode AuthMode
111+
header bool
112+
want string
113+
}{
114+
{
115+
name: "raw access token",
116+
token: "access-token",
117+
mode: AuthModeAccessToken,
118+
header: false,
119+
want: "access-token",
120+
},
121+
{
122+
name: "raw oauth token",
123+
token: "oauth-token",
124+
mode: AuthModeOAuth,
125+
header: false,
126+
want: "oauth-token",
127+
},
128+
{
129+
name: "authorization header for access token",
130+
token: "access-token",
131+
mode: AuthModeAccessToken,
132+
header: true,
133+
want: "Authorization: token access-token",
134+
},
135+
{
136+
name: "authorization header for oauth token",
137+
token: "oauth-token",
138+
mode: AuthModeOAuth,
139+
header: true,
140+
want: "Authorization: Bearer oauth-token",
141+
},
142+
}
143+
144+
for _, test := range tests {
145+
t.Run(test.name, func(t *testing.T) {
146+
if got := formatAuthTokenOutput(test.token, test.mode, test.header); got != test.want {
147+
t.Fatalf("formatAuthTokenOutput(%q, %v, %v) = %q, want %q", test.token, test.mode, test.header, got, test.want)
148+
}
149+
})
150+
}
151+
}
152+
106153
func stubAuthTokenDependencies(t *testing.T) func() {
107154
t.Helper()
108155

0 commit comments

Comments
 (0)