-
Notifications
You must be signed in to change notification settings - Fork 156
/
user.go
1000 lines (834 loc) · 31.9 KB
/
user.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package commands
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mmctl/v6/client"
"github.com/mattermost/mmctl/v6/printer"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var UserCmd = &cobra.Command{
Use: "user",
Short: "Management of users",
}
var UserActivateCmd = &cobra.Command{
Use: "activate [emails, usernames, userIds]",
Short: "Activate users",
Long: "Activate users that have been deactivated.",
Example: ` user activate user@example.com
user activate username`,
RunE: withClient(userActivateCmdF),
Args: cobra.MinimumNArgs(1),
}
var UserDeactivateCmd = &cobra.Command{
Use: "deactivate [emails, usernames, userIds]",
Short: "Deactivate users",
Long: "Deactivate users. Deactivated users are immediately logged out of all sessions and are unable to log back in.",
Example: ` user deactivate user@example.com
user deactivate username`,
RunE: withClient(userDeactivateCmdF),
Args: cobra.MinimumNArgs(1),
}
var UserCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a user",
Long: "Create a user",
Example: ` # You can create a user
$ mmctl user create --email user@example.com --username userexample --password Password1
# You can define optional fields like first name, last name and nick name too
$ mmctl user create --email user@example.com --username userexample --password Password1 --firstname User --lastname Example --nickname userex
# Also you can create the user as system administrator
$ mmctl user create --email user@example.com --username userexample --password Password1 --system-admin
# Finally you can verify user on creation if you have enough permissions
$ mmctl user create --email user@example.com --username userexample --password Password1 --system-admin --email-verified`,
RunE: withClient(userCreateCmdF),
}
var UserInviteCmd = &cobra.Command{
Use: "invite [email] [teams]",
Short: "Send user an email invite to a team.",
Long: `Send user an email invite to a team.
You can invite a user to multiple teams by listing them.
You can specify teams by name or ID.`,
Example: ` user invite user@example.com myteam
user invite user@example.com myteam1 myteam2`,
RunE: withClient(userInviteCmdF),
}
var SendPasswordResetEmailCmd = &cobra.Command{
Use: "reset-password [users]",
Aliases: []string{"reset_password"},
Short: "Send users an email to reset their password",
Long: "Send users an email to reset their password",
Example: " user reset-password user@example.com",
RunE: withClient(sendPasswordResetEmailCmdF),
}
var UpdateUserEmailCmd = &cobra.Command{
Use: "email [user] [new email]",
Short: "Change email of the user",
Long: "Change the email address associated with a user.",
Example: " user email testuser user@example.com",
RunE: withClient(updateUserEmailCmdF),
}
var UpdateUsernameCmd = &cobra.Command{
Use: "username [user] [new username]",
Short: "Change username of the user",
Long: "Change username of the user.",
Example: " user username testuser newusername",
Args: cobra.ExactArgs(2),
RunE: withClient(updateUsernameCmdF),
}
var ChangePasswordUserCmd = &cobra.Command{
Use: "change-password <user>",
Short: "Changes a user's password",
Long: "Changes the password of a user by a new one provided. If the user is changing their own password, the flag --current must indicate the current password. The flag --hashed can be used to indicate that the new password has been introduced already hashed",
Example: ` # if you have system permissions, you can change other user's passwords
$ mmctl user change-password john_doe --password new-password
# if you are changing your own password, you need to provide the current one
$ mmctl user change-password my-username --current current-password --password new-password
# you can ommit these flags to introduce them interactively
$ mmctl user change-password my-username
Are you changing your own password? (YES/NO): YES
Current password:
New password:
# if you have system permissions, you can update the password with the already hashed new
# password. The hashing method should be the same that the server uses internally
$ mmctl user change-password john_doe --password HASHED_PASSWORD --hashed`,
Args: cobra.ExactArgs(1),
RunE: withClient(changePasswordUserCmdF),
}
var ResetUserMfaCmd = &cobra.Command{
Use: "resetmfa [users]",
Short: "Turn off MFA",
Long: `Turn off multi-factor authentication for a user.
If MFA enforcement is enabled, the user will be forced to re-enable MFA as soon as they log in.`,
Example: " user resetmfa user@example.com",
RunE: withClient(resetUserMfaCmdF),
}
var DeleteUsersCmd = &cobra.Command{
Use: "delete [users]",
Short: "Delete users",
Long: `Permanently delete some users.
Permanently deletes one or multiple users along with all related information including posts from the database.`,
Example: " user delete user@example.com",
Args: cobra.MinimumNArgs(1),
RunE: withClient(deleteUsersCmdF),
}
var DeleteAllUsersCmd = &cobra.Command{
Use: "deleteall",
Short: "Delete all users and all posts. Local command only.",
Long: "Permanently delete all users and all related information including posts. This command can only be run in local mode.",
Example: " user deleteall",
Args: cobra.NoArgs,
PreRun: localOnlyPrecheck,
RunE: withClient(deleteAllUsersCmdF),
}
var SearchUserCmd = &cobra.Command{
Use: "search [users]",
Short: "Search for users",
Long: "Search for users based on username, email, or user ID.",
Example: " user search user1@mail.com user2@mail.com",
RunE: withClient(searchUserCmdF),
}
var ListUsersCmd = &cobra.Command{
Use: "list",
Short: "List users",
Long: "List all users",
Example: " user list",
RunE: withClient(listUsersCmdF),
Args: cobra.NoArgs,
}
var VerifyUserEmailWithoutTokenCmd = &cobra.Command{
Use: "verify [users]",
Short: "Mark user's email as verified",
Long: "Mark user's email as verified without requiring user to complete email verification path.",
Example: " user verify user1",
RunE: withClient(verifyUserEmailWithoutTokenCmdF),
Args: cobra.MinimumNArgs(1),
}
var PromoteGuestToUserCmd = &cobra.Command{
Use: "promote [guests]",
Short: "Promote guests to users",
Long: "Convert a guest into a regular user.",
Example: " user promote guest1 guest2",
RunE: withClient(promoteGuestToUserCmdF),
Args: cobra.MinimumNArgs(1),
}
var DemoteUserToGuestCmd = &cobra.Command{
Use: "demote [users]",
Short: "Demote users to guests",
Long: "Convert a regular user into a guest.",
Example: " user demote user1 user2",
RunE: withClient(demoteUserToGuestCmdF),
Args: cobra.MinimumNArgs(1),
}
var UserConvertCmd = &cobra.Command{
Use: "convert (--bot [emails] [usernames] [userIds] | --user <username> --password PASSWORD [--email EMAIL])",
Short: "Convert users to bots, or a bot to a user",
Long: "Convert user accounts to bots or convert bots to user accounts.",
Example: ` # you can convert a user to a bot providing its email, id or username
$ mmctl user convert user@example.com --bot
# or multiple users in one go
$ mmctl user convert user@example.com anotherUser --bot
# you can convert a bot to a user specifying the email and password that the user will have after conversion
$ mmctl user convert botusername --email new.email@email.com --password password --user`,
RunE: withClient(userConvertCmdF),
Args: cobra.MinimumNArgs(1),
}
var MigrateAuthCmd = &cobra.Command{
Use: "migrate-auth [from_auth] [to_auth] [migration-options]",
Aliases: []string{"migrate_auth"},
Short: "Mass migrate user accounts authentication type",
Long: `Migrates accounts from one authentication provider to another. For example, you can upgrade your authentication provider from email to ldap.`,
Example: "user migrate-auth email saml users.json",
Args: func(command *cobra.Command, args []string) error {
if len(args) < 2 {
return errors.New("auth migration requires at least 2 arguments")
}
toAuth := args[1]
if toAuth != "ldap" && toAuth != "saml" { // nolint: goconst
return errors.New("invalid to_auth parameter, must be saml or ldap")
}
if toAuth == "ldap" && len(args) != 3 {
return errors.New("ldap migration requires 3 arguments")
}
autoFlag, _ := command.Flags().GetBool("auto")
if toAuth == "saml" && autoFlag {
if len(args) != 2 {
return errors.New("saml migration requires two arguments when using the --auto flag")
}
}
if toAuth == "saml" && !autoFlag {
if len(args) != 3 {
return errors.New("saml migration requires three arguments when not using the --auto flag")
}
}
return nil
},
RunE: withClient(migrateAuthCmdF),
}
func init() {
UserCreateCmd.Flags().String("username", "", "Required. Username for the new user account")
_ = UserCreateCmd.MarkFlagRequired("username")
UserCreateCmd.Flags().String("email", "", "Required. The email address for the new user account")
_ = UserCreateCmd.MarkFlagRequired("email")
UserCreateCmd.Flags().String("password", "", "Required. The password for the new user account")
_ = UserCreateCmd.MarkFlagRequired("password")
UserCreateCmd.Flags().String("nickname", "", "Optional. The nickname for the new user account")
UserCreateCmd.Flags().String("firstname", "", "Optional. The first name for the new user account")
UserCreateCmd.Flags().String("lastname", "", "Optional. The last name for the new user account")
UserCreateCmd.Flags().String("locale", "", "Optional. The locale (ex: en, fr) for the new user account")
UserCreateCmd.Flags().Bool("system-admin", false, "Optional. If supplied, the new user will be a system administrator. Defaults to false")
UserCreateCmd.Flags().Bool("system_admin", false, "")
_ = UserCreateCmd.Flags().MarkDeprecated("system_admin", "please use system-admin instead")
UserCreateCmd.Flags().Bool("guest", false, "Optional. If supplied, the new user will be a guest. Defaults to false")
UserCreateCmd.Flags().Bool("email-verified", false, "Optional. If supplied, the new user will have the email verified. Defaults to false")
UserCreateCmd.Flags().Bool("email_verified", false, "")
_ = UserCreateCmd.Flags().MarkDeprecated("email_verified", "please use email-verified instead")
UserCreateCmd.Flags().Bool("disable-welcome-email", false, "Optional. If supplied, the new user will not receive a welcome email. Defaults to false")
DeleteUsersCmd.Flags().Bool("confirm", false, "Confirm you really want to delete the user and a DB backup has been performed")
DeleteAllUsersCmd.Flags().Bool("confirm", false, "Confirm you really want to delete the user and a DB backup has been performed")
ListUsersCmd.Flags().Int("page", 0, "Page number to fetch for the list of users")
ListUsersCmd.Flags().Int("per-page", 200, "Number of users to be fetched")
ListUsersCmd.Flags().Bool("all", false, "Fetch all users. --page flag will be ignore if provided")
ListUsersCmd.Flags().String("team", "", "If supplied, only users belonging to this team will be listed")
UserConvertCmd.Flags().Bool("bot", false, "If supplied, convert users to bots")
UserConvertCmd.Flags().Bool("user", false, "If supplied, convert a bot to a user")
UserConvertCmd.Flags().String("password", "", "The password for converted new user account. Required when \"user\" flag is set")
UserConvertCmd.Flags().String("username", "", "Username for the converted user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().String("email", "", "The email address for the converted user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().String("nickname", "", "The nickname for the converted user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().String("firstname", "", "The first name for the converted user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().String("lastname", "", "The last name for the converted user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().String("locale", "", "The locale (ex: en, fr) for converted new user account. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().Bool("system-admin", false, "If supplied, the converted user will be a system administrator. Defaults to false. Required when the \"bot\" flag is set")
UserConvertCmd.Flags().Bool("system_admin", false, "")
_ = UserConvertCmd.Flags().MarkDeprecated("system_admin", "please use system-admin instead")
ChangePasswordUserCmd.Flags().StringP("current", "c", "", "The current password of the user. Use only if changing your own password")
ChangePasswordUserCmd.Flags().StringP("password", "p", "", "The new password for the user")
ChangePasswordUserCmd.Flags().Bool("hashed", false, "The supplied password is already hashed")
MigrateAuthCmd.Flags().Bool("force", false, "Force the migration to occur even if there are duplicates on the LDAP server. Duplicates will not be migrated. (ldap only)")
MigrateAuthCmd.Flags().Bool("auto", false, "Automatically migrate all users. Assumes the usernames and emails are identical between Mattermost and SAML services. (saml only)")
MigrateAuthCmd.Flags().Bool("confirm", false, "Confirm you really want to proceed with auto migration. (saml only)")
MigrateAuthCmd.SetHelpTemplate(`Usage:
mmctl user migrate-auth [from_auth] [to_auth] [migration-options] [flags]
Examples:
mmctl {{.Example}}
Arguments:
from_auth:
The authentication service to migrate users accounts from.
Supported options: email, gitlab, google, ldap, office365, saml.
to_auth:
The authentication service to migrate users to.
Supported options: ldap, saml.
migration-options (ldap):
match_field:
The field that is guaranteed to be the same in both authentication services. For example, if the users emails are consistent set to email.
Supported options: email, username.
migration-options (saml):
users_file:
The path of a json file with the usernames and emails of all users to migrate to SAML. The username and email must be the same that the SAML service provider store. And the email must match with the email in mattermost database.
Example json content:
{
"usr1@email.com": "usr.one",
"usr2@email.com": "usr.two"
}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}
`)
UserCmd.AddCommand(
UserActivateCmd,
UserDeactivateCmd,
UserCreateCmd,
UserInviteCmd,
SendPasswordResetEmailCmd,
UpdateUserEmailCmd,
UpdateUsernameCmd,
ChangePasswordUserCmd,
ResetUserMfaCmd,
DeleteUsersCmd,
DeleteAllUsersCmd,
SearchUserCmd,
ListUsersCmd,
VerifyUserEmailWithoutTokenCmd,
UserConvertCmd,
MigrateAuthCmd,
PromoteGuestToUserCmd,
DemoteUserToGuestCmd,
)
RootCmd.AddCommand(UserCmd)
}
func userActivateCmdF(c client.Client, command *cobra.Command, args []string) error {
return changeUsersActiveStatus(c, args, true)
}
func changeUsersActiveStatus(c client.Client, userArgs []string, active bool) error {
var multiErr *multierror.Error
users, err := getUsersFromArgs(c, userArgs)
if err != nil {
printer.PrintError(err.Error())
multiErr = multierror.Append(multiErr, err)
}
for _, user := range users {
if err := changeUserActiveStatus(c, user, active); err != nil {
printer.PrintError(err.Error())
multiErr = multierror.Append(multiErr, err)
}
}
return multiErr.ErrorOrNil()
}
func changeUserActiveStatus(c client.Client, user *model.User, activate bool) error {
if !activate && user.IsSSOUser() {
printer.Print("You must also deactivate user " + user.Id + " in the SSO provider or they will be reactivated on next login or sync.")
}
if _, err := c.UpdateUserActive(user.Id, activate); err != nil {
return fmt.Errorf("unable to change activation status of user: %v", user.Id)
}
return nil
}
func userDeactivateCmdF(c client.Client, cmd *cobra.Command, args []string) error {
return changeUsersActiveStatus(c, args, false)
}
func userCreateCmdF(c client.Client, cmd *cobra.Command, args []string) error {
printer.SetSingle(true)
username, erru := cmd.Flags().GetString("username")
if erru != nil {
return errors.Wrap(erru, "Username is required")
}
email, erre := cmd.Flags().GetString("email")
if erre != nil {
return errors.Wrap(erre, "Email is required")
}
password, errp := cmd.Flags().GetString("password")
if errp != nil {
return errors.Wrap(errp, "Password is required")
}
nickname, _ := cmd.Flags().GetString("nickname")
firstname, _ := cmd.Flags().GetString("firstname")
lastname, _ := cmd.Flags().GetString("lastname")
locale, _ := cmd.Flags().GetString("locale")
systemAdmin, _ := cmd.Flags().GetBool("system-admin")
if !systemAdmin {
systemAdmin, _ = cmd.Flags().GetBool("system_admin")
}
guest, _ := cmd.Flags().GetBool("guest")
emailVerified, _ := cmd.Flags().GetBool("email-verified")
if !emailVerified {
emailVerified, _ = cmd.Flags().GetBool("email_verified")
}
disableWelcomeEmail, _ := cmd.Flags().GetBool("disable-welcome-email")
user := &model.User{
Username: username,
Email: email,
Password: password,
Nickname: nickname,
FirstName: firstname,
LastName: lastname,
Locale: locale,
EmailVerified: emailVerified,
DisableWelcomeEmail: disableWelcomeEmail,
}
ruser, _, err := c.CreateUser(user)
if err != nil {
return errors.New("Unable to create user. Error: " + err.Error())
}
if systemAdmin {
if _, err := c.UpdateUserRoles(ruser.Id, "system_user system_admin"); err != nil {
return errors.New("Unable to update user roles. Error: " + err.Error())
}
} else if guest {
if _, err := c.DemoteUserToGuest(ruser.Id); err != nil {
return errors.Wrapf(err, "Unable to demote use to guest")
}
}
printer.PrintT("Created user {{.Username}}", ruser)
return nil
}
func userInviteCmdF(c client.Client, cmd *cobra.Command, args []string) error {
var errs *multierror.Error
if len(args) < 2 {
return errors.New("expected at least two arguments. See help text for details")
}
email := args[0]
if !model.IsValidEmail(email) {
errs = multierror.Append(errs, fmt.Errorf("invalid email %q", email))
}
teams := getTeamsFromTeamArgs(c, args[1:])
for i, team := range teams {
err := inviteUser(c, email, team, args[i+1])
if err != nil {
errs = multierror.Append(errs, err)
printer.PrintError(err.Error())
}
}
return errs.ErrorOrNil()
}
func inviteUser(c client.Client, email string, team *model.Team, teamArg string) error {
invites := []string{email}
if team == nil {
return fmt.Errorf("can't find team '%v'", teamArg)
}
if _, err := c.InviteUsersToTeam(team.Id, invites); err != nil {
return errors.New("Unable to invite user with email " + email + " to team " + team.Name + ". Error: " + err.Error())
}
printer.Print("Invites may or may not have been sent.")
return nil
}
func sendPasswordResetEmailCmdF(c client.Client, cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("expected at least one argument. See help text for details")
}
var result *multierror.Error
for _, email := range args {
if !model.IsValidEmail(email) {
result = multierror.Append(result, fmt.Errorf("invalid email '%s'", email))
printer.PrintError("Invalid email '" + email + "'")
continue
}
if _, err := c.SendPasswordResetEmail(email); err != nil {
result = multierror.Append(result, fmt.Errorf("unable send reset password email to email %s: %w", email, err))
printer.PrintError("Unable send reset password email to email " + email + ". Error: " + err.Error())
}
}
return result.ErrorOrNil()
}
func updateUserEmailCmdF(c client.Client, cmd *cobra.Command, args []string) error {
printer.SetSingle(true)
if len(args) != 2 {
return errors.New("expected two arguments. See help text for details")
}
newEmail := args[1]
if !model.IsValidEmail(newEmail) {
return errors.New("invalid email: '" + newEmail + "'")
}
user, err := getUserFromArg(c, args[0])
if err != nil {
return err
}
user.Email = newEmail
ruser, _, err := c.UpdateUser(user)
if err != nil {
return errors.New(err.Error())
}
printer.PrintT("User {{.Username}} updated successfully", ruser)
return nil
}
func updateUsernameCmdF(c client.Client, cmd *cobra.Command, args []string) error {
printer.SetSingle(true)
newUsername := args[1]
if !model.IsValidUsername(newUsername) {
return errors.New("invalid username: '" + newUsername + "'")
}
user := getUserFromUserArg(c, args[0])
if user == nil {
return errors.New("unable to find user '" + args[0] + "'")
}
user.Username = newUsername
ruser, _, err := c.UpdateUser(user)
if err != nil {
return errors.New(err.Error())
}
printer.PrintT("User {{.Username}} updated successfully", ruser)
return nil
}
func changePasswordUserCmdF(c client.Client, cmd *cobra.Command, args []string) error {
password, _ := cmd.Flags().GetString("password")
current, _ := cmd.Flags().GetString("current")
hashed, _ := cmd.Flags().GetBool("hashed")
if password == "" {
if err := getConfirmation("Are you changing your own password?", false); err == nil {
fmt.Printf("Current password: ")
var err error
current, err = getPasswordFromStdin()
if err != nil {
return errors.Wrap(err, "couldn't read password")
}
}
fmt.Printf("New password: ")
var err error
password, err = getPasswordFromStdin()
if err != nil {
return errors.Wrap(err, "couldn't read password")
}
}
user, err := getUserFromArg(c, args[0])
if err != nil {
return err
}
if hashed {
if _, err := c.UpdateUserHashedPassword(user.Id, password); err != nil {
return errors.Wrap(err, "changing user hashed password failed")
}
} else {
if _, err := c.UpdateUserPassword(user.Id, current, password); err != nil {
return errors.Wrap(err, "changing user password failed")
}
}
printer.PrintT("Password for user {{.Username}} successfully changed", user)
return nil
}
func resetUserMfaCmdF(c client.Client, cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("expected at least one argument. See help text for details")
}
var result *multierror.Error
users, err := getUsersFromArgs(c, args)
if err != nil {
result = multierror.Append(result, err)
}
for _, user := range users {
if _, err := c.UpdateUserMfa(user.Id, "", false); err != nil {
result = multierror.Append(result, fmt.Errorf("unable to reset user %q MFA. Error: %w", user.Id, err))
}
}
return result.ErrorOrNil()
}
func deleteUsersCmdF(c client.Client, cmd *cobra.Command, args []string) error {
confirmFlag, _ := cmd.Flags().GetBool("confirm")
if !confirmFlag {
if err := getConfirmation("Are you sure you want to delete the users specified? All data will be permanently deleted?", true); err != nil {
return err
}
}
users, err := getUsersFromArgs(c, args)
if err != nil {
printer.PrintError(err.Error())
}
for i, user := range users {
if user == nil {
printer.PrintError("Unable to find user '" + args[i] + "'")
continue
}
if res, err := c.PermanentDeleteUser(user.Id); err != nil {
printer.PrintError("Unable to delete user '" + user.Username + "' error: " + err.Error())
} else {
// res.StatusCode is checked for 202 to identify issues with file deletion.
if res.StatusCode == http.StatusAccepted {
printer.PrintError("There were issues with deleting profile image of the user. Please delete it manually. Id: " + user.Id)
}
printer.PrintT("Deleted user '{{.Username}}'", user)
}
}
return nil
}
func deleteAllUsersCmdF(c client.Client, cmd *cobra.Command, args []string) error {
confirmFlag, _ := cmd.Flags().GetBool("confirm")
if !confirmFlag {
if err := getConfirmation("Are you sure you want to permanently delete all user accounts?", true); err != nil {
return err
}
}
if _, err := c.PermanentDeleteAllUsers(); err != nil {
return err
}
defer printer.Print("All users successfully deleted")
return nil
}
func searchUserCmdF(c client.Client, cmd *cobra.Command, args []string) error {
printer.SetSingle(true)
if len(args) < 1 {
return errors.New("expected at least one argument. See help text for details")
}
users, err := getUsersFromArgs(c, args)
if err != nil {
printer.PrintError(err.Error())
}
for i, user := range users {
tpl := `id: {{.Id}}
username: {{.Username}}
nickname: {{.Nickname}}
position: {{.Position}}
first_name: {{.FirstName}}
last_name: {{.LastName}}
email: {{.Email}}
auth_service: {{.AuthService}}`
if i > 0 {
tpl = "------------------------------\n" + tpl
}
printer.PrintT(tpl, user)
}
return nil
}
func listUsersCmdF(c client.Client, command *cobra.Command, args []string) error {
page, err := command.Flags().GetInt("page")
if err != nil {
return err
}
perPage, err := command.Flags().GetInt("per-page")
if err != nil {
return err
}
showAll, err := command.Flags().GetBool("all")
if err != nil {
return err
}
teamName, err := command.Flags().GetString("team")
if err != nil {
return err
}
if showAll {
page = 0
}
var team *model.Team
if teamName != "" {
var err error
team, _, err = c.GetTeamByName(teamName, "")
if err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to get team %s", teamName))
}
}
tpl := `{{.Id}}: {{.Username}} ({{.Email}})`
for {
var users []*model.User
var err error
if team != nil {
users, _, err = c.GetUsersInTeam(team.Id, page, perPage, "")
if err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to fetch users for team %s", teamName))
}
} else {
users, _, err = c.GetUsers(page, perPage, "")
if err != nil {
return errors.Wrap(err, "Failed to fetch users")
}
}
if len(users) == 0 {
break
}
for _, user := range users {
printer.PrintT(tpl, user)
}
if !showAll {
break
}
page++
}
return nil
}
func verifyUserEmailWithoutTokenCmdF(c client.Client, cmd *cobra.Command, userArgs []string) error {
var result *multierror.Error
users, err := getUsersFromArgs(c, userArgs)
if err != nil {
result = multierror.Append(result, err)
}
for _, user := range users {
if newUser, _, err := c.VerifyUserEmailWithoutToken(user.Id); err != nil {
result = multierror.Append(result, fmt.Errorf("unable to verify user %s email: %w", user.Id, err))
} else {
printer.PrintT("User {{.Username}} verified", newUser)
}
}
return result.ErrorOrNil()
}
func userConvertCmdF(c client.Client, cmd *cobra.Command, userArgs []string) error {
toBot, _ := cmd.Flags().GetBool("bot")
toUser, _ := cmd.Flags().GetBool("user")
if !(toUser || toBot) {
return fmt.Errorf("either %q flag or %q flag should be provided", "user", "bot")
}
if toBot {
return convertUserToBot(c, cmd, userArgs)
}
return convertBotToUser(c, cmd, userArgs)
}
func convertUserToBot(c client.Client, _ *cobra.Command, userArgs []string) error {
users, err := getUsersFromArgs(c, userArgs)
if err != nil {
printer.PrintError(err.Error())
}
for _, user := range users {
bot, _, err := c.ConvertUserToBot(user.Id)
if err != nil {
printer.PrintError(err.Error())
continue
}
printer.PrintT("{{.Username}} converted to bot.", bot)
}
return nil
}
func convertBotToUser(c client.Client, cmd *cobra.Command, userArgs []string) error {
user, err := getUserFromArg(c, userArgs[0])
if err != nil {
return err
}
password, _ := cmd.Flags().GetString("password")
if password == "" {
return errors.New("password is required")
}
up := &model.UserPatch{Password: &password}
username, _ := cmd.Flags().GetString("username")
if username == "" {
if user.Username == "" {
return errors.New("username is empty")
}
} else {
up.Username = model.NewString(username)
}
email, _ := cmd.Flags().GetString("email")
if email == "" {
if user.Email == "" {
return errors.New("email is empty")
}
} else {
up.Email = model.NewString(email)
}
nickname, _ := cmd.Flags().GetString("nickname")
if nickname != "" {
up.Nickname = model.NewString(nickname)
}
firstname, _ := cmd.Flags().GetString("firstname")
if firstname != "" {
up.FirstName = model.NewString(firstname)
}
lastname, _ := cmd.Flags().GetString("lastname")
if lastname != "" {
up.LastName = model.NewString(lastname)
}
locale, _ := cmd.Flags().GetString("locale")
if locale != "" {
up.Locale = model.NewString(locale)
}
systemAdmin, _ := cmd.Flags().GetBool("system-admin")
if !systemAdmin {
systemAdmin, _ = cmd.Flags().GetBool("system_admin")
}
user, _, err = c.ConvertBotToUser(user.Id, up, systemAdmin)
if err != nil {
return err
}
printer.PrintT("{{.Username}} converted to user.", user)
return nil
}
func migrateAuthCmdF(c client.Client, cmd *cobra.Command, userArgs []string) error {
if userArgs[1] == "saml" {
return migrateAuthToSamlCmdF(c, cmd, userArgs)
}
return migrateAuthToLdapCmdF(c, cmd, userArgs)
}
func migrateAuthToSamlCmdF(c client.Client, cmd *cobra.Command, userArgs []string) error {
fromAuth := userArgs[0]
auto, _ := cmd.Flags().GetBool("auto")
confirm, _ := cmd.Flags().GetBool("confirm")
if auto && !confirm {
if err := getConfirmation("You are about to perform an automatic \""+fromAuth+" to saml\" migration. This must only be done if your current Mattermost users with "+fromAuth+" auth have the same username and email in your SAML service. Otherwise, provide the usernames and emails from your SAML Service using the \"users file\" without the \"--auto\" option.\n\nDo you want to proceed with automatic migration anyway?", false); err != nil {
return err
}
}
matches := map[string]string{}
if !auto {
matchesFile := userArgs[2]
file, err := ioutil.ReadFile(matchesFile)
if err != nil {
return fmt.Errorf("could not read file: %w", err)
}
if err := json.Unmarshal(file, &matches); err != nil {
return fmt.Errorf("invalid json: %w", err)
}
}
if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "ldap" && fromAuth != "google" && fromAuth != "office365") {
return errors.New("invalid from_auth argument")
}
resp, err := c.MigrateAuthToSaml(fromAuth, matches, auto)
if err != nil {
return err
} else if resp.StatusCode == http.StatusOK {
printer.Print("Successfully migrated accounts.")
}
return nil
}
func migrateAuthToLdapCmdF(c client.Client, cmd *cobra.Command, userArgs []string) error {
fromAuth := userArgs[0]
if len(fromAuth) == 0 || (fromAuth != "email" && fromAuth != "gitlab" && fromAuth != "saml" && fromAuth != "google" && fromAuth != "office365") { // nolint:goconst
return errors.New("invalid from_auth argument")
}
matchField := userArgs[2]
if len(matchField) == 0 || (matchField != "email" && matchField != "username") {
return errors.New("invalid match_field argument")
}
force, _ := cmd.Flags().GetBool("force")
resp, err := c.MigrateAuthToLdap(fromAuth, matchField, force)
if err != nil {
return err
} else if resp.StatusCode == http.StatusOK {
printer.Print("Successfully migrated accounts.")
}
return nil
}
func promoteGuestToUserCmdF(c client.Client, _ *cobra.Command, userArgs []string) error {
for i, user := range getUsersFromUserArgs(c, userArgs) {
if user == nil {
printer.PrintError(fmt.Sprintf("can't find guest '%v'", userArgs[i]))
continue
}
if _, err := c.PromoteGuestToUser(user.Id); err != nil {
printer.PrintError(fmt.Sprintf("unable to promote guest %s: %s", userArgs[i], err))
continue
}
printer.PrintT("User {{.Username}} promoted.", user)
}
return nil
}
func demoteUserToGuestCmdF(c client.Client, _ *cobra.Command, userArgs []string) error {
var errs *multierror.Error
for i, user := range getUsersFromUserArgs(c, userArgs) {
if user == nil {
err := fmt.Errorf("can't find user '%s'", userArgs[i])
errs = multierror.Append(errs, err)
printer.PrintError(err.Error())
continue
}
if _, err := c.DemoteUserToGuest(user.Id); err != nil {
err = fmt.Errorf("unable to demote user %s: %w", userArgs[i], err)
errs = multierror.Append(errs, err)
printer.PrintError(err.Error())
continue
}
printer.PrintT("User {{.Username}} demoted.", user)
}
return errs.ErrorOrNil()
}