File: create.go

package info (click to toggle)
glab 1.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,936 kB
  • sloc: sh: 295; makefile: 153; perl: 99; ruby: 68; javascript: 67
file content (260 lines) | stat: -rw-r--r-- 8,804 bytes parent folder | download
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
package create

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"gitlab.com/gitlab-org/cli/commands/token/expirationdate"
	"gitlab.com/gitlab-org/cli/commands/token/filter"

	"gitlab.com/gitlab-org/cli/commands/flag"
	"gitlab.com/gitlab-org/cli/commands/token/accesslevel"

	"gitlab.com/gitlab-org/cli/pkg/iostreams"

	"github.com/MakeNowJust/heredoc/v2"
	"github.com/spf13/cobra"
	gitlab "gitlab.com/gitlab-org/api/client-go"
	"gitlab.com/gitlab-org/cli/api"
	"gitlab.com/gitlab-org/cli/commands/cmdutils"
	"gitlab.com/gitlab-org/cli/internal/glrepo"
)

type CreateOptions struct {
	HTTPClient func() (*gitlab.Client, error)
	IO         *iostreams.IOStreams
	BaseRepo   func() (glrepo.Interface, error)

	Name         string
	User         string
	Group        string
	AccessLevel  accesslevel.AccessLevel
	Scopes       []string
	Duration     time.Duration
	ExpireAt     expirationdate.ExpirationDate
	OutputFormat string
}

func NewCmdCreate(f *cmdutils.Factory, runE func(opts *CreateOptions) error) *cobra.Command {
	opts := &CreateOptions{
		IO: f.IO,
	}

	cmd := &cobra.Command{
		Use:     "create <name>",
		Aliases: []string{"create", "new"},
		Args:    cobra.RangeArgs(1, 1),
		Short:   "Creates user, group, or project access tokens.",
		Long: heredoc.Doc(`
		Creates a new access token for a user, group, or project. Defaults to a
		project access token, unless user or group name is specified.

		The expiration date of the token is calculated by adding the duration
		(default: 30 days) to the current date. You can specify a different duration,
		or an explicit end date.

		The name of the token must be unique. The token is printed to stdout.

		Administrators can create full-featured personal access tokens for themselves and for other users.
		Non-administrators can create personal access tokens only for themselves (@me) with the scope 'k8s_proxy'.
		`),
		Example: heredoc.Doc(`
		# Create project access token for current project
		glab token create --access-level developer --scope read_repository --scope read_registry my-project-token

		# Create project access token for a specific project
		glab token create --repo user/my-repo --access-level owner --scope api my-project-token

		# Create a group access token
		glab token create --group group/sub-group --access-level owner --scope api my-group-token

		# Create a personal access token for current user
		glab token create --user @me --scope k8s_proxy my-personal-token

		# (administrator only) Create a personal access token for another user
		glab token create --user johndoe --scope api johns-personal-token

		`),
		RunE: func(cmd *cobra.Command, args []string) (err error) {
			// Supports repo override
			opts.HTTPClient = f.HttpClient
			opts.BaseRepo = f.BaseRepo
			opts.Name = args[0]
			if opts.Group, err = flag.GroupOverride(cmd); err != nil {
				return
			}

			if opts.Group != "" && opts.User != "" {
				return cmdutils.FlagError{Err: errors.New("'--group' and '--user' are mutually exclusive.")}
			}

			if cmd.Flags().Changed("expires-at") && cmd.Flags().Changed("duration") {
				return cmdutils.FlagError{Err: errors.New("'--expires-at' and '--duration' are mutually exclusive.")}
			}

			if time.Time(opts.ExpireAt).IsZero() {
				opts.ExpireAt = expirationdate.ExpirationDate(time.Now().Add(opts.Duration).Truncate(time.Hour * 24))
			}

			if opts.Duration.Truncate(24*time.Hour) != opts.Duration {
				return cmdutils.FlagError{Err: errors.New("duration must be in days.")}
			}

			if opts.Duration < 24*time.Hour || opts.Duration > 365*24*time.Hour {
				return cmdutils.FlagError{Err: errors.New("duration in days must be between 1 and 365.")}
			}

			if opts.User != "" && opts.Group != "" {
				return cmdutils.FlagError{Err: errors.New("'--user' and '--group' are mutually exclusive.")}
			}

			if opts.User == "" && !cmd.Flag("access-level").Changed {
				return cmdutils.FlagError{Err: errors.New("the required flag '--access-level' is not set.")}
			}

			if runE != nil {
				err = runE(opts)
				return
			}
			err = createTokenRun(opts)
			return
		},
	}

	cmdutils.EnableRepoOverride(cmd, f)
	cmd.Flags().StringVarP(&opts.Group, "group", "g", "", "Create a group access token. Ignored if a user or repository argument is set.")
	cmd.Flags().StringVarP(&opts.User, "user", "U", "", "Create a personal access token. For the current user, use @me.")
	cmd.Flags().DurationVarP(&opts.Duration, "duration", "D", time.Duration(30*24*time.Hour), "Sets the token duration, in hours. Maximum of 8760. Examples: 24h, 168h, 504h.")
	cmd.Flags().VarP(&opts.ExpireAt, "expires-at", "E", "Sets the token's expiration date and time, in YYYY-MM-DD format. If not specified, --duration is used.")
	cmd.Flags().StringSliceVarP(&opts.Scopes, "scope", "S", []string{"read_repository"}, "Scopes for the token. For a list, see https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#personal-access-token-scopes.")
	cmd.Flags().VarP(&opts.AccessLevel, "access-level", "A", "Access level of the token: one of 'guest', 'reporter', 'developer', 'maintainer', 'owner'.")
	cmd.Flags().StringVarP(&opts.OutputFormat, "output", "F", "text", "Format output as 'text' for the token value, 'json' for the actual API token structure.")
	return cmd
}

func createTokenRun(opts *CreateOptions) error {
	httpClient, err := opts.HTTPClient()
	if err != nil {
		return err
	}
	var outputToken interface{}
	var outputTokenValue string
	expirationDate := gitlab.ISOTime(opts.ExpireAt)

	if opts.User != "" {
		user, err := api.UserByName(httpClient, opts.User)
		if err != nil {
			return err
		}

		options := &gitlab.ListPersonalAccessTokensOptions{
			ListOptions: gitlab.ListOptions{PerPage: 100},
			UserID:      &user.ID,
		}
		tokens, err := api.ListPersonalAccessTokens(httpClient, options)
		if err != nil {
			return err
		}
		tokens = filter.Filter(tokens, func(t *gitlab.PersonalAccessToken) bool {
			return t.Active && t.Name == opts.Name
		})
		if len(tokens) > 0 {
			return cmdutils.FlagError{Err: fmt.Errorf("a personal access token with the name %s already exists.", opts.Name)}
		}

		if opts.User == "@me" {
			token, err := api.CreatePersonalAccessTokenForCurrentUser(httpClient, opts.Name, opts.Scopes, time.Time(expirationDate))
			if err != nil {
				return err
			}
			outputToken = token
			outputTokenValue = token.Token
		} else {
			createOptions := &gitlab.CreatePersonalAccessTokenOptions{
				Name:      &opts.Name,
				ExpiresAt: &expirationDate,
				Scopes:    &opts.Scopes,
			}
			token, err := api.CreatePersonalAccessToken(httpClient, user.ID, createOptions)
			if err != nil {
				return err
			}
			outputToken = token
			outputTokenValue = token.Token
		}
	} else {
		if opts.Group != "" {
			listOptions := &gitlab.ListGroupAccessTokensOptions{PerPage: 100}
			tokens, err := api.ListGroupAccessTokens(httpClient, opts.Group, listOptions)
			if err != nil {
				return err
			}
			tokens = filter.Filter(tokens, func(t *gitlab.GroupAccessToken) bool {
				return t.Active && t.Name == opts.Name
			})
			if len(tokens) > 0 {
				return cmdutils.FlagError{Err: fmt.Errorf("a group access token with the name %s already exists.", opts.Name)}
			}

			options := gitlab.CreateGroupAccessTokenOptions{
				Name:        &opts.Name,
				Scopes:      &opts.Scopes,
				AccessLevel: &opts.AccessLevel.Value,
				ExpiresAt:   &expirationDate,
			}
			token, err := api.CreateGroupAccessToken(httpClient, opts.Group, &options)
			if err != nil {
				return err
			}
			outputToken = token
			outputTokenValue = token.Token

		} else {
			repo, err := opts.BaseRepo()
			if err != nil {
				return err
			}
			listOptions := &gitlab.ListProjectAccessTokensOptions{PerPage: 100}
			tokens, err := api.ListProjectAccessTokens(httpClient, repo.FullName(), listOptions)
			if err != nil {
				return err
			}
			tokens = filter.Filter(tokens, func(t *gitlab.ProjectAccessToken) bool {
				return t.Active && t.Name == opts.Name
			})

			if len(tokens) > 0 {
				return cmdutils.FlagError{Err: fmt.Errorf("a project access token with name %s already exists.", opts.Name)}
			}

			options := gitlab.CreateProjectAccessTokenOptions{
				Name:        &opts.Name,
				Scopes:      &opts.Scopes,
				AccessLevel: &opts.AccessLevel.Value,
				ExpiresAt:   &expirationDate,
			}
			token, err := api.CreateProjectAccessToken(httpClient, repo.FullName(), &options)
			if err != nil {
				return err
			}
			outputToken = token
			outputTokenValue = token.Token
		}
	}

	if opts.OutputFormat == "json" {
		encoder := json.NewEncoder(opts.IO.StdOut)
		encoder.SetIndent("  ", "  ")
		if err := encoder.Encode(outputToken); err != nil {
			return err
		}
	} else {
		if _, err := fmt.Fprintf(opts.IO.StdOut, "%s\n", outputTokenValue); err != nil {
			return err
		}
	}

	return nil
}