forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_createadminuser.go
274 lines (248 loc) · 7.83 KB
/
server_createadminuser.go
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//go:build !slim
package cli
import (
"fmt"
"os/signal"
"sort"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/gitsshkey"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/userpassword"
"github.com/coder/coder/codersdk"
)
func (r *RootCmd) newCreateAdminUserCommand() *clibase.Cmd {
var (
newUserDBURL string
newUserSSHKeygenAlgorithm string
newUserUsername string
newUserEmail string
newUserPassword string
)
createAdminUserCommand := &clibase.Cmd{
Use: "create-admin-user",
Short: "Create a new admin user with the given username, email and password and adds it to every organization.",
Handler: func(inv *clibase.Invocation) error {
ctx := inv.Context()
sshKeygenAlgorithm, err := gitsshkey.ParseAlgorithm(newUserSSHKeygenAlgorithm)
if err != nil {
return xerrors.Errorf("parse ssh keygen algorithm %q: %w", newUserSSHKeygenAlgorithm, err)
}
cfg := r.createConfig()
logger := slog.Make(sloghuman.Sink(inv.Stderr))
if r.verbose {
logger = logger.Leveled(slog.LevelDebug)
}
ctx, cancel := signal.NotifyContext(ctx, InterruptSignals...)
defer cancel()
if newUserDBURL == "" {
cliui.Infof(inv.Stdout, "Using built-in PostgreSQL (%s)\n", cfg.PostgresPath())
url, closePg, err := startBuiltinPostgres(ctx, cfg, logger)
if err != nil {
return err
}
defer func() {
_ = closePg()
}()
newUserDBURL = url
}
sqlDB, err := connectToPostgres(ctx, logger, "postgres", newUserDBURL)
if err != nil {
return xerrors.Errorf("connect to postgres: %w", err)
}
defer func() {
_ = sqlDB.Close()
}()
db := database.New(sqlDB)
validateInputs := func(username, email, password string) error {
// Use the validator tags so we match the API's validation.
req := codersdk.CreateUserRequest{
Username: "username",
Email: "[email protected]",
Password: "ValidPa$$word123!",
OrganizationID: uuid.New(),
}
if username != "" {
req.Username = username
}
if email != "" {
req.Email = email
}
if password != "" {
req.Password = password
}
return httpapi.Validate.Struct(req)
}
if newUserUsername == "" {
newUserUsername, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Username",
Validate: func(val string) error {
if val == "" {
return xerrors.New("username cannot be empty")
}
return validateInputs(val, "", "")
},
})
if err != nil {
return err
}
}
if newUserEmail == "" {
newUserEmail, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Email",
Validate: func(val string) error {
if val == "" {
return xerrors.New("email cannot be empty")
}
return validateInputs("", val, "")
},
})
if err != nil {
return err
}
}
if newUserPassword == "" {
newUserPassword, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Password",
Secret: true,
Validate: func(val string) error {
if val == "" {
return xerrors.New("password cannot be empty")
}
return validateInputs("", "", val)
},
})
if err != nil {
return err
}
// Prompt again.
_, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Confirm password",
Secret: true,
Validate: func(val string) error {
if val != newUserPassword {
return xerrors.New("passwords do not match")
}
return nil
},
})
if err != nil {
return err
}
}
err = validateInputs(newUserUsername, newUserEmail, newUserPassword)
if err != nil {
return xerrors.Errorf("validate inputs: %w", err)
}
hashedPassword, err := userpassword.Hash(newUserPassword)
if err != nil {
return xerrors.Errorf("hash password: %w", err)
}
// Create the user.
var newUser database.User
err = db.InTx(func(tx database.Store) error {
orgs, err := tx.GetOrganizations(ctx)
if err != nil {
return xerrors.Errorf("get organizations: %w", err)
}
// Sort organizations by name so that test output is consistent.
sort.Slice(orgs, func(i, j int) bool {
return orgs[i].Name < orgs[j].Name
})
_, _ = fmt.Fprintln(inv.Stderr, "Creating user...")
newUser, err = tx.InsertUser(ctx, database.InsertUserParams{
ID: uuid.New(),
Email: newUserEmail,
Username: newUserUsername,
HashedPassword: []byte(hashedPassword),
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
RBACRoles: []string{rbac.RoleOwner()},
LoginType: database.LoginTypePassword,
})
if err != nil {
return xerrors.Errorf("insert user: %w", err)
}
_, _ = fmt.Fprintln(inv.Stderr, "Generating user SSH key...")
privateKey, publicKey, err := gitsshkey.Generate(sshKeygenAlgorithm)
if err != nil {
return xerrors.Errorf("generate user gitsshkey: %w", err)
}
_, err = tx.InsertGitSSHKey(ctx, database.InsertGitSSHKeyParams{
UserID: newUser.ID,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
PrivateKey: privateKey,
PublicKey: publicKey,
})
if err != nil {
return xerrors.Errorf("insert user gitsshkey: %w", err)
}
for _, org := range orgs {
_, _ = fmt.Fprintf(inv.Stderr, "Adding user to organization %q (%s) as admin...\n", org.Name, org.ID.String())
_, err := tx.InsertOrganizationMember(ctx, database.InsertOrganizationMemberParams{
OrganizationID: org.ID,
UserID: newUser.ID,
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
Roles: []string{rbac.RoleOrgAdmin(org.ID)},
})
if err != nil {
return xerrors.Errorf("insert organization member: %w", err)
}
}
return nil
}, nil)
if err != nil {
return err
}
_, _ = fmt.Fprintln(inv.Stderr, "")
_, _ = fmt.Fprintln(inv.Stderr, "User created successfully.")
_, _ = fmt.Fprintln(inv.Stderr, "ID: "+newUser.ID.String())
_, _ = fmt.Fprintln(inv.Stderr, "Username: "+newUser.Username)
_, _ = fmt.Fprintln(inv.Stderr, "Email: "+newUser.Email)
_, _ = fmt.Fprintln(inv.Stderr, "Password: ********")
return nil
},
}
createAdminUserCommand.Options.Add(
clibase.Option{
Env: "CODER_PG_CONNECTION_URL",
Flag: "postgres-url",
Description: "URL of a PostgreSQL database. If empty, the built-in PostgreSQL deployment will be used (Coder must not be already running in this case).",
Value: clibase.StringOf(&newUserDBURL),
},
clibase.Option{
Env: "CODER_SSH_KEYGEN_ALGORITHM",
Flag: "ssh-keygen-algorithm",
Description: "The algorithm to use for generating ssh keys. Accepted values are \"ed25519\", \"ecdsa\", or \"rsa4096\".",
Default: "ed25519",
Value: clibase.StringOf(&newUserSSHKeygenAlgorithm),
},
clibase.Option{
Env: "CODER_USERNAME",
Flag: "username",
Description: "The username of the new user. If not specified, you will be prompted via stdin.",
Value: clibase.StringOf(&newUserUsername),
},
clibase.Option{
Env: "CODER_EMAIL",
Flag: "email",
Description: "The email of the new user. If not specified, you will be prompted via stdin.",
Value: clibase.StringOf(&newUserEmail),
},
clibase.Option{
Env: "CODER_PASSWORD",
Flag: "password",
Description: "The password of the new user. If not specified, you will be prompted via stdin.",
Value: clibase.StringOf(&newUserPassword),
},
)
return createAdminUserCommand
}