-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathget_access_token.go
More file actions
82 lines (70 loc) · 2.07 KB
/
get_access_token.go
File metadata and controls
82 lines (70 loc) · 2.07 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
package getaccesstoken
import (
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/stackitcloud/stackit-cli/internal/cmd/params"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
"github.com/stackitcloud/stackit-cli/internal/pkg/auth"
cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
"github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
)
type inputModel struct {
*globalflags.GlobalFlagModel
}
func NewCmd(params *params.CmdParams) *cobra.Command {
cmd := &cobra.Command{
Use: "get-access-token",
Short: "Prints a short-lived access token.",
Long: "Prints a short-lived access token which can be used e.g. for API calls.",
Args: args.NoArgs,
Example: examples.Build(
examples.NewExample(
`Print a short-lived access token`,
"$ stackit auth get-access-token"),
),
RunE: func(cmd *cobra.Command, _ []string) error {
model, err := parseInput(params.Printer, cmd)
if err != nil {
return err
}
userSessionExpired, err := auth.UserSessionExpired()
if err != nil {
return err
}
if userSessionExpired {
return &cliErr.SessionExpiredError{}
}
accessToken, err := auth.GetValidAccessToken(params.Printer)
if err != nil {
params.Printer.Debug(print.ErrorLevel, "get valid access token: %v", err)
return &cliErr.SessionExpiredError{}
}
switch model.OutputFormat {
case print.JSONOutputFormat:
details, err := json.MarshalIndent(map[string]string{
"access_token": accessToken,
}, "", " ")
if err != nil {
return fmt.Errorf("marshal image list: %w", err)
}
params.Printer.Outputln(string(details))
return nil
default:
params.Printer.Outputln(accessToken)
return nil
}
},
}
return cmd
}
func parseInput(p *print.Printer, cmd *cobra.Command) (*inputModel, error) {
globalFlags := globalflags.Parse(p, cmd)
model := inputModel{
GlobalFlagModel: globalFlags,
}
p.DebugInputModel(model)
return &model, nil
}