forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mattermost.go
1218 lines (1014 loc) · 33.8 KB
/
mattermost.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 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package main
import (
"bufio"
"flag"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
"time"
l4g "github.com/alecthomas/log4go"
"github.com/mattermost/platform/api"
"github.com/mattermost/platform/einterfaces"
"github.com/mattermost/platform/manualtesting"
"github.com/mattermost/platform/model"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils"
"github.com/mattermost/platform/web"
// Plugins
_ "github.com/mattermost/platform/model/gitlab"
// Enterprise Deps
_ "github.com/dgryski/dgoogauth"
_ "github.com/go-ldap/ldap"
_ "github.com/mattermost/rsc/qr"
)
//ENTERPRISE_IMPORTS
var flagCmdUpdateDb30 bool
var flagCmdCreateTeam bool
var flagCmdCreateUser bool
var flagCmdAssignRole bool
var flagCmdJoinTeam bool
var flagCmdVersion bool
var flagCmdRunWebClientTests bool
var flagCmdRunJavascriptClientTests bool
var flagCmdResetPassword bool
var flagCmdResetMfa bool
var flagCmdPermanentDeleteUser bool
var flagCmdPermanentDeleteTeam bool
var flagCmdPermanentDeleteAllUsers bool
var flagCmdResetDatabase bool
var flagUsername string
var flagCmdUploadLicense bool
var flagConfigFile string
var flagLicenseFile string
var flagEmail string
var flagPassword string
var flagTeamName string
var flagRole string
var flagRunCmds bool
func doLoadConfig(filename string) (err string) {
defer func() {
if r := recover(); r != nil {
err = r.(string)
}
}()
utils.LoadConfig(filename)
return ""
}
func main() {
parseCmds()
utils.InitTranslations()
if errstr := doLoadConfig(flagConfigFile); errstr != "" {
l4g.Exit(utils.T("mattermost.unable_to_load_config"), errstr)
return
}
if flagRunCmds {
utils.ConfigureCmdLineLog()
}
pwd, _ := os.Getwd()
l4g.Info(utils.T("mattermost.current_version"), model.CurrentVersion, model.BuildNumber, model.BuildDate, model.BuildHash, model.BuildHashEnterprise)
l4g.Info(utils.T("mattermost.entreprise_enabled"), model.BuildEnterpriseReady)
l4g.Info(utils.T("mattermost.working_dir"), pwd)
l4g.Info(utils.T("mattermost.config_file"), utils.FindConfigFile(flagConfigFile))
// Special case for upgrading the db to 3.0
// ADDED for 3.0 REMOVE for 3.4
cmdUpdateDb30()
api.NewServer()
api.InitApi()
web.InitWeb()
if model.BuildEnterpriseReady == "true" {
api.LoadLicense()
}
if !utils.IsLicensed && len(utils.Cfg.SqlSettings.DataSourceReplicas) > 1 {
l4g.Critical(utils.T("store.sql.read_replicas_not_licensed.critical"))
return
}
if flagRunCmds {
runCmds()
} else {
api.StartServer()
// If we allow testing then listen for manual testing URL hits
if utils.Cfg.ServiceSettings.EnableTesting {
manualtesting.InitManualTesting()
}
setDiagnosticId()
go runSecurityAndDiagnosticsJob()
if einterfaces.GetComplianceInterface() != nil {
einterfaces.GetComplianceInterface().StartComplianceDailyJob()
}
// wait for kill signal before attempting to gracefully shutdown
// the running service
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-c
api.StopServer()
}
}
func setDiagnosticId() {
if result := <-api.Srv.Store.System().Get(); result.Err == nil {
props := result.Data.(model.StringMap)
id := props[model.SYSTEM_DIAGNOSTIC_ID]
if len(id) == 0 {
id = model.NewId()
systemId := &model.System{Name: model.SYSTEM_DIAGNOSTIC_ID, Value: id}
<-api.Srv.Store.System().Save(systemId)
}
utils.CfgDiagnosticId = id
}
}
func runSecurityAndDiagnosticsJob() {
for {
if *utils.Cfg.ServiceSettings.EnableSecurityFixAlert {
if result := <-api.Srv.Store.System().Get(); result.Err == nil {
props := result.Data.(model.StringMap)
lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0)
currentTime := model.GetMillis()
if (currentTime - lastSecurityTime) > 1000*60*60*24*1 {
l4g.Debug(utils.T("mattermost.security_checks.debug"))
v := url.Values{}
v.Set(utils.PROP_DIAGNOSTIC_ID, utils.CfgDiagnosticId)
v.Set(utils.PROP_DIAGNOSTIC_BUILD, model.CurrentVersion+"."+model.BuildNumber)
v.Set(utils.PROP_DIAGNOSTIC_ENTERPRISE_READY, model.BuildEnterpriseReady)
v.Set(utils.PROP_DIAGNOSTIC_DATABASE, utils.Cfg.SqlSettings.DriverName)
v.Set(utils.PROP_DIAGNOSTIC_OS, runtime.GOOS)
v.Set(utils.PROP_DIAGNOSTIC_CATEGORY, utils.VAL_DIAGNOSTIC_CATEGORY_DEFAULT)
if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 {
v.Set(utils.PROP_DIAGNOSTIC_UNIT_TESTS, "1")
} else {
v.Set(utils.PROP_DIAGNOSTIC_UNIT_TESTS, "0")
}
systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)}
if lastSecurityTime == 0 {
<-api.Srv.Store.System().Save(systemSecurityLastTime)
} else {
<-api.Srv.Store.System().Update(systemSecurityLastTime)
}
if ucr := <-api.Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil {
v.Set(utils.PROP_DIAGNOSTIC_USER_COUNT, strconv.FormatInt(ucr.Data.(int64), 10))
}
if ucr := <-api.Srv.Store.User().GetTotalActiveUsersCount(); ucr.Err == nil {
v.Set(utils.PROP_DIAGNOSTIC_ACTIVE_USER_COUNT, strconv.FormatInt(ucr.Data.(int64), 10))
}
res, err := http.Get(utils.DIAGNOSTIC_URL + "/security?" + v.Encode())
if err != nil {
l4g.Error(utils.T("mattermost.security_info.error"))
return
}
bulletins := model.SecurityBulletinsFromJson(res.Body)
for _, bulletin := range bulletins {
if bulletin.AppliesToVersion == model.CurrentVersion {
if props["SecurityBulletin_"+bulletin.Id] == "" {
if results := <-api.Srv.Store.User().GetSystemAdminProfiles(); results.Err != nil {
l4g.Error(utils.T("mattermost.system_admins.error"))
return
} else {
users := results.Data.(map[string]*model.User)
resBody, err := http.Get(utils.DIAGNOSTIC_URL + "/bulletins/" + bulletin.Id)
if err != nil {
l4g.Error(utils.T("mattermost.security_bulletin.error"))
return
}
body, err := ioutil.ReadAll(resBody.Body)
res.Body.Close()
if err != nil || resBody.StatusCode != 200 {
l4g.Error(utils.T("mattermost.security_bulletin_read.error"))
return
}
for _, user := range users {
l4g.Info(utils.T("mattermost.send_bulletin.info"), bulletin.Id, user.Email)
utils.SendMail(user.Email, utils.T("mattermost.bulletin.subject"), string(body))
}
}
bulletinSeen := &model.System{Name: "SecurityBulletin_" + bulletin.Id, Value: bulletin.Id}
<-api.Srv.Store.System().Save(bulletinSeen)
}
}
}
}
}
}
time.Sleep(time.Hour * 4)
}
}
func parseCmds() {
flag.Usage = func() {
fmt.Fprintln(os.Stderr, usage)
}
flag.StringVar(&flagConfigFile, "config", "config.json", "")
flag.StringVar(&flagUsername, "username", "", "")
flag.StringVar(&flagLicenseFile, "license", "", "")
flag.StringVar(&flagEmail, "email", "", "")
flag.StringVar(&flagPassword, "password", "", "")
flag.StringVar(&flagTeamName, "team_name", "", "")
flag.StringVar(&flagRole, "role", "", "")
flag.BoolVar(&flagCmdUpdateDb30, "upgrade_db_30", false, "")
flag.BoolVar(&flagCmdCreateTeam, "create_team", false, "")
flag.BoolVar(&flagCmdCreateUser, "create_user", false, "")
flag.BoolVar(&flagCmdAssignRole, "assign_role", false, "")
flag.BoolVar(&flagCmdJoinTeam, "join_team", false, "")
flag.BoolVar(&flagCmdVersion, "version", false, "")
flag.BoolVar(&flagCmdRunWebClientTests, "run_web_client_tests", false, "")
flag.BoolVar(&flagCmdRunJavascriptClientTests, "run_javascript_client_tests", false, "")
flag.BoolVar(&flagCmdResetPassword, "reset_password", false, "")
flag.BoolVar(&flagCmdResetMfa, "reset_mfa", false, "")
flag.BoolVar(&flagCmdPermanentDeleteUser, "permanent_delete_user", false, "")
flag.BoolVar(&flagCmdPermanentDeleteTeam, "permanent_delete_team", false, "")
flag.BoolVar(&flagCmdPermanentDeleteAllUsers, "permanent_delete_all_users", false, "")
flag.BoolVar(&flagCmdResetDatabase, "reset_database", false, "")
flag.BoolVar(&flagCmdUploadLicense, "upload_license", false, "")
flag.Parse()
flagRunCmds = (flagCmdCreateTeam ||
flagCmdCreateUser ||
flagCmdAssignRole ||
flagCmdJoinTeam ||
flagCmdResetPassword ||
flagCmdResetMfa ||
flagCmdVersion ||
flagCmdRunWebClientTests ||
flagCmdRunJavascriptClientTests ||
flagCmdPermanentDeleteUser ||
flagCmdPermanentDeleteTeam ||
flagCmdPermanentDeleteAllUsers ||
flagCmdResetDatabase ||
flagCmdUploadLicense)
}
func runCmds() {
cmdVersion()
cmdRunClientTests()
cmdCreateTeam()
cmdCreateUser()
cmdAssignRole()
cmdJoinTeam()
cmdResetPassword()
cmdResetMfa()
cmdPermDeleteUser()
cmdPermDeleteTeam()
cmdPermDeleteAllUsers()
cmdResetDatabase()
cmdUploadLicense()
}
type TeamForUpgrade struct {
Id string
Name string
}
func setupClientTests() {
*utils.Cfg.TeamSettings.EnableOpenServer = true
}
func executeTestCommand(cmd *exec.Cmd) {
cmdOutPipe, err := cmd.StdoutPipe()
if err != nil {
l4g.Error("Failed to run tests")
os.Exit(1)
}
cmdOutReader := bufio.NewScanner(cmdOutPipe)
go func() {
for cmdOutReader.Scan() {
fmt.Println(cmdOutReader.Text())
}
}()
if err := cmd.Run(); err != nil {
l4g.Error("Client Tests failed")
os.Exit(1)
}
}
func runWebClientTests() {
os.Chdir("webapp")
cmd := exec.Command("npm", "test")
executeTestCommand(cmd)
}
func runJavascriptClientTests() {
os.Chdir("../mattermost-driver-javascript")
cmd := exec.Command("npm", "test")
executeTestCommand(cmd)
}
func cmdRunClientTests() {
if flagCmdRunWebClientTests {
api.StartServer()
setupClientTests()
runWebClientTests()
api.StopServer()
}
if flagCmdRunJavascriptClientTests {
api.StartServer()
setupClientTests()
runJavascriptClientTests()
api.StopServer()
}
}
// ADDED for 3.0 REMOVE for 3.4
func cmdUpdateDb30() {
if flagCmdUpdateDb30 {
api.Srv = &api.Server{}
api.Srv.Store = store.NewSqlStoreForUpgrade30()
store := api.Srv.Store.(*store.SqlStore)
utils.InitHTML()
l4g.Info("Attempting to run special upgrade of the database schema to version 3.0 for user model changes")
time.Sleep(time.Second)
if !store.DoesColumnExist("Users", "TeamId") {
fmt.Println("**WARNING** the database schema appears to be upgraded to 3.0")
flushLogAndExit(1)
}
if !(store.SchemaVersion == "2.2.0" ||
store.SchemaVersion == "2.1.0" ||
store.SchemaVersion == "2.0.0") {
fmt.Println("**WARNING** the database schema needs to be version 2.2.0, 2.1.0 or 2.0.0 to upgrade")
flushLogAndExit(1)
}
var confirmBackup string
fmt.Println("\nPlease see http://www.mattermost.org/upgrade-to-3-0/")
fmt.Println("**WARNING** This upgrade process will be irreversible.")
fmt.Print("Have you performed a database backup? (YES/NO): ")
fmt.Scanln(&confirmBackup)
if confirmBackup != "YES" {
fmt.Fprintln(os.Stderr, "ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
var flagTeamName string
var teams []*TeamForUpgrade
if _, err := store.GetMaster().Select(&teams, "SELECT Id, Name FROM Teams"); err != nil {
l4g.Error("Failed to load all teams details=%v", err)
flushLogAndExit(1)
}
fmt.Println(fmt.Sprintf("We found %v teams.", len(teams)))
for _, team := range teams {
fmt.Println(team.Name)
}
fmt.Print("Please pick a primary team from the list above: ")
fmt.Scanln(&flagTeamName)
var team *TeamForUpgrade
for _, t := range teams {
if t.Name == flagTeamName {
team = t
break
}
}
if team == nil {
l4g.Error("Failed to find primary team details")
flushLogAndExit(1)
}
l4g.Info("Starting special 3.0 database upgrade with performed_backup=YES team_name=%v", team.Name)
l4g.Info("Primary team %v will be left unchanged", team.Name)
l4g.Info("Upgrading primary team %v", team.Name)
uniqueEmails := make(map[string]bool)
uniqueUsernames := make(map[string]bool)
uniqueAuths := make(map[string]bool)
primaryUsers := convertTeamTo30(team.Name, team, uniqueEmails, uniqueUsernames, uniqueAuths)
l4g.Info("Upgraded %v users", len(primaryUsers))
for _, otherTeam := range teams {
if otherTeam.Id != team.Id {
l4g.Info("Upgrading team %v", otherTeam.Name)
users := convertTeamTo30(team.Name, otherTeam, uniqueEmails, uniqueUsernames, uniqueAuths)
l4g.Info("Upgraded %v users", len(users))
}
}
l4g.Info("Altering other scheme changes needed 3.0 for user model changes")
if _, err := store.GetMaster().Exec(`
UPDATE Channels
SET
TeamId = ''
WHERE
Type = 'D'
`,
); err != nil {
l4g.Error("Failed to update direct channel types details=%v", err)
flushLogAndExit(1)
}
if _, err := store.GetMaster().Exec(`
UPDATE Users
SET
AuthData = NULL
WHERE
AuthData = ''
`,
); err != nil {
l4g.Error("Failed to update AuthData types details=%v", err)
flushLogAndExit(1)
}
extraLength := store.GetMaxLengthOfColumnIfExists("Audits", "ExtraInfo")
if len(extraLength) > 0 && extraLength != "1024" {
store.AlterColumnTypeIfExists("Audits", "ExtraInfo", "VARCHAR(1024)", "VARCHAR(1024)")
}
actionLength := store.GetMaxLengthOfColumnIfExists("Audits", "Action")
if len(actionLength) > 0 && actionLength != "512" {
store.AlterColumnTypeIfExists("Audits", "Action", "VARCHAR(512)", "VARCHAR(512)")
}
if store.DoesColumnExist("Sessions", "TeamId") {
store.RemoveColumnIfExists("Sessions", "TeamId")
store.GetMaster().Exec(`TRUNCATE Sessions`)
}
// ADDED for 2.2 REMOVE for 2.6
store.CreateColumnIfNotExists("Users", "MfaActive", "tinyint(1)", "boolean", "0")
store.CreateColumnIfNotExists("Users", "MfaSecret", "varchar(128)", "character varying(128)", "")
// ADDED for 2.2 REMOVE for 2.6
if store.DoesColumnExist("Users", "TeamId") {
store.RemoveIndexIfExists("idx_users_team_id", "Users")
store.CreateUniqueIndexIfNotExists("idx_users_email_unique", "Users", "Email")
store.CreateUniqueIndexIfNotExists("idx_users_username_unique", "Users", "Username")
store.CreateUniqueIndexIfNotExists("idx_users_authdata_unique", "Users", "AuthData")
store.RemoveColumnIfExists("Teams", "AllowTeamListing")
store.RemoveColumnIfExists("Users", "TeamId")
}
l4g.Info("Finished running special upgrade of the database schema to version 3.0 for user model changes")
if result := <-store.System().Update(&model.System{Name: "Version", Value: model.CurrentVersion}); result.Err != nil {
l4g.Error("Failed to update system schema version details=%v", result.Err)
flushLogAndExit(1)
}
l4g.Info(utils.T("store.sql.upgraded.warn"), model.CurrentVersion)
fmt.Println("**SUCCESS** with upgrade")
flushLogAndExit(0)
}
}
type UserForUpgrade struct {
Id string
Username string
Email string
Roles string
TeamId string
AuthData *string
}
func convertTeamTo30(primaryTeamName string, team *TeamForUpgrade, uniqueEmails map[string]bool, uniqueUsernames map[string]bool, uniqueAuths map[string]bool) []*UserForUpgrade {
store := api.Srv.Store.(*store.SqlStore)
var users []*UserForUpgrade
if _, err := store.GetMaster().Select(&users, "SELECT Users.Id, Users.Username, Users.Email, Users.Roles, Users.TeamId, Users.AuthData FROM Users WHERE Users.TeamId = :TeamId", map[string]interface{}{"TeamId": team.Id}); err != nil {
l4g.Error("Failed to load profiles for team details=%v", err)
flushLogAndExit(1)
}
var members []*model.TeamMember
if result := <-api.Srv.Store.Team().GetMembers(team.Id); result.Err != nil {
l4g.Error("Failed to load team membership details=%v", result.Err)
flushLogAndExit(1)
} else {
members = result.Data.([]*model.TeamMember)
}
for _, user := range users {
shouldUpdateUser := false
previousRole := user.Roles
previousEmail := user.Email
previousUsername := user.Username
member := &model.TeamMember{
TeamId: team.Id,
UserId: user.Id,
}
if model.IsInRole(user.Roles, model.ROLE_TEAM_ADMIN) {
member.Roles = model.ROLE_TEAM_ADMIN
user.Roles = ""
shouldUpdateUser = true
}
exists := false
for _, member := range members {
if member.UserId == user.Id {
exists = true
break
}
}
if !exists {
if result := <-api.Srv.Store.Team().SaveMember(member); result.Err != nil {
l4g.Error("Failed to save membership for %v details=%v", user.Email, result.Err)
flushLogAndExit(1)
}
}
err := api.MoveFile(
"teams/"+team.Id+"/users/"+user.Id+"/profile.png",
"users/"+user.Id+"/profile.png",
)
if err != nil {
l4g.Warn("No profile image to move for %v", user.Email)
}
if uniqueEmails[user.Email] {
shouldUpdateUser = true
emailParts := strings.Split(user.Email, "@")
if len(emailParts) == 2 {
user.Email = emailParts[0] + "+" + team.Name + "@" + emailParts[1]
} else {
user.Email = user.Email + "." + team.Name
}
if len(user.Email) > 127 {
user.Email = user.Email[:127]
}
}
if uniqueUsernames[user.Username] {
shouldUpdateUser = true
user.Username = team.Name + "." + user.Username
if len(user.Username) > 63 {
user.Username = user.Username[:63]
}
}
if user.AuthData != nil && *user.AuthData != "" && uniqueAuths[*user.AuthData] {
shouldUpdateUser = true
}
if shouldUpdateUser {
if _, err := store.GetMaster().Exec(`
UPDATE Users
SET
Email = :Email,
Username = :Username,
Roles = :Roles,
AuthService = '',
AuthData = NULL
WHERE
Id = :Id
`,
map[string]interface{}{
"Email": user.Email,
"Username": user.Username,
"Roles": user.Roles,
"Id": user.Id,
},
); err != nil {
l4g.Error("Failed to update user %v details=%v", user.Email, err)
flushLogAndExit(1)
}
l4g.Info("modified user_id=%v, changed email from=%v to=%v, changed username from=%v to %v changed roles from=%v to=%v", user.Id, previousEmail, user.Email, previousUsername, user.Username, previousRole, user.Roles)
emailChanged := previousEmail != user.Email
usernameChanged := previousUsername != user.Username
if emailChanged || usernameChanged {
bodyPage := utils.NewHTMLTemplate("upgrade_30_body", "")
EmailChanged := ""
UsernameChanged := ""
if emailChanged {
EmailChanged = "true"
}
if usernameChanged {
UsernameChanged = "true"
}
bodyPage.Html["Info"] = template.HTML(utils.T("api.templates.upgrade_30_body.info",
map[string]interface{}{
"SiteName": utils.ClientCfg["SiteName"],
"TeamName": team.Name,
"Email": user.Email,
"Username": user.Username,
"EmailChanged": EmailChanged,
"UsernameChanged": UsernameChanged,
}))
utils.SendMail(
previousEmail,
utils.T("api.templates.upgrade_30_subject.info"),
bodyPage.Render(),
)
}
}
uniqueEmails[user.Email] = true
uniqueUsernames[user.Username] = true
if user.AuthData != nil && *user.AuthData != "" {
uniqueAuths[*user.AuthData] = true
}
}
return users
}
func cmdCreateTeam() {
if flagCmdCreateTeam {
if len(flagTeamName) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -team_name")
flag.Usage()
os.Exit(1)
}
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
c := getMockContext()
team := &model.Team{}
team.DisplayName = flagTeamName
team.Name = flagTeamName
team.Email = flagEmail
team.Type = model.TEAM_OPEN
api.CreateTeam(c, team)
if c.Err != nil {
if c.Err.Id != "store.sql_team.save.domain_exists.app_error" {
l4g.Error("%v", c.Err)
flushLogAndExit(1)
}
}
os.Exit(0)
}
}
func cmdCreateUser() {
if flagCmdCreateUser {
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
if len(flagPassword) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -password")
flag.Usage()
os.Exit(1)
}
var team *model.Team
user := &model.User{}
user.Email = flagEmail
user.Password = flagPassword
if len(flagUsername) == 0 {
splits := strings.Split(strings.Replace(flagEmail, "@", " ", -1), " ")
user.Username = splits[0]
} else {
user.Username = flagUsername
}
if len(flagTeamName) > 0 {
if result := <-api.Srv.Store.Team().GetByName(flagTeamName); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
team = result.Data.(*model.Team)
}
}
ruser, err := api.CreateUser(user)
if err != nil {
if err.Id != "store.sql_user.save.email_exists.app_error" {
l4g.Error("%v", err)
flushLogAndExit(1)
}
}
if team != nil {
err = api.JoinUserToTeam(team, ruser)
if err != nil {
l4g.Error("%v", err)
flushLogAndExit(1)
}
}
os.Exit(0)
}
}
func cmdVersion() {
if flagCmdVersion {
fmt.Fprintln(os.Stderr, "Version: "+model.CurrentVersion)
fmt.Fprintln(os.Stderr, "Build Number: "+model.BuildNumber)
fmt.Fprintln(os.Stderr, "Build Date: "+model.BuildDate)
fmt.Fprintln(os.Stderr, "Build Hash: "+model.BuildHash)
fmt.Fprintln(os.Stderr, "Build Enterprise Ready: "+model.BuildEnterpriseReady)
os.Exit(0)
}
}
func cmdAssignRole() {
if flagCmdAssignRole {
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
if !model.IsValidUserRoles(flagRole) {
fmt.Fprintln(os.Stderr, "flag invalid argument: -role")
flag.Usage()
os.Exit(1)
}
c := getMockContext()
var user *model.User
if result := <-api.Srv.Store.User().GetByEmail(flagEmail); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
if !user.IsInRole(flagRole) {
api.UpdateUserRoles(c, user, flagRole)
}
os.Exit(0)
}
}
func cmdJoinTeam() {
if flagCmdJoinTeam {
if len(flagTeamName) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
var team *model.Team
if result := <-api.Srv.Store.Team().GetByName(flagTeamName); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
team = result.Data.(*model.Team)
}
var user *model.User
if result := <-api.Srv.Store.User().GetByEmail(flagEmail); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
err := api.JoinUserToTeam(team, user)
if err != nil {
l4g.Error("%v", err)
flushLogAndExit(1)
}
os.Exit(0)
}
}
func cmdResetPassword() {
if flagCmdResetPassword {
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
if len(flagPassword) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -password")
flag.Usage()
os.Exit(1)
}
if len(flagPassword) < 5 {
fmt.Fprintln(os.Stderr, "flag invalid argument needs to be more than 4 characters: -password")
flag.Usage()
os.Exit(1)
}
var user *model.User
if result := <-api.Srv.Store.User().GetByEmail(flagEmail); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
if result := <-api.Srv.Store.User().UpdatePassword(user.Id, model.HashPassword(flagPassword)); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
}
os.Exit(0)
}
}
func cmdResetMfa() {
if flagCmdResetMfa {
if len(flagEmail) == 0 && len(flagUsername) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email OR -username")
flag.Usage()
os.Exit(1)
}
var user *model.User
if len(flagEmail) > 0 {
if result := <-api.Srv.Store.User().GetByEmail(flagEmail); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
} else {
if result := <-api.Srv.Store.User().GetByUsername(flagUsername); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
}
if err := api.DeactivateMfa(user.Id); err != nil {
l4g.Error("%v", err)
flushLogAndExit(1)
}
os.Exit(0)
}
}
func cmdPermDeleteUser() {
if flagCmdPermanentDeleteUser {
if len(flagEmail) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -email")
flag.Usage()
os.Exit(1)
}
c := getMockContext()
var user *model.User
if result := <-api.Srv.Store.User().GetByEmail(flagEmail); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
user = result.Data.(*model.User)
}
var confirmBackup string
fmt.Print("Have you performed a database backup? (YES/NO): ")
fmt.Scanln(&confirmBackup)
if confirmBackup != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
var confirm string
fmt.Printf("Are you sure you want to delete the user %v? All data will be permanently deleted? (YES/NO): ", user.Email)
fmt.Scanln(&confirm)
if confirm != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
if err := api.PermanentDeleteUser(c, user); err != nil {
l4g.Error("%v", err)
flushLogAndExit(1)
} else {
fmt.Print("SUCCESS: User deleted.")
flushLogAndExit(0)
}
}
}
func cmdPermDeleteTeam() {
if flagCmdPermanentDeleteTeam {
if len(flagTeamName) == 0 {
fmt.Fprintln(os.Stderr, "flag needs an argument: -team_name")
flag.Usage()
os.Exit(1)
}
c := getMockContext()
var team *model.Team
if result := <-api.Srv.Store.Team().GetByName(flagTeamName); result.Err != nil {
l4g.Error("%v", result.Err)
flushLogAndExit(1)
} else {
team = result.Data.(*model.Team)
}
var confirmBackup string
fmt.Print("Have you performed a database backup? (YES/NO): ")
fmt.Scanln(&confirmBackup)
if confirmBackup != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")
flushLogAndExit(1)
}
var confirm string
fmt.Printf("Are you sure you want to delete the team %v? All data will be permanently deleted? (YES/NO): ", team.Name)
fmt.Scanln(&confirm)
if confirm != "YES" {
fmt.Print("ABORTED: You did not answer YES exactly, in all capitals.")