Skip to content

Commit 31e33ab

Browse files
committed
Add 'whoami' command to display authenticated user and tenant information
This new command retrieves and presents the current user's details and associated tenant from the access token. It includes error handling for token extraction and supports multiple output formats. Files added: 1 - internal/commands/whoami.go
1 parent f7e2b45 commit 31e33ab

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

internal/commands/whoami.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package commands
2+
3+
import (
4+
"github.com/MakeNowJust/heredoc"
5+
"github.com/checkmarx/ast-cli/internal/commands/util/printer"
6+
"github.com/checkmarx/ast-cli/internal/wrappers"
7+
"github.com/pkg/errors"
8+
"github.com/spf13/cobra"
9+
)
10+
11+
const (
12+
whoamiTenantClaimKey = "tenant_name"
13+
whoamiUserClaimKey = "name"
14+
whoamiUserFallbackClaimKey = "sub"
15+
)
16+
17+
type whoamiView struct {
18+
User string `json:"user" format:"name:User"`
19+
Tenant string `json:"tenant" format:"name:Tenant"`
20+
}
21+
22+
func NewWhoamiCommand() *cobra.Command {
23+
whoamiCmd := &cobra.Command{
24+
Use: "whoami",
25+
Short: "Show authenticated user and tenant information",
26+
Long: "The whoami command shows authenticated user and tenant information from the current access token",
27+
Example: heredoc.Doc(
28+
`
29+
$ cx whoami
30+
`,
31+
),
32+
RunE: runWhoami,
33+
}
34+
35+
addFormatFlag(whoamiCmd, printer.FormatList, printer.FormatJSON, printer.FormatTable)
36+
return whoamiCmd
37+
}
38+
39+
func runWhoami(cmd *cobra.Command, _ []string) error {
40+
accessToken, err := wrappers.GetAccessToken()
41+
if err != nil {
42+
return err
43+
}
44+
45+
user, err := extractWhoamiUser(accessToken)
46+
if err != nil {
47+
return errors.Wrap(err, "failed to extract authenticated user from token")
48+
}
49+
50+
tenant, err := wrappers.ExtractFromTokenClaims(accessToken, whoamiTenantClaimKey)
51+
if err != nil {
52+
return errors.Wrap(err, "failed to extract tenant from token")
53+
}
54+
55+
return printByFormat(cmd, whoamiView{
56+
User: user,
57+
Tenant: tenant,
58+
})
59+
}
60+
61+
func extractWhoamiUser(accessToken string) (string, error) {
62+
claimKeys := []string{whoamiUserClaimKey, whoamiUserFallbackClaimKey}
63+
var err error
64+
for _, claimKey := range claimKeys {
65+
var user string
66+
user, err = wrappers.ExtractFromTokenClaims(accessToken, claimKey)
67+
if err == nil {
68+
return user, nil
69+
}
70+
}
71+
return "", err
72+
}

0 commit comments

Comments
 (0)