diff --git a/.golangci.yml b/.golangci.yml index 16d1c896b1..63c522c239 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -49,10 +49,6 @@ issues: - golint text: "should have|should be|should replace|stutters|underscore|annoying|error strings should not be capitalized" - - linters: - - golint - path: "model/" - - linters: - misspell path: "shared/markdown/html_entities.go" diff --git a/api4/api.go b/api4/api.go index 12aa721305..16d4d34f53 100644 --- a/api4/api.go +++ b/api4/api.go @@ -146,7 +146,7 @@ func Init(a app.AppIface, root *mux.Router) *API { } api.BaseRoutes.Root = root - api.BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX).Subrouter() + api.BaseRoutes.ApiRoot = root.PathPrefix(model.ApiUrlSuffix).Subrouter() api.BaseRoutes.Users = api.BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() api.BaseRoutes.User = api.BaseRoutes.ApiRoot.PathPrefix("/users/{user_id:[A-Za-z0-9]+}").Subrouter() @@ -305,7 +305,7 @@ func InitLocal(a app.AppIface, root *mux.Router) *API { } api.BaseRoutes.Root = root - api.BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX).Subrouter() + api.BaseRoutes.ApiRoot = root.PathPrefix(model.ApiUrlSuffix).Subrouter() api.BaseRoutes.Users = api.BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() api.BaseRoutes.User = api.BaseRoutes.Users.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 19248cd90e..debd8b82ab 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -261,7 +261,7 @@ func SetupConfigWithStoreMock(tb testing.TB, updateConfig func(cfg *model.Config th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, false, false, updateConfig, nil) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -275,7 +275,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, false, false, nil, nil) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -289,7 +289,7 @@ func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, true, false, nil, nil) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -361,17 +361,17 @@ func (th *TestHelper) InitLogin() *TestHelper { // create users once and cache them because password hashing is slow initBasicOnce.Do(func() { th.SystemAdminUser = th.CreateUser() - th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id) userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy() th.SystemManagerUser = th.CreateUser() - th.App.UpdateUserRoles(th.SystemManagerUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_MANAGER_ROLE_ID, false) + th.App.UpdateUserRoles(th.SystemManagerUser.Id, model.SystemUserRoleId+" "+model.SystemManagerRoleId, false) th.SystemManagerUser, _ = th.App.GetUser(th.SystemManagerUser.Id) userCache.SystemManagerUser = th.SystemManagerUser.DeepCopy() th.TeamAdminUser = th.CreateUser() - th.App.UpdateUserRoles(th.TeamAdminUser.Id, model.SYSTEM_USER_ROLE_ID, false) + th.App.UpdateUserRoles(th.TeamAdminUser.Id, model.SystemUserRoleId, false) th.TeamAdminUser, _ = th.App.GetUser(th.TeamAdminUser.Id) userCache.TeamAdminUser = th.TeamAdminUser.DeepCopy() @@ -433,7 +433,7 @@ func (th *TestHelper) InitBasic() *TestHelper { th.App.AddUserToChannel(th.BasicUser2, th.BasicPrivateChannel, false) th.App.AddUserToChannel(th.BasicUser, th.BasicDeletedChannel, false) th.App.AddUserToChannel(th.BasicUser2, th.BasicDeletedChannel, false) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId, false) th.Client.DeleteChannel(th.BasicDeletedChannel.Id) th.LoginBasic() th.Group = th.CreateGroup() @@ -468,7 +468,7 @@ func (th *TestHelper) CreateLocalClient(socketPath string) *model.Client4 { } return &model.Client4{ - ApiUrl: "http://_" + model.API_URL_SUFFIX, + ApiUrl: "http://_" + model.ApiUrlSuffix, HttpClient: httpClient, } } @@ -523,7 +523,7 @@ func (th *TestHelper) CreateTeamWithClient(client *model.Client4) *model.Team { DisplayName: "dn_" + id, Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } utils.DisableDebugLogForTest() @@ -622,18 +622,18 @@ func (th *TestHelper) SetupSamlConfig() { *cfg.SamlSettings.NicknameAttribute = "" *cfg.SamlSettings.PositionAttribute = "" *cfg.SamlSettings.LocaleAttribute = "" - *cfg.SamlSettings.SignatureAlgorithm = model.SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256 - *cfg.SamlSettings.CanonicalAlgorithm = model.SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11 + *cfg.SamlSettings.SignatureAlgorithm = model.SamlSettingsSignatureAlgorithmSha256 + *cfg.SamlSettings.CanonicalAlgorithm = model.SamlSettingsCanonicalAlgorithmC14n11 }) th.App.Srv().SetLicense(model.NewTestLicense("saml")) } func (th *TestHelper) CreatePublicChannel() *model.Channel { - return th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN) + return th.CreateChannelWithClient(th.Client, model.ChannelTypeOpen) } func (th *TestHelper) CreatePrivateChannel() *model.Channel { - return th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE) + return th.CreateChannelWithClient(th.Client, model.ChannelTypePrivate) } func (th *TestHelper) CreateChannelWithClient(client *model.Client4, channelType string) *model.Channel { @@ -1049,7 +1049,7 @@ func s3New(endpoint, accessKey, secretKey string, secure bool, signV2 bool, regi func (th *TestHelper) cleanupTestFile(info *model.FileInfo) error { cfg := th.App.Config() - if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 { + if *cfg.FileSettings.DriverName == model.ImageDriverS3 { endpoint := *cfg.FileSettings.AmazonS3Endpoint accessKey := *cfg.FileSettings.AmazonS3AccessKeyId secretKey := *cfg.FileSettings.AmazonS3SecretAccessKey @@ -1076,7 +1076,7 @@ func (th *TestHelper) cleanupTestFile(info *model.FileInfo) error { return err } } - } else if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL { + } else if *cfg.FileSettings.DriverName == model.ImageDriverLocal { if err := os.Remove(*cfg.FileSettings.Directory + info.Path); err != nil { return err } @@ -1260,11 +1260,11 @@ func (th *TestHelper) AddPermissionToRole(permission string, roleName string) { } func (th *TestHelper) SetupTeamScheme() *model.Scheme { - return th.SetupScheme(model.SCHEME_SCOPE_TEAM) + return th.SetupScheme(model.SchemeScopeTeam) } func (th *TestHelper) SetupChannelScheme() *model.Scheme { - return th.SetupScheme(model.SCHEME_SCOPE_CHANNEL) + return th.SetupScheme(model.SchemeScopeChannel) } func (th *TestHelper) SetupScheme(scope string) *model.Scheme { diff --git a/api4/bleve.go b/api4/bleve.go index 3a54a0f471..6d5ba56ca4 100644 --- a/api4/bleve.go +++ b/api4/bleve.go @@ -18,8 +18,8 @@ func purgeBleveIndexes(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("purgeBleveIndexes", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PURGE_BLEVE_INDEXES) { - c.SetPermissionError(model.PERMISSION_PURGE_BLEVE_INDEXES) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionPurgeBleveIndexes) { + c.SetPermissionError(model.PermissionPurgeBleveIndexes) return } diff --git a/api4/bleve_test.go b/api4/bleve_test.go index adc94c1ea5..d72bc2de54 100644 --- a/api4/bleve_test.go +++ b/api4/bleve_test.go @@ -19,8 +19,8 @@ func TestBlevePurgeIndexes(t *testing.T) { }) t.Run("as system user with write experimental permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_PURGE_BLEVE_INDEXES.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionPurgeBleveIndexes.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteExperimental.Id, model.SystemUserRoleId) _, resp := th.Client.PurgeBleveIndexes() CheckOKStatus(t, resp) }) diff --git a/api4/bot.go b/api4/bot.go index 5da0d774e7..4d254f7f6b 100644 --- a/api4/bot.go +++ b/api4/bot.go @@ -45,14 +45,14 @@ func createBot(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("bot", bot) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_BOT) { - c.SetPermissionError(model.PERMISSION_CREATE_BOT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateBot) { + c.SetPermissionError(model.PermissionCreateBot) return } if user, err := c.App.GetUser(c.AppContext.Session().UserId); err == nil { if user.IsBot { - c.SetPermissionError(model.PERMISSION_CREATE_BOT) + c.SetPermissionError(model.PermissionCreateBot) return } } @@ -124,10 +124,10 @@ func getBot(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_OTHERS_BOTS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadOthersBots) { // Allow access to any bot. } else if bot.OwnerId == c.AppContext.Session().UserId { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_BOTS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadBots) { // Pretend like the bot doesn't exist at all to avoid revealing that the // user is a bot. It's kind of silly in this case, sine we created the bot, // but we don't have read bot permissions. @@ -153,14 +153,14 @@ func getBots(c *Context, w http.ResponseWriter, r *http.Request) { onlyOrphaned, _ := strconv.ParseBool(r.URL.Query().Get("only_orphaned")) var OwnerId string - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_OTHERS_BOTS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadOthersBots) { // Get bots created by any user. OwnerId = "" - } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_BOTS) { + } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadBots) { // Only get bots created by this user. OwnerId = c.AppContext.Session().UserId } else { - c.SetPermissionError(model.PERMISSION_READ_BOTS) + c.SetPermissionError(model.PermissionReadBots) return } @@ -241,7 +241,7 @@ func assignBot(c *Context, w http.ResponseWriter, _ *http.Request) { if user, err := c.App.GetUser(userId); err == nil { if user.IsBot { - c.SetPermissionError(model.PERMISSION_ASSIGN_BOT) + c.SetPermissionError(model.PermissionAssignBot) return } } @@ -272,7 +272,7 @@ func getBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -294,7 +294,7 @@ func getBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { } w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, private", 24*60*60)) // 24 hrs - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Header().Set("Content-Type", "image/svg+xml") w.Write(img) } @@ -406,8 +406,8 @@ func convertBotToUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("userPatch", userPatch) auditRec.AddMeta("set_system_admin", systemAdmin) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/bot_test.go b/api4/bot_test.go index 9849ee9be1..25c4ced84d 100644 --- a/api4/bot_test.go +++ b/api4/bot_test.go @@ -41,8 +41,8 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.Config().ServiceSettings.EnableBotAccountCreation = model.NewBool(false) _, resp := th.Client.CreateBot(&model.Bot{ @@ -59,8 +59,8 @@ func TestCreateBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -84,8 +84,8 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -108,9 +108,9 @@ func TestCreateBot(t *testing.T) { }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_EDIT_OTHER_USERS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionEditOtherUsers.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) bot, resp := th.Client.CreateBot(&model.Bot{ Username: GenerateTestUsername(), @@ -119,7 +119,7 @@ func TestCreateBot(t *testing.T) { }) CheckCreatedStatus(t, resp) defer th.App.PermanentDeleteBot(bot.UserId) - th.App.UpdateUserRoles(bot.UserId, model.TEAM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(bot.UserId, model.TeamUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) rtoken, resp := th.Client.CreateUserAccessToken(bot.UserId, "test token") CheckNoError(t, resp) @@ -153,8 +153,8 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -230,8 +230,8 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -253,8 +253,8 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -282,12 +282,12 @@ func TestPatchBot(t *testing.T) { // Continue through the bot update process (call UpdateUserRoles), then // get the bot, to make sure the patched bot was correctly saved. - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_ROLES.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageRoles.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) - success, resp := th.Client.UpdateUserRoles(createdBot.UserId, model.SYSTEM_USER_ROLE_ID) + success, resp := th.Client.UpdateUserRoles(createdBot.UserId, model.SystemUserRoleId) CheckOKStatus(t, resp) require.True(t, success) @@ -302,8 +302,8 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -331,9 +331,9 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -361,9 +361,9 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -395,9 +395,9 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -429,9 +429,9 @@ func TestPatchBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -491,8 +491,8 @@ func TestGetBot(t *testing.T) { deletedBot, resp = th.SystemAdminClient.DisableBot(deletedBot.UserId) CheckOKStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -504,14 +504,14 @@ func TestGetBot(t *testing.T) { }) CheckCreatedStatus(t, resp) defer th.App.PermanentDeleteBot(myBot.UserId) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) t.Run("get unknown bot", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) _, resp := th.Client.GetBot(model.NewId(), "") CheckNotFoundStatus(t, resp) @@ -520,9 +520,9 @@ func TestGetBot(t *testing.T) { t.Run("get bot1", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) bot, resp := th.Client.GetBot(bot1.UserId, "") CheckOKStatus(t, resp) @@ -535,9 +535,9 @@ func TestGetBot(t *testing.T) { t.Run("get bot2", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) bot, resp := th.Client.GetBot(bot2.UserId, "") CheckOKStatus(t, resp) @@ -547,26 +547,26 @@ func TestGetBot(t *testing.T) { CheckEtag(t, bot, resp) }) - t.Run("get bot1 without READ_OTHERS_BOTS permission", func(t *testing.T) { + t.Run("get bot1 without PermissionReadOthersBots permission", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) _, resp := th.Client.GetBot(bot1.UserId, "") CheckErrorMessage(t, resp, "store.sql_bot.get.missing.app_error") }) - t.Run("get myBot without READ_BOTS OR READ_OTHERS_BOTS permissions", func(t *testing.T) { + t.Run("get myBot without ReadBots OR ReadOthersBots permissions", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) _, resp := th.Client.GetBot(myBot.UserId, "") CheckErrorMessage(t, resp, "store.sql_bot.get.missing.app_error") @@ -575,9 +575,9 @@ func TestGetBot(t *testing.T) { t.Run("get deleted bot", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) _, resp := th.Client.GetBot(deletedBot.UserId, "") CheckNotFoundStatus(t, resp) @@ -586,9 +586,9 @@ func TestGetBot(t *testing.T) { t.Run("get deleted bot, include deleted", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) bot, resp := th.Client.GetBotIncludeDeleted(deletedBot.UserId, "") CheckOKStatus(t, resp) @@ -652,8 +652,8 @@ func TestGetBots(t *testing.T) { deletedBot2, resp = th.SystemAdminClient.DisableBot(deletedBot2.UserId) CheckOKStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser2.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser2.Id, model.TeamUserRoleId, false) th.LoginBasic2() orphanedBot, resp := th.Client.CreateBot(&model.Bot{ Username: GenerateTestUsername(), @@ -672,9 +672,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=0, perPage=10", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot1, bot2, bot3, orphanedBot} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -691,9 +691,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=0, perPage=1", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot1} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -710,9 +710,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=1, perPage=2", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot3, orphanedBot} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -729,9 +729,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=2, perPage=2", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -748,9 +748,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=0, perPage=10, include deleted", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot1, deletedBot1, bot2, bot3, deletedBot2, orphanedBot} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -767,9 +767,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=0, perPage=1, include deleted", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot1} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -786,9 +786,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=1, perPage=2, include deleted", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{bot2, bot3} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -805,9 +805,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=2, perPage=2, include deleted", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{deletedBot2, orphanedBot} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -824,9 +824,9 @@ func TestGetBots(t *testing.T) { t.Run("get bots, page=0, perPage=10, only orphaned", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) expectedBotList := []*model.Bot{orphanedBot} th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -843,10 +843,10 @@ func TestGetBots(t *testing.T) { t.Run("get bots without permission", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) _, resp := th.Client.GetBots(0, 10, "") CheckErrorMessage(t, resp, "api.context.permissions.app_error") @@ -869,8 +869,8 @@ func TestDisableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -893,9 +893,9 @@ func TestDisableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -918,9 +918,9 @@ func TestDisableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -967,8 +967,8 @@ func TestEnableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -994,9 +994,9 @@ func TestEnableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1022,9 +1022,9 @@ func TestEnableBot(t *testing.T) { defer th.TearDown() defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1073,8 +1073,8 @@ func TestAssignBot(t *testing.T) { t.Run("system admin and local mode assign bot", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1115,8 +1115,8 @@ func TestAssignBot(t *testing.T) { t.Run("random user assign bot", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1136,7 +1136,7 @@ func TestAssignBot(t *testing.T) { CheckErrorMessage(t, resp, "store.sql_bot.get.missing.app_error") // With permissions to read we don't have permissions to modify - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.SystemUserRoleId) _, resp = th.Client.AssignBot(createdBot.UserId, th.BasicUser2.Id) CheckErrorMessage(t, resp, "api.context.permissions.app_error") @@ -1146,8 +1146,8 @@ func TestAssignBot(t *testing.T) { t.Run("delegated user assign bot", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1161,11 +1161,11 @@ func TestAssignBot(t *testing.T) { defer th.App.PermanentDeleteBot(bot.UserId) // Simulate custom role by just changing the system user role - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.SystemUserRoleId) th.LoginBasic2() _, resp = th.Client.AssignBot(bot.UserId, th.BasicUser2.Id) @@ -1179,11 +1179,11 @@ func TestAssignBot(t *testing.T) { t.Run("bot assigned to bot fails", func(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_OTHERS_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadOthersBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.SystemUserRoleId) bot := &model.Bot{ Username: GenerateTestUsername(), @@ -1215,9 +1215,9 @@ func TestSetBotIconImage(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1284,9 +1284,9 @@ func TestGetBotIconImage(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1346,9 +1346,9 @@ func TestDeleteBotIconImage(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionReadBots.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1408,8 +1408,8 @@ func TestConvertBotToUser(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -1460,7 +1460,7 @@ func TestConvertBotToUser(t *testing.T) { CheckNoError(t, resp) require.NotNil(t, user) require.Equal(t, bot.UserId, user.Id) - require.Contains(t, user.GetRoles(), model.SYSTEM_ADMIN_ROLE_ID) + require.Contains(t, user.GetRoles(), model.SystemAdminRoleId) bot, resp = client.GetBot(bot.UserId, "") CheckNotFoundStatus(t, resp) diff --git a/api4/brand.go b/api4/brand.go index a9213deac6..a3d53bfe07 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -61,8 +61,8 @@ func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("uploadBrandImage", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_EDIT_BRAND) { - c.SetPermissionError(model.PERMISSION_EDIT_BRAND) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionEditBrand) { + c.SetPermissionError(model.PermissionEditBrand) return } @@ -82,8 +82,8 @@ func deleteBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deleteBrandImage", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_EDIT_BRAND) { - c.SetPermissionError(model.PERMISSION_EDIT_BRAND) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionEditBrand) { + c.SetPermissionError(model.PermissionEditBrand) return } diff --git a/api4/channel.go b/api4/channel.go index 23abf1dc85..13890ab9ae 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -89,13 +89,13 @@ func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_CREATE_PUBLIC_CHANNEL) { - c.SetPermissionError(model.PERMISSION_CREATE_PUBLIC_CHANNEL) + if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionCreatePublicChannel) { + c.SetPermissionError(model.PermissionCreatePublicChannel) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_CREATE_PRIVATE_CHANNEL) { - c.SetPermissionError(model.PERMISSION_CREATE_PRIVATE_CHANNEL) + if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionCreatePrivateChannel) { + c.SetPermissionError(model.PermissionCreatePrivateChannel) return } @@ -145,19 +145,19 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", oldChannel) switch oldChannel.Type { - case model.CHANNEL_OPEN: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { - c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) + case model.ChannelTypeOpen: + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { + c.SetPermissionError(model.PermissionManagePublicChannelProperties) return } - case model.CHANNEL_PRIVATE: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { - c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) + case model.ChannelTypePrivate: + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { + c.SetPermissionError(model.PermissionManagePrivateChannelProperties) return } - case model.CHANNEL_GROUP, model.CHANNEL_DIRECT: + case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. if _, errGet := c.App.GetChannelMember(context.Background(), channel.Id, c.AppContext.Session().UserId); errGet != nil { c.Err = model.NewAppError("updateChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) @@ -179,9 +179,9 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if oldChannel.Name == model.DEFAULT_CHANNEL { + if oldChannel.Name == model.DefaultChannelName { if channel.Name != "" && channel.Name != oldChannel.Name { - c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) + c.Err = model.NewAppError("updateChannel", "api.channel.update_channel.tried.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) return } } @@ -239,17 +239,17 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", oldPublicChannel) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { - c.SetPermissionError(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPublicChannelToPrivate) { + c.SetPermissionError(model.PermissionConvertPublicChannelToPrivate) return } - if oldPublicChannel.Type == model.CHANNEL_PRIVATE { + if oldPublicChannel.Type == model.ChannelTypePrivate { c.Err = model.NewAppError("convertChannelToPrivate", "api.channel.convert_channel_to_private.private_channel_error", nil, "", http.StatusBadRequest) return } - if oldPublicChannel.Name == model.DEFAULT_CHANNEL { + if oldPublicChannel.Name == model.DefaultChannelName { c.Err = model.NewAppError("convertChannelToPrivate", "api.channel.convert_channel_to_private.default_channel_error", nil, "", http.StatusBadRequest) return } @@ -261,7 +261,7 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) } auditRec.AddMeta("user", user) - oldPublicChannel.Type = model.CHANNEL_PRIVATE + oldPublicChannel.Type = model.ChannelTypePrivate rchannel, err := c.App.UpdateChannelPrivacy(c.AppContext, oldPublicChannel, user) if err != nil { @@ -283,7 +283,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { props := model.StringInterfaceFromJson(r.Body) privacy, ok := props["privacy"].(string) - if !ok || (privacy != model.CHANNEL_OPEN && privacy != model.CHANNEL_PRIVATE) { + if !ok || (privacy != model.ChannelTypeOpen && privacy != model.ChannelTypePrivate) { c.SetInvalidParam("privacy") return } @@ -299,17 +299,17 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) auditRec.AddMeta("new_type", privacy) - if privacy == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC) { - c.SetPermissionError(model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC) + if privacy == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPrivateChannelToPublic) { + c.SetPermissionError(model.PermissionConvertPrivateChannelToPublic) return } - if privacy == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { - c.SetPermissionError(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) + if privacy == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPublicChannelToPrivate) { + c.SetPermissionError(model.PermissionConvertPublicChannelToPrivate) return } - if channel.Name == model.DEFAULT_CHANNEL && privacy == model.CHANNEL_PRIVATE { + if channel.Name == model.DefaultChannelName && privacy == model.ChannelTypePrivate { c.Err = model.NewAppError("updateChannelPrivacy", "api.channel.update_channel_privacy.default_channel_error", nil, "", http.StatusBadRequest) return } @@ -358,19 +358,19 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", oldChannel) switch oldChannel.Type { - case model.CHANNEL_OPEN: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { - c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) + case model.ChannelTypeOpen: + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { + c.SetPermissionError(model.PermissionManagePublicChannelProperties) return } - case model.CHANNEL_PRIVATE: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { - c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) + case model.ChannelTypePrivate: + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { + c.SetPermissionError(model.PermissionManagePrivateChannelProperties) return } - case model.CHANNEL_GROUP, model.CHANNEL_DIRECT: + case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. if _, err = c.App.GetChannelMember(context.Background(), c.Params.ChannelId, c.AppContext.Session().UserId); err != nil { c.Err = model.NewAppError("patchChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) @@ -418,8 +418,8 @@ func restoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -457,13 +457,13 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createDirectChannel", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_DIRECT_CHANNEL) { - c.SetPermissionError(model.PERMISSION_CREATE_DIRECT_CHANNEL) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateDirectChannel) { + c.SetPermissionError(model.PermissionCreateDirectChannel) return } - if !allowed && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !allowed && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -481,7 +481,7 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -540,8 +540,8 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createGroupChannel", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_GROUP_CHANNEL) { - c.SetPermissionError(model.PERMISSION_CREATE_GROUP_CHANNEL) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateGroupChannel) { + c.SetPermissionError(model.PermissionCreateGroupChannel) return } @@ -560,7 +560,7 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSeeAll { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -589,14 +589,14 @@ func getChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) + if channel.Type == model.ChannelTypeOpen { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } @@ -617,12 +617,12 @@ func getChannelUnread(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -641,8 +641,8 @@ func getChannelStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -674,8 +674,8 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -691,22 +691,22 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { clientPostList := c.App.PreparePostListForClient(posts) - w.Header().Set(model.HEADER_ETAG_SERVER, clientPostList.Etag()) + w.Header().Set(model.HeaderEtagServer, clientPostList.Etag()) w.Write([]byte(clientPostList.ToJson())) } func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { permissions := []*model.Permission{ - model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS, - model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS, + model.PermissionSysconsoleReadUserManagementGroups, + model.PermissionSysconsoleReadUserManagementChannels, } if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), permissions) { c.SetPermissionError(permissions...) return } // Only system managers may use the ExcludePolicyConstrained parameter - if c.Params.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if c.Params.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -716,7 +716,7 @@ func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { IncludeDeleted: c.Params.IncludeDeleted, ExcludePolicyConstrained: c.Params.ExcludePolicyConstrained, } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { opts.IncludePolicyID = true } @@ -751,8 +751,8 @@ func getPublicChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { - c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { + c.SetPermissionError(model.PermissionListTeamChannels) return } @@ -798,8 +798,8 @@ func getPrivateChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -837,8 +837,8 @@ func getPublicChannelsByIdsForTeam(c *Context, w http.ResponseWriter, r *http.Re } } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -864,12 +864,12 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -899,7 +899,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - w.Header().Set(model.HEADER_ETAG_SERVER, channels.Etag()) + w.Header().Set(model.HeaderEtagServer, channels.Etag()) w.Write([]byte(channels.ToJson())) } @@ -909,8 +909,8 @@ func autocompleteChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Requ return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { - c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { + c.SetPermissionError(model.PermissionListTeamChannels) return } @@ -958,7 +958,7 @@ func searchChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request) { var channels *model.ChannelList var err *model.AppError - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { channels, err = c.App.SearchChannels(c.Params.TeamId, props.Term) } else { // If the user is not a team member, return a 404 @@ -994,7 +994,7 @@ func searchArchivedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Re var channels *model.ChannelList var err *model.AppError - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.AppContext.Session().UserId) } else { // If the user is not a team member, return a 404 @@ -1023,13 +1023,13 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { return } // Only system managers may use the ExcludePolicyConstrained field - if props.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if props.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementChannels) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementChannels) return } includeDeleted, _ := strconv.ParseBool(r.URL.Query().Get("include_deleted")) @@ -1049,7 +1049,7 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { Page: props.Page, PerPage: props.PerPage, } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { opts.IncludePolicyID = true } @@ -1087,18 +1087,18 @@ func deleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channeld", channel) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("deleteChannel", "api.channel.delete_channel.type.invalid", nil, "", http.StatusBadRequest) return } - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_DELETE_PUBLIC_CHANNEL) { - c.SetPermissionError(model.PERMISSION_DELETE_PUBLIC_CHANNEL) + if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionDeletePublicChannel) { + c.SetPermissionError(model.PermissionDeletePublicChannel) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_DELETE_PRIVATE_CHANNEL) { - c.SetPermissionError(model.PERMISSION_DELETE_PRIVATE_CHANNEL) + if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionDeletePrivateChannel) { + c.SetPermissionError(model.PermissionDeletePrivateChannel) return } @@ -1135,13 +1135,13 @@ func getChannelByName(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) + if channel.Type == model.ChannelTypeOpen { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.Err = model.NewAppError("getChannelByName", "app.channel.get_by_name.missing.app_error", nil, "teamId="+channel.TeamId+", "+"name="+channel.Name+"", http.StatusNotFound) return } @@ -1169,12 +1169,12 @@ func getChannelByNameForTeamName(c *Context, w http.ResponseWriter, r *http.Requ return } - teamOk := c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) - channelOk := c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) + teamOk := c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) + channelOk := c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) - if channel.Type == model.CHANNEL_OPEN { + if channel.Type == model.ChannelTypeOpen { if !teamOk && !channelOk { - c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) + c.SetPermissionError(model.PermissionReadPublicChannel) return } } else if !channelOk { @@ -1197,8 +1197,8 @@ func getChannelMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -1217,8 +1217,8 @@ func getChannelMembersTimezones(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -1243,8 +1243,8 @@ func getChannelMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -1263,8 +1263,8 @@ func getChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -1283,13 +1283,13 @@ func getChannelMembersForUser(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } - if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -1309,7 +1309,7 @@ func viewChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1367,8 +1367,8 @@ func updateChannelMemberRoles(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { - c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { + c.SetPermissionError(model.PermissionManageChannelRoles) return } @@ -1399,8 +1399,8 @@ func updateChannelMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.R auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", schemeRoles) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { - c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { + c.SetPermissionError(model.PermissionManageChannelRoles) return } @@ -1432,7 +1432,7 @@ func updateChannelMemberNotifyProps(c *Context, w http.ResponseWriter, r *http.R auditRec.AddMeta("props", props) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1493,7 +1493,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("addUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) return } @@ -1510,33 +1510,33 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { isSelfAdd := member.UserId == c.AppContext.Session().UserId - if channel.Type == model.CHANNEL_OPEN { + if channel.Type == model.ChannelTypeOpen { if isSelfAdd && isNewMembership { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_JOIN_PUBLIC_CHANNELS) { - c.SetPermissionError(model.PERMISSION_JOIN_PUBLIC_CHANNELS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionJoinPublicChannels) { + c.SetPermissionError(model.PermissionJoinPublicChannels) return } } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { - c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { + c.SetPermissionError(model.PermissionManagePublicChannelMembers) return } } } - if channel.Type == model.CHANNEL_PRIVATE { + if channel.Type == model.ChannelTypePrivate { if isSelfAdd && isNewMembership { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { - c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { - c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } } @@ -1598,7 +1598,7 @@ func removeChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) auditRec.AddMeta("remove_user_id", user.Id) - if !(channel.Type == model.CHANNEL_OPEN || channel.Type == model.CHANNEL_PRIVATE) { + if !(channel.Type == model.ChannelTypeOpen || channel.Type == model.ChannelTypePrivate) { c.Err = model.NewAppError("removeChannelMember", "api.channel.remove_channel_member.type.app_error", nil, "", http.StatusBadRequest) return } @@ -1609,13 +1609,13 @@ func removeChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } if c.Params.UserId != c.AppContext.Session().UserId { - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { - c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) + if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { + c.SetPermissionError(model.PermissionManagePublicChannelMembers) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { - c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) + if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } } @@ -1652,8 +1652,8 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -1663,7 +1663,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if scheme.Scope != model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope != model.SchemeScopeChannel { c.Err = model.NewAppError("Api4.UpdateChannelScheme", "api.channel.update_channel_scheme.scheme_scope.error", nil, "", http.StatusBadRequest) return } @@ -1712,8 +1712,8 @@ func channelMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http. groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementChannels) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementChannels) return } @@ -1751,8 +1751,8 @@ func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -1784,8 +1784,8 @@ func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementChannels) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementChannels) return } @@ -1824,8 +1824,8 @@ func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) auditRec := c.MakeAuditRecord("patchChannelModerations", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementChannels) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementChannels) return } @@ -1892,13 +1892,13 @@ func moveChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", team.Id) auditRec.AddMeta("team_name", team.Name) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("moveChannel", "api.channel.move_channel.type.invalid", nil, "", http.StatusForbidden) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/channel_category.go b/api4/channel_category.go index ccfa9ee02c..57977da5a0 100644 --- a/api4/channel_category.go +++ b/api4/channel_category.go @@ -18,7 +18,7 @@ func getCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.Requ } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -38,7 +38,7 @@ func createCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -73,7 +73,7 @@ func getCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *http.R } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -93,7 +93,7 @@ func updateCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *htt } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -126,7 +126,7 @@ func getCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques } if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -146,7 +146,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -234,7 +234,7 @@ func updateCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req } if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -271,7 +271,7 @@ func deleteCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req } if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } diff --git a/api4/channel_category_test.go b/api4/channel_category_test.go index 0ab22ccd3f..9e83c10f35 100644 --- a/api4/channel_category_test.go +++ b/api4/channel_category_test.go @@ -51,7 +51,7 @@ func TestCreateCategoryForTeamForUser(t *testing.T) { // Have another user create a channel that user isn't a part of channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{ TeamId: th.BasicTeam.Id, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "testchannel", }) require.Nil(t, resp.Error) @@ -235,7 +235,7 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) { // Have another user create a channel that user isn't a part of channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{ TeamId: th.BasicTeam.Id, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "testchannel", }) require.Nil(t, resp.Error) @@ -381,7 +381,7 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) { // Have another user create a channel that user isn't a part of channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{ TeamId: th.BasicTeam.Id, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "testchannel", }) require.Nil(t, resp.Error) diff --git a/api4/channel_local.go b/api4/channel_local.go index 267d7c07b8..c196a239df 100644 --- a/api4/channel_local.go +++ b/api4/channel_local.go @@ -68,7 +68,7 @@ func localUpdateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Reques props := model.StringInterfaceFromJson(r.Body) privacy, ok := props["privacy"].(string) - if !ok || (privacy != model.CHANNEL_OPEN && privacy != model.CHANNEL_PRIVATE) { + if !ok || (privacy != model.ChannelTypeOpen && privacy != model.ChannelTypePrivate) { c.SetInvalidParam("privacy") return } @@ -84,7 +84,7 @@ func localUpdateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Reques auditRec.AddMeta("channel", channel) auditRec.AddMeta("new_type", privacy) - if channel.Name == model.DEFAULT_CHANNEL && privacy == model.CHANNEL_PRIVATE { + if channel.Name == model.DefaultChannelName && privacy == model.ChannelTypePrivate { c.Err = model.NewAppError("updateChannelPrivacy", "api.channel.update_channel_privacy.default_channel_error", nil, "", http.StatusBadRequest) return } @@ -176,7 +176,7 @@ func localAddChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("localAddChannelMember", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) return } @@ -231,7 +231,7 @@ func localRemoveChannelMember(c *Context, w http.ResponseWriter, r *http.Request return } - if !(channel.Type == model.CHANNEL_OPEN || channel.Type == model.CHANNEL_PRIVATE) { + if !(channel.Type == model.ChannelTypeOpen || channel.Type == model.ChannelTypePrivate) { c.Err = model.NewAppError("removeChannelMember", "api.channel.remove_channel_member.type.app_error", nil, "", http.StatusBadRequest) return } @@ -338,7 +338,7 @@ func localMoveChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", team.Id) auditRec.AddMeta("team_name", team.Name) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("moveChannel", "api.channel.move_channel.type.invalid", nil, "", http.StatusForbidden) return } @@ -386,7 +386,7 @@ func localDeleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channeld", channel) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { c.Err = model.NewAppError("localDeleteChannel", "api.channel.delete_channel.type.invalid", nil, "", http.StatusBadRequest) return } diff --git a/api4/channel_test.go b/api4/channel_test.go index 5b49cad815..a7d49470df 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -30,8 +30,8 @@ func TestCreateChannel(t *testing.T) { Client := th.Client team := th.BasicTeam - channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id} - private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id} + channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id} + private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypePrivate, TeamId: team.Id} rchannel, resp := Client.CreateChannel(channel) CheckNoError(t, resp) @@ -45,14 +45,14 @@ func TestCreateChannel(t *testing.T) { CheckNoError(t, resp) require.Equal(t, private.Name, rprivate.Name, "names did not match") - require.Equal(t, model.CHANNEL_PRIVATE, rprivate.Type, "wrong channel type") + require.Equal(t, model.ChannelTypePrivate, rprivate.Type, "wrong channel type") require.Equal(t, th.BasicUser.Id, rprivate.CreatorId, "wrong creator id") _, resp = Client.CreateChannel(channel) CheckErrorMessage(t, resp, "store.sql_channel.save_channel.exists.app_error") CheckBadRequestStatus(t, resp) - direct := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_DIRECT, TeamId: team.Id} + direct := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeDirect, TeamId: team.Id} _, resp = Client.CreateChannel(direct) CheckErrorMessage(t, resp, "api.channel.create_channel.direct_channel.app_error") CheckBadRequestStatus(t, resp) @@ -76,8 +76,8 @@ func TestCreateChannel(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreatePublicChannel.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreatePrivateChannel.Id, model.TeamUserRoleId) th.LoginBasic() @@ -89,10 +89,10 @@ func TestCreateChannel(t *testing.T) { _, resp = Client.CreateChannel(private) CheckNoError(t, resp) - th.AddPermissionToRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, model.TEAM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreatePublicChannel.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionCreatePrivateChannel.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionCreatePublicChannel.Id, model.TeamUserRoleId) + th.RemovePermissionFromRole(model.PermissionCreatePrivateChannel.Id, model.TeamUserRoleId) _, resp = Client.CreateChannel(channel) CheckForbiddenStatus(t, resp) @@ -126,7 +126,7 @@ func TestCreateChannel(t *testing.T) { require.Equal(t, http.StatusBadRequest, r.StatusCode, "Expected 400 Bad Request") // Test GroupConstrained flag - groupConstrainedChannel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id, GroupConstrained: model.NewBool(true)} + groupConstrainedChannel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id, GroupConstrained: model.NewBool(true)} rchannel, resp = Client.CreateChannel(groupConstrainedChannel) CheckNoError(t, resp) @@ -139,8 +139,8 @@ func TestUpdateChannel(t *testing.T) { Client := th.Client team := th.BasicTeam - channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id} - private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_PRIVATE, TeamId: team.Id} + channel := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id} + private := &model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypePrivate, TeamId: team.Id} channel, _ = Client.CreateChannel(channel) private, _ = Client.CreateChannel(private) @@ -179,18 +179,18 @@ func TestUpdateChannel(t *testing.T) { // Test that changing the type fails and returns error - private.Type = model.CHANNEL_OPEN + private.Type = model.ChannelTypeOpen newPrivateChannel, resp = Client.UpdateChannel(private) CheckBadRequestStatus(t, resp) // Test that keeping the same type succeeds - private.Type = model.CHANNEL_PRIVATE + private.Type = model.ChannelTypePrivate newPrivateChannel, resp = Client.UpdateChannel(private) CheckNoError(t, resp) //Non existing channel - channel1 := &model.Channel{DisplayName: "Test API Name for apiv4", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel1 := &model.Channel{DisplayName: "Test API Name for apiv4", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id} _, resp = Client.UpdateChannel(channel1) CheckNotFoundStatus(t, resp) @@ -335,7 +335,7 @@ func TestChannelUnicodeNames(t *testing.T) { channel := &model.Channel{ Name: "\u206cenglish\u206dchannel", DisplayName: "The \u206cEnglish\u206d Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id} rchannel, resp := Client.CreateChannel(channel) @@ -350,7 +350,7 @@ func TestChannelUnicodeNames(t *testing.T) { channel := &model.Channel{ DisplayName: "Test API Name", Name: GenerateTestChannelName(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, _ = Client.CreateChannel(channel) @@ -425,7 +425,7 @@ func TestCreateDirectChannel(t *testing.T) { // Normal client should not be allowed to create a direct channel if users are // restricted to messaging members of their own team th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.TeamSettings.RestrictDirectMessage = model.DIRECT_MESSAGE_TEAM + *cfg.TeamSettings.RestrictDirectMessage = model.DirectMessageTeam }) user4 := th.CreateUser() _, resp = th.Client.CreateDirectChannel(user1.Id, user4.Id) @@ -516,7 +516,7 @@ func TestCreateGroupChannel(t *testing.T) { CheckCreatedStatus(t, resp) require.NotNil(t, rgc, "should have created a group channel") - require.Equal(t, model.CHANNEL_GROUP, rgc.Type, "should have created a channel of group type") + require.Equal(t, model.ChannelTypeGroup, rgc.Type, "should have created a channel of group type") m, _ := th.App.GetChannelMembersPage(rgc.Id, 0, 10) require.Len(t, *m, 3, "should have 3 channel members") @@ -769,7 +769,7 @@ func TestGetPrivateChannelsForTeam(t *testing.T) { require.Len(t, channels, 2, "wrong number of private channels") for _, c := range channels { // check all channels included are private - require.Equal(t, model.CHANNEL_PRIVATE, c.Type, "should include private channels only") + require.Equal(t, model.ChannelTypePrivate, c.Type, "should include private channels only") } channels, resp = c.GetPrivateChannelsForTeam(team.Id, 0, 1, "") @@ -803,7 +803,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) { for i, c := range channels { // check all channels included are open - require.Equal(t, model.CHANNEL_OPEN, c.Type, "should include open channel only") + require.Equal(t, model.ChannelTypeOpen, c.Type, "should include open channel only") // only check the created 2 public channels require.False(t, i < 2 && !(c.DisplayName == publicChannel1.DisplayName || c.DisplayName == publicChannel2.DisplayName), "should match public channel display name") @@ -815,7 +815,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) { require.Len(t, channels, 4, "incorrect length of team public channels") for _, c := range channels { - require.Equal(t, model.CHANNEL_OPEN, c.Type, "should not include private channel") + require.Equal(t, model.ChannelTypeOpen, c.Type, "should not include private channel") require.NotEqual(t, privateChannel.DisplayName, c.DisplayName, "should not match private channel display name") } @@ -952,7 +952,7 @@ func TestGetChannelsForTeamForUser(t *testing.T) { testChannel := &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestChannelName(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, } @@ -1139,7 +1139,7 @@ func TestSearchChannels(t *testing.T) { found := false for _, c := range channels { - require.Equal(t, model.CHANNEL_OPEN, c.Type, "should only return public channels") + require.Equal(t, model.ChannelTypeOpen, c.Type, "should only return public channels") if c.Id == th.BasicChannel.Id { found = true @@ -1180,7 +1180,7 @@ func TestSearchChannels(t *testing.T) { }() // Remove list channels permission from the user - th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListTeamChannels.Id, model.TeamUserRoleId) t.Run("Search for a BasicChannel, which the user is a member of", func(t *testing.T) { search.Term = th.BasicChannel.Name @@ -1223,7 +1223,7 @@ func TestSearchArchivedChannels(t *testing.T) { found := false for _, c := range channels { - require.Equal(t, model.CHANNEL_OPEN, c.Type) + require.Equal(t, model.ChannelTypeOpen, c.Type) if c.Id == th.BasicChannel.Id { found = true @@ -1268,7 +1268,7 @@ func TestSearchArchivedChannels(t *testing.T) { }() // Remove list channels permission from the user - th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListTeamChannels.Id, model.TeamUserRoleId) t.Run("Search for a BasicDeletedChannel, which the user is a member of", func(t *testing.T) { search.Term = th.BasicDeletedChannel.Name @@ -1305,7 +1305,7 @@ func TestSearchAllChannels(t *testing.T) { openChannel, chanErr := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "SearchAllChannels-FOOBARDISPLAYNAME", Name: "whatever", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, }) CheckNoError(t, chanErr) @@ -1313,7 +1313,7 @@ func TestSearchAllChannels(t *testing.T) { privateChannel, privErr := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "SearchAllChannels-private1", Name: "private1", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, }) CheckNoError(t, privErr) @@ -1322,7 +1322,7 @@ func TestSearchAllChannels(t *testing.T) { groupConstrainedChannel, groupErr := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "SearchAllChannels-groupConstrained-1", Name: "groupconstrained1", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, GroupConstrained: model.NewBool(true), TeamId: team.Id, }) @@ -1613,7 +1613,7 @@ func TestDeleteChannel(t *testing.T) { CheckNoError(t, resp) // default channel cannot be deleted. - defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, team.Id, false) + defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, team.Id, false) pass, resp = client.DeleteChannel(defaultChannel.Id) CheckBadRequestStatus(t, resp) require.False(t, pass, "should have failed") @@ -1623,7 +1623,7 @@ func TestDeleteChannel(t *testing.T) { sdPublicChannel := &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestChannelName(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: sdTeam.Id, } sdPublicChannel, resp = c.CreateChannel(sdPublicChannel) @@ -1634,7 +1634,7 @@ func TestDeleteChannel(t *testing.T) { sdPrivateChannel := &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestChannelName(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: sdTeam.Id, } sdPrivateChannel, resp = c.CreateChannel(sdPrivateChannel) @@ -1678,12 +1678,12 @@ func TestDeleteChannel2(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionDeletePublicChannel.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionDeletePrivateChannel.Id, model.ChannelUserRoleId) // channels created by SystemAdmin - publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN) - privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) + publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypeOpen) + privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) th.App.AddUserToChannel(user, publicChannel6, false) th.App.AddUserToChannel(user, privateChannel7, false) th.App.AddUserToChannel(user, privateChannel7, false) @@ -1696,14 +1696,14 @@ func TestDeleteChannel2(t *testing.T) { CheckNoError(t, resp) // Restrict permissions to Channel Admins - th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeletePublicChannel.Id, model.ChannelUserRoleId) + th.RemovePermissionFromRole(model.PermissionDeletePrivateChannel.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionDeletePublicChannel.Id, model.ChannelAdminRoleId) + th.AddPermissionToRole(model.PermissionDeletePrivateChannel.Id, model.ChannelAdminRoleId) // channels created by SystemAdmin - publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_OPEN) - privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) + publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypeOpen) + privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) th.App.AddUserToChannel(user, publicChannel6, false) th.App.AddUserToChannel(user, privateChannel7, false) th.App.AddUserToChannel(user, privateChannel7, false) @@ -1727,16 +1727,16 @@ func TestDeleteChannel2(t *testing.T) { CheckNoError(t, resp) // Make sure team admins don't have permission to delete channels. - th.RemovePermissionFromRole(model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeletePublicChannel.Id, model.ChannelAdminRoleId) + th.RemovePermissionFromRole(model.PermissionDeletePrivateChannel.Id, model.ChannelAdminRoleId) // last member of a public channel should have required permission to delete - publicChannel6 = th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN) + publicChannel6 = th.CreateChannelWithClient(th.Client, model.ChannelTypeOpen) _, resp = Client.DeleteChannel(publicChannel6.Id) CheckForbiddenStatus(t, resp) // last member of a private channel should not be able to delete it if they don't have required permissions - privateChannel7 = th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE) + privateChannel7 = th.CreateChannelWithClient(th.Client, model.ChannelTypePrivate) _, resp = Client.DeleteChannel(privateChannel7.Id) CheckForbiddenStatus(t, resp) } @@ -1785,7 +1785,7 @@ func TestConvertChannelToPrivate(t *testing.T) { defer th.TearDown() Client := th.Client - defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false) + defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, th.BasicTeam.Id, false) _, resp := Client.ConvertChannelToPrivate(defaultChannel.Id) CheckForbiddenStatus(t, resp) @@ -1798,16 +1798,16 @@ func TestConvertChannelToPrivate(t *testing.T) { CheckForbiddenStatus(t, resp) th.LoginTeamAdmin() - th.RemovePermissionFromRole(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, model.TEAM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionConvertPublicChannelToPrivate.Id, model.TeamAdminRoleId) _, resp = Client.ConvertChannelToPrivate(publicChannel.Id) CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, model.TEAM_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionConvertPublicChannelToPrivate.Id, model.TeamAdminRoleId) rchannel, resp := Client.ConvertChannelToPrivate(publicChannel.Id) CheckOKStatus(t, resp) - require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private") + require.Equal(t, model.ChannelTypePrivate, rchannel.Type, "channel should be converted from public to private") rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(privateChannel.Id) CheckBadRequestStatus(t, resp) @@ -1824,14 +1824,14 @@ func TestConvertChannelToPrivate(t *testing.T) { publicChannel2 := th.CreatePublicChannel() rchannel, resp = th.SystemAdminClient.ConvertChannelToPrivate(publicChannel2.Id) CheckOKStatus(t, resp) - require.Equal(t, model.CHANNEL_PRIVATE, rchannel.Type, "channel should be converted from public to private") + require.Equal(t, model.ChannelTypePrivate, rchannel.Type, "channel should be converted from public to private") timeout := time.After(10 * time.Second) for { select { case resp := <-WebSocketClient.EventChannel: - if resp.EventType() == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED && resp.GetData()["channel_id"].(string) == publicChannel2.Id { + if resp.EventType() == model.WebsocketEventChannelConverted && resp.GetData()["channel_id"].(string) == publicChannel2.Id { return } case <-timeout: @@ -1845,7 +1845,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - defaultChannel, _ := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false) + defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, th.BasicTeam.Id, false) type testTable []struct { name string @@ -1858,9 +1858,9 @@ func TestUpdateChannelPrivacy(t *testing.T) { publicChannel := th.CreatePublicChannel() tt := testTable{ - {"Updating default channel should fail with forbidden status if not logged in", defaultChannel, model.CHANNEL_OPEN}, - {"Updating private channel should fail with forbidden status if not logged in", privateChannel, model.CHANNEL_PRIVATE}, - {"Updating public channel should fail with forbidden status if not logged in", publicChannel, model.CHANNEL_OPEN}, + {"Updating default channel should fail with forbidden status if not logged in", defaultChannel, model.ChannelTypeOpen}, + {"Updating private channel should fail with forbidden status if not logged in", privateChannel, model.ChannelTypePrivate}, + {"Updating public channel should fail with forbidden status if not logged in", publicChannel, model.ChannelTypeOpen}, } for _, tc := range tt { @@ -1876,7 +1876,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { publicChannel := th.CreatePublicChannel() tt := testTable{ - {"Converting default channel to private should fail", defaultChannel, model.CHANNEL_PRIVATE}, + {"Converting default channel to private should fail", defaultChannel, model.ChannelTypePrivate}, {"Updating privacy to an invalid setting should fail", publicChannel, "invalid"}, } @@ -1888,11 +1888,11 @@ func TestUpdateChannelPrivacy(t *testing.T) { } tt = testTable{ - {"Default channel should stay public", defaultChannel, model.CHANNEL_OPEN}, - {"Public channel should stay public", publicChannel, model.CHANNEL_OPEN}, - {"Private channel should stay private", privateChannel, model.CHANNEL_PRIVATE}, - {"Public channel should convert to private", publicChannel, model.CHANNEL_PRIVATE}, - {"Private channel should convert to public", privateChannel, model.CHANNEL_OPEN}, + {"Default channel should stay public", defaultChannel, model.ChannelTypeOpen}, + {"Public channel should stay public", publicChannel, model.ChannelTypeOpen}, + {"Private channel should stay private", privateChannel, model.ChannelTypePrivate}, + {"Public channel should convert to private", publicChannel, model.ChannelTypePrivate}, + {"Private channel should convert to public", privateChannel, model.ChannelTypeOpen}, } for _, tc := range tt { @@ -1913,20 +1913,20 @@ func TestUpdateChannelPrivacy(t *testing.T) { th.LoginTeamAdmin() - th.RemovePermissionFromRole(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, model.TEAM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionConvertPublicChannelToPrivate.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionConvertPrivateChannelToPublic.Id, model.TeamAdminRoleId) - _, resp := th.Client.UpdateChannelPrivacy(publicChannel.Id, model.CHANNEL_PRIVATE) + _, resp := th.Client.UpdateChannelPrivacy(publicChannel.Id, model.ChannelTypePrivate) CheckForbiddenStatus(t, resp) - _, resp = th.Client.UpdateChannelPrivacy(privateChannel.Id, model.CHANNEL_OPEN) + _, resp = th.Client.UpdateChannelPrivacy(privateChannel.Id, model.ChannelTypeOpen) CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, model.TEAM_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionConvertPublicChannelToPrivate.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionConvertPrivateChannelToPublic.Id, model.TeamAdminRoleId) - _, resp = th.Client.UpdateChannelPrivacy(privateChannel.Id, model.CHANNEL_OPEN) + _, resp = th.Client.UpdateChannelPrivacy(privateChannel.Id, model.ChannelTypeOpen) CheckNoError(t, resp) - _, resp = th.Client.UpdateChannelPrivacy(publicChannel.Id, model.CHANNEL_PRIVATE) + _, resp = th.Client.UpdateChannelPrivacy(publicChannel.Id, model.ChannelTypePrivate) CheckNoError(t, resp) }) } @@ -2501,8 +2501,8 @@ func TestUpdateChannelMemberSchemeRoles(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - if event.Event == model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED { - require.Equal(t, model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, event.Event) + if event.Event == model.WebsocketEventChannelMemberUpdated { + require.Equal(t, model.WebsocketEventChannelMemberUpdated, event.Event) waiting = false } case <-timeout: @@ -2608,8 +2608,8 @@ func TestUpdateChannelNotifyProps(t *testing.T) { Client := th.Client props := map[string]string{} - props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_MENTION - props[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_MARK_UNREAD_MENTION + props[model.DesktopNotifyProp] = model.ChannelNotifyMention + props[model.MarkUnreadNotifyProp] = model.ChannelMarkUnreadMention pass, resp := Client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props) CheckNoError(t, resp) @@ -2617,8 +2617,8 @@ func TestUpdateChannelNotifyProps(t *testing.T) { member, err := th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) - require.Equal(t, model.CHANNEL_NOTIFY_MENTION, member.NotifyProps[model.DESKTOP_NOTIFY_PROP], "bad update") - require.Equal(t, model.CHANNEL_MARK_UNREAD_MENTION, member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP], "bad update") + require.Equal(t, model.ChannelNotifyMention, member.NotifyProps[model.DesktopNotifyProp], "bad update") + require.Equal(t, model.ChannelMarkUnreadMention, member.NotifyProps[model.MarkUnreadNotifyProp], "bad update") _, resp = Client.UpdateChannelNotifyProps("junk", th.BasicUser.Id, props) CheckBadRequestStatus(t, resp) @@ -2749,7 +2749,7 @@ func TestAddChannelMember(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelUserRoleId) // Check that a regular channel user can add other users. Client.Login(user2.Username, user2.Password) @@ -2764,8 +2764,8 @@ func TestAddChannelMember(t *testing.T) { Client.Logout() // Restrict the permission for adding users to Channel Admins - th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelUserRoleId) Client.Login(user2.Username, user2.Password) privateChannel = th.CreatePrivateChannel() @@ -2837,31 +2837,31 @@ func TestAddChannelMemberAddMyself(t *testing.T) { ExpectedError string }{ { - "Add myself to a public channel with JOIN_PUBLIC_CHANNEL permission", + "Add myself to a public channel with JoinPublicChannel permission", notMemberPublicChannel1, true, "", }, { - "Try to add myself to a private channel with the JOIN_PUBLIC_CHANNEL permission", + "Try to add myself to a private channel with the JoinPublicChannel permission", notMemberPrivateChannel, true, "api.context.permissions.app_error", }, { - "Try to add myself to a public channel without the JOIN_PUBLIC_CHANNEL permission", + "Try to add myself to a public channel without the JoinPublicChannel permission", notMemberPublicChannel2, false, "api.context.permissions.app_error", }, { - "Add myself a public channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission", + "Add myself a public channel where I'm already a member, not having JoinPublicChannel or ManageMembers permission", memberPublicChannel, false, "", }, { - "Add myself a private channel where I'm already a member, not having JOIN_PUBLIC_CHANNEL or MANAGE MEMBERS permission", + "Add myself a private channel where I'm already a member, not having JoinPublicChannel or ManageMembers permission", memberPrivateChannel, false, "", @@ -2878,7 +2878,7 @@ func TestAddChannelMemberAddMyself(t *testing.T) { }() if !tc.WithJoinPublicPermission { - th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionJoinPublicChannels.Id, model.TeamUserRoleId) } _, resp := Client.AddChannelMember(tc.Channel.Id, user.Id) @@ -2930,7 +2930,7 @@ func TestRemoveChannelMember(t *testing.T) { _, err = th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel2, false) require.Nil(t, err) props := map[string]string{} - props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_ALL + props[model.DesktopNotifyProp] = model.ChannelNotifyAll _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.SystemAdminUser.Id, props) _, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel2.Id, th.SystemAdminUser.Id, props) CheckNoError(t, resp) @@ -2944,7 +2944,7 @@ func TestRemoveChannelMember(t *testing.T) { }) wsr := <-wsClient.EventChannel - require.Equal(t, model.WEBSOCKET_EVENT_HELLO, wsr.EventType()) + require.Equal(t, model.WebsocketEventHello, wsr.EventType()) // requirePost listens for websocket events and tries to find the post matching // the expected post's channel and message. @@ -3036,11 +3036,11 @@ func TestRemoveChannelMember(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelUserRoleId) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { // Check that a regular channel user can remove other users. - privateChannel := th.CreateChannelWithClient(client, model.CHANNEL_PRIVATE) + privateChannel := th.CreateChannelWithClient(client, model.ChannelTypePrivate) _, resp = client.AddChannelMember(privateChannel.Id, user1.Id) CheckNoError(t, resp) _, resp = client.AddChannelMember(privateChannel.Id, user2.Id) @@ -3051,10 +3051,10 @@ func TestRemoveChannelMember(t *testing.T) { }) // Restrict the permission for adding users to Channel Admins - th.AddPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManagePrivateChannelMembers.Id, model.ChannelUserRoleId) - privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) + privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user1.Id) CheckNoError(t, resp) _, resp = th.SystemAdminClient.AddChannelMember(privateChannel.Id, user2.Id) @@ -3122,13 +3122,13 @@ func TestAutocompleteChannels(t *testing.T) { ptown, _ := th.Client.CreateChannel(&model.Channel{ DisplayName: "Town", Name: "town", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, }) tower, _ := th.Client.CreateChannel(&model.Channel{ DisplayName: "Tower", Name: "tower", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, }) utils.EnableDebugLogForTest() @@ -3204,7 +3204,7 @@ func TestAutocompleteChannelsForSearch(t *testing.T) { ptown, _ := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "Town", Name: "town", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, }) defer func() { @@ -3213,7 +3213,7 @@ func TestAutocompleteChannelsForSearch(t *testing.T) { mypriv, _ := th.Client.CreateChannel(&model.Channel{ DisplayName: "My private town", Name: "townpriv", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, }) defer func() { @@ -3334,7 +3334,7 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) { town, _ := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "Town", Name: "town", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, }) defer func() { @@ -3346,7 +3346,7 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) { mypriv, _ := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "My private town", Name: "townpriv", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, }) defer func() { @@ -3446,14 +3446,14 @@ func TestUpdateChannelScheme(t *testing.T) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) CheckNoError(t, resp) channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{ DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, }) CheckNoError(t, resp) @@ -3462,7 +3462,7 @@ func TestUpdateChannelScheme(t *testing.T) { DisplayName: "DisplayName", Name: model.NewId(), Description: "Some description", - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }) CheckNoError(t, resp) @@ -3470,7 +3470,7 @@ func TestUpdateChannelScheme(t *testing.T) { DisplayName: "DisplayName", Name: model.NewId(), Description: "Some description", - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }) CheckNoError(t, resp) @@ -3689,13 +3689,13 @@ func TestGetChannelModerations(t *testing.T) { _, err := th.App.UpdateTeamScheme(team) require.Nil(t, err) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) - defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) + th.RemovePermissionFromRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) + defer th.AddPermissionToRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") require.Nil(t, res.Error) for _, moderation := range moderations { - if moderation.Name == model.PERMISSION_CREATE_POST.Id { + if moderation.Name == model.PermissionCreatePost.Id { require.Equal(t, moderation.Roles.Members.Value, true) require.Equal(t, moderation.Roles.Members.Enabled, true) require.Equal(t, moderation.Roles.Guests.Value, false) @@ -3710,13 +3710,13 @@ func TestGetChannelModerations(t *testing.T) { _, err := th.App.UpdateChannelScheme(channel) require.Nil(t, err) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) - defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) + th.RemovePermissionFromRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) + defer th.AddPermissionToRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") require.Nil(t, res.Error) for _, moderation := range moderations { - if moderation.Name == model.PERMISSION_CREATE_POST.Id { + if moderation.Name == model.PermissionCreatePost.Id { require.Equal(t, moderation.Roles.Members.Value, true) require.Equal(t, moderation.Roles.Members.Enabled, true) require.Equal(t, moderation.Roles.Guests.Value, false) @@ -3734,16 +3734,16 @@ func TestGetChannelModerations(t *testing.T) { channel.SchemeId = &scheme.Id th.App.UpdateChannelScheme(channel) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) - th.RemovePermissionFromRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole) + th.RemovePermissionFromRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) + th.RemovePermissionFromRole(model.PermissionCreatePost.Id, teamScheme.DefaultChannelGuestRole) - defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelGuestRole) - defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, teamScheme.DefaultChannelGuestRole) + defer th.AddPermissionToRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) + defer th.AddPermissionToRole(model.PermissionCreatePost.Id, teamScheme.DefaultChannelGuestRole) moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") require.Nil(t, res.Error) for _, moderation := range moderations { - if moderation.Name == model.PERMISSION_CREATE_POST.Id { + if moderation.Name == model.PermissionCreatePost.Id { require.Equal(t, moderation.Roles.Members.Value, true) require.Equal(t, moderation.Roles.Members.Enabled, true) require.Equal(t, moderation.Roles.Guests.Value, false) @@ -3758,8 +3758,8 @@ func TestGetChannelModerations(t *testing.T) { _, err := th.App.UpdateTeamScheme(team) require.Nil(t, err) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, scheme.DefaultChannelUserRole) - defer th.AddPermissionToRole(model.PERMISSION_CREATE_POST.Id, scheme.DefaultChannelUserRole) + th.RemovePermissionFromRole(model.PermissionManagePublicChannelMembers.Id, scheme.DefaultChannelUserRole) + defer th.AddPermissionToRole(model.PermissionCreatePost.Id, scheme.DefaultChannelUserRole) // public channel does not have the permission moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") @@ -4237,7 +4237,7 @@ func TestViewChannelWithoutCollapsedThreads(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client diff --git a/api4/cloud.go b/api4/cloud.go index b23bda10bd..c064342d98 100644 --- a/api4/cloud.go +++ b/api4/cloud.go @@ -51,8 +51,8 @@ func getSubscription(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadBilling) { + c.SetPermissionError(model.PermissionSysconsoleReadBilling) return } @@ -77,8 +77,8 @@ func changeSubscription(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) { + c.SetPermissionError(model.PermissionSysconsoleWriteBilling) return } @@ -133,8 +133,8 @@ func getCloudProducts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadBilling) { + c.SetPermissionError(model.PermissionSysconsoleReadBilling) return } @@ -159,8 +159,8 @@ func getCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadBilling) { + c.SetPermissionError(model.PermissionSysconsoleReadBilling) return } @@ -185,8 +185,8 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) { + c.SetPermissionError(model.PermissionSysconsoleWriteBilling) return } @@ -223,8 +223,8 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) { + c.SetPermissionError(model.PermissionSysconsoleWriteBilling) return } @@ -261,8 +261,8 @@ func createCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) { + c.SetPermissionError(model.PermissionSysconsoleWriteBilling) return } @@ -292,8 +292,8 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteBilling) { + c.SetPermissionError(model.PermissionSysconsoleWriteBilling) return } @@ -329,8 +329,8 @@ func getInvoicesForSubscription(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadBilling) { + c.SetPermissionError(model.PermissionSysconsoleReadBilling) return } @@ -360,8 +360,8 @@ func getSubscriptionInvoicePDF(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadBilling) { + c.SetPermissionError(model.PermissionSysconsoleReadBilling) return } diff --git a/api4/cluster.go b/api4/cluster.go index 8aa72a4986..d41d6f2416 100644 --- a/api4/cluster.go +++ b/api4/cluster.go @@ -14,8 +14,8 @@ func (api *API) InitCluster() { } func getClusterStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadEnvironmentHighAvailability) { + c.SetPermissionError(model.PermissionSysconsoleReadEnvironmentHighAvailability) return } diff --git a/api4/command.go b/api4/command.go index d330638e49..2a8fa852d9 100644 --- a/api4/command.go +++ b/api4/command.go @@ -38,8 +38,8 @@ func createCommand(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { - c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageSlashCommands) { + c.SetPermissionError(model.PermissionManageSlashCommands) return } @@ -88,7 +88,7 @@ func updateCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), oldCmd.TeamId, model.PermissionManageSlashCommands) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -96,9 +96,9 @@ func updateCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != oldCmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.AppContext.Session().UserId != oldCmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), oldCmd.TeamId, model.PermissionManageOthersSlashCommands) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) + c.SetPermissionError(model.PermissionManageOthersSlashCommands) return } @@ -137,9 +137,9 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("team", newTeam) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), newTeam.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), newTeam.Id, model.PermissionManageSlashCommands) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) + c.SetPermissionError(model.PermissionManageSlashCommands) return } @@ -150,7 +150,7 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageSlashCommands) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -186,7 +186,7 @@ func deleteCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageSlashCommands) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -194,9 +194,9 @@ func deleteCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageOthersSlashCommands) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) + c.SetPermissionError(model.PermissionManageOthersSlashCommands) return } @@ -221,16 +221,16 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } var commands []*model.Command var err *model.AppError if customOnly { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { - c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageSlashCommands) { + c.SetPermissionError(model.PermissionManageSlashCommands) return } commands, err = c.App.ListTeamCommands(teamId) @@ -240,7 +240,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { } } else { //User with no permission should see only system commands - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageSlashCommands) { commands, err = c.App.ListAutocompleteCommands(teamId, c.AppContext.T) if err != nil { c.Err = err @@ -273,13 +273,13 @@ func getCommand(c *Context, w http.ResponseWriter, r *http.Request) { // check for permissions to view this command; must have perms to view team and // PERMISSION_MANAGE_SLASH_COMMANDS for the team the command belongs to. - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionViewTeam) { // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. c.SetCommandNotFoundError() return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageSlashCommands) { // again, return not_found to ensure id existence does not leak. c.SetCommandNotFoundError() return @@ -304,8 +304,8 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("commandargs", commandArgs) // checks that user is a member of the specified channel, and that they have permission to use slash commands in it - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), commandArgs.ChannelId, model.PERMISSION_USE_SLASH_COMMANDS) { - c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), commandArgs.ChannelId, model.PermissionUseSlashCommands) { + c.SetPermissionError(model.PermissionUseSlashCommands) return } @@ -315,7 +315,7 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type != model.CHANNEL_DIRECT && channel.Type != model.CHANNEL_GROUP { + if channel.Type != model.ChannelTypeDirect && channel.Type != model.ChannelTypeGroup { // if this isn't a DM or GM, the team id is implicitly taken from the channel so that slash commands created on // some other team can't be run against this one commandArgs.TeamId = channel.TeamId @@ -323,8 +323,8 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { // if the slash command was used in a DM or GM, ensure that the user is a member of the specified team, so that // they can't just execute slash commands against arbitrary teams if c.AppContext.Session().GetTeamByTeamId(commandArgs.TeamId) == nil { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_USE_SLASH_COMMANDS) { - c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionUseSlashCommands) { + c.SetPermissionError(model.PermissionUseSlashCommands) return } } @@ -353,8 +353,8 @@ func listAutocompleteCommands(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -372,14 +372,14 @@ func listCommandAutocompleteSuggestions(c *Context, w http.ResponseWriter, r *ht if c.Err != nil { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } - roleId := model.SYSTEM_USER_ROLE_ID + roleId := model.SystemUserRoleId if c.IsSystemAdmin() { - roleId = model.SYSTEM_ADMIN_ROLE_ID + roleId = model.SystemAdminRoleId } query := r.URL.Query() @@ -431,7 +431,7 @@ func regenCommandToken(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageSlashCommands) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -439,9 +439,9 @@ func regenCommandToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PermissionManageOthersSlashCommands) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) + c.SetPermissionError(model.PermissionManageOthersSlashCommands) return } diff --git a/api4/command_help_test.go b/api4/command_help_test.go index a35b4aac15..888185c292 100644 --- a/api4/command_help_test.go +++ b/api4/command_help_test.go @@ -25,7 +25,7 @@ func TestHelpCommand(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" }) rs1, _ := Client.ExecuteCommand(channel.Id, "/help ") - assert.Equal(t, rs1.GotoLocation, model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK, "failed to default help link") + assert.Equal(t, rs1.GotoLocation, model.SupportSettingsDefaultHelpLink, "failed to default help link") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" diff --git a/api4/command_test.go b/api4/command_test.go index 9060dd1403..63e3843257 100644 --- a/api4/command_test.go +++ b/api4/command_test.go @@ -32,7 +32,7 @@ func TestCreateCommand(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger"} _, resp := Client.CreateCommand(newCmd) @@ -90,7 +90,7 @@ func TestUpdateCommand(t *testing.T) { CreatorId: user.Id, TeamId: team.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger1", } @@ -100,7 +100,7 @@ func TestUpdateCommand(t *testing.T) { CreatorId: GenerateTestId(), TeamId: team.Id, URL: "http://nowhere.com/change", - Method: model.COMMAND_METHOD_GET, + Method: model.CommandMethodGet, Trigger: "trigger2", Id: cmd1.Id, Token: "tokenchange", @@ -165,7 +165,7 @@ func TestMoveCommand(t *testing.T) { CreatorId: user.Id, TeamId: team.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger1", } @@ -192,7 +192,7 @@ func TestMoveCommand(t *testing.T) { CreatorId: user.Id, TeamId: team.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger2", } @@ -222,7 +222,7 @@ func TestDeleteCommand(t *testing.T) { CreatorId: user.Id, TeamId: team.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger1", } @@ -250,7 +250,7 @@ func TestDeleteCommand(t *testing.T) { CreatorId: user.Id, TeamId: team.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger2", } @@ -279,7 +279,7 @@ func TestListCommands(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "custom_command"} _, resp := th.SystemAdminClient.CreateCommand(newCmd) @@ -363,7 +363,7 @@ func TestListAutocompleteCommands(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "custom_command"} _, resp := th.SystemAdminClient.CreateCommand(newCmd) @@ -430,7 +430,7 @@ func TestListCommandAutocompleteSuggestions(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "custom_command"} _, resp := th.SystemAdminClient.CreateCommand(newCmd) @@ -525,7 +525,7 @@ func TestGetCommand(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "roger"} newCmd, resp := th.SystemAdminClient.CreateCommand(newCmd) @@ -585,7 +585,7 @@ func TestRegenToken(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "trigger"} createdCmd, resp := th.SystemAdminClient.CreateCommand(newCmd) @@ -629,7 +629,7 @@ func TestExecuteInvalidCommand(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_GET, + Method: model.CommandMethodGet, Trigger: "getcommand", } @@ -683,7 +683,7 @@ func TestExecuteGetCommand(t *testing.T) { token := model.NewId() expectedCommandResponse := &model.CommandResponse{ Text: "test get command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -707,7 +707,7 @@ func TestExecuteGetCommand(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: ts.URL + "/?cmd=ourCommand", - Method: model.COMMAND_METHOD_GET, + Method: model.CommandMethodGet, Trigger: "getcommand", Token: token, } @@ -743,7 +743,7 @@ func TestExecutePostCommand(t *testing.T) { token := model.NewId() expectedCommandResponse := &model.CommandResponse{ Text: "test post command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -765,7 +765,7 @@ func TestExecutePostCommand(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "postcommand", Token: token, } @@ -802,7 +802,7 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) { expectedCommandResponse := &model.CommandResponse{ Text: "test post command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -819,7 +819,7 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: team2.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "postcommand", } _, err := th.App.CreateCommand(postCmd) @@ -851,7 +851,7 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) { expectedCommandResponse := &model.CommandResponse{ Text: "test post command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -868,14 +868,14 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: team2.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "postcommand", } _, err := th.App.CreateCommand(postCmd) require.Nil(t, err, "failed to create post command") // make a channel on that team, ensuring that our test user isn't in it - channel2 := th.CreateChannelWithClientAndTeam(client, model.CHANNEL_OPEN, team2.Id) + channel2 := th.CreateChannelWithClientAndTeam(client, model.ChannelTypeOpen, team2.Id) success, _ := client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id) require.True(t, success, "Failed to remove user from channel") @@ -907,7 +907,7 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) { expectedCommandResponse := &model.CommandResponse{ Text: "test post command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -924,7 +924,7 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: team2.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "postcommand", } _, err := th.App.CreateCommand(postCmd) @@ -966,7 +966,7 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) { expectedCommandResponse := &model.CommandResponse{ Text: "test post command response", - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + ResponseType: model.CommandResponseTypeInChannel, Type: "custom_test", Props: map[string]interface{}{"someprop": "somevalue"}, } @@ -986,7 +986,7 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: team2.Id, URL: ts.URL, - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "postcommand", } _, err := th.App.CreateCommand(postCmd) diff --git a/api4/commands_test.go b/api4/commands_test.go index a52323890d..c47bbae235 100644 --- a/api4/commands_test.go +++ b/api4/commands_test.go @@ -101,14 +101,14 @@ func testJoinCommands(t *testing.T, alias string) { team := th.BasicTeam user2 := th.BasicUser2 - channel0 := &model.Channel{DisplayName: "00", Name: "00" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel0 := &model.Channel{DisplayName: "00", Name: "00" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id} channel0 = Client.Must(Client.CreateChannel(channel0)).(*model.Channel) - channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).(*model.Channel) Client.Must(Client.RemoveUserFromChannel(channel1.Id, th.BasicUser.Id)) - channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).(*model.Channel) Client.Must(Client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id)) @@ -131,7 +131,7 @@ func testJoinCommands(t *testing.T, alias string) { require.True(t, found, "did not join channel") // test case insensitively - channel4 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel4 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id} channel4 = Client.Must(Client.CreateChannel(channel4)).(*model.Channel) Client.Must(Client.RemoveUserFromChannel(channel4.Id, th.BasicUser.Id)) rs7 := Client.Must(Client.ExecuteCommand(channel0.Id, "/"+alias+" "+strings.ToUpper(channel4.Name))).(*model.CommandResponse) @@ -250,11 +250,11 @@ func TestLeaveCommands(t *testing.T) { team := th.BasicTeam user2 := th.BasicUser2 - channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} + channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id} channel1 = Client.Must(Client.CreateChannel(channel1)).(*model.Channel) Client.Must(Client.AddChannelMember(channel1.Id, th.BasicUser.Id)) - channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} + channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypePrivate, TeamId: team.Id} channel2 = Client.Must(Client.CreateChannel(channel2)).(*model.Channel) Client.Must(Client.AddChannelMember(channel2.Id, th.BasicUser.Id)) Client.Must(Client.AddChannelMember(channel2.Id, user2.Id)) @@ -262,10 +262,10 @@ func TestLeaveCommands(t *testing.T) { channel3 := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id, user2.Id)).(*model.Channel) rs1 := Client.Must(Client.ExecuteCommand(channel1.Id, "/leave")).(*model.CommandResponse) - require.True(t, strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+model.DEFAULT_CHANNEL), "failed to leave open channel 1") + require.True(t, strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+model.DefaultChannelName), "failed to leave open channel 1") rs2 := Client.Must(Client.ExecuteCommand(channel2.Id, "/leave")).(*model.CommandResponse) - require.True(t, strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+model.DEFAULT_CHANNEL), "failed to leave private channel 1") + require.True(t, strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+model.DefaultChannelName), "failed to leave private channel 1") _, err := Client.ExecuteCommand(channel3.Id, "/leave") require.NotNil(t, err, "should fail leaving direct channel") @@ -281,7 +281,7 @@ func TestLeaveCommands(t *testing.T) { require.False(t, found, "did not leave right channels") for _, c := range cdata { - if c.Name == model.DEFAULT_CHANNEL { + if c.Name == model.DefaultChannelName { _, err := Client.RemoveUserFromChannel(c.Id, th.BasicUser.Id) require.NotNil(t, err, "should have errored on leaving default channel") break @@ -314,7 +314,7 @@ func TestMeCommand(t *testing.T) { require.Len(t, p1.Order, 2, "Command failed to send") pt := p1.Posts[p1.Order[0]].Type - require.Equal(t, model.POST_ME, pt, "invalid post type") + require.Equal(t, model.PostTypeMe, pt, "invalid post type") msg := p1.Posts[p1.Order[0]].Message want := "*hello*" diff --git a/api4/compliance.go b/api4/compliance.go index 397dd50307..04a7536014 100644 --- a/api4/compliance.go +++ b/api4/compliance.go @@ -30,8 +30,8 @@ func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) auditRec := c.MakeAuditRecord("createComplianceReport", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB) { - c.SetPermissionError(model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateComplianceExportJob) { + c.SetPermissionError(model.PermissionCreateComplianceExportJob) return } @@ -53,8 +53,8 @@ func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) } func getComplianceReports(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) { - c.SetPermissionError(model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadComplianceExportJob) { + c.SetPermissionError(model.PermissionReadComplianceExportJob) return } @@ -80,8 +80,8 @@ func getComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("getComplianceReport", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) { - c.SetPermissionError(model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadComplianceExportJob) { + c.SetPermissionError(model.PermissionReadComplianceExportJob) return } @@ -108,8 +108,8 @@ func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request defer c.LogAuditRec(auditRec) auditRec.AddMeta("compliance_id", c.Params.ReportId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { - c.SetPermissionError(model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDownloadComplianceExportResult) { + c.SetPermissionError(model.PermissionDownloadComplianceExportResult) return } diff --git a/api4/config.go b/api4/config.go index 0d96342b65..59596b7d53 100644 --- a/api4/config.go +++ b/api4/config.go @@ -78,8 +78,8 @@ func configReload(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("configReload", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_RELOAD_CONFIG) { - c.SetPermissionError(model.PERMISSION_RELOAD_CONFIG) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReloadConfig) { + c.SetPermissionError(model.PermissionReloadConfig) return } @@ -307,7 +307,7 @@ func makeFilterConfigByPermission(accessType filterType) func(c *Context, struct // If there are no access tag values and the role has manage_system, no need to continue // checking permissions. if len(tagPermissions) == 0 { - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { return true } } @@ -355,7 +355,7 @@ func makeFilterConfigByPermission(accessType filterType) func(c *Context, struct } // with manage_system, default to allow, otherwise default not-allow - return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) + return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) } } @@ -377,8 +377,8 @@ func migrateConfig(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("to", to) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/config_test.go b/api4/config_test.go index e4353e3c3d..1e3d876b6e 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -34,26 +34,26 @@ func TestGetConfig(t *testing.T) { require.NotEqual(t, "", cfg.TeamSettings.SiteName) - if *cfg.LdapSettings.BindPassword != model.FAKE_SETTING && *cfg.LdapSettings.BindPassword != "" { + if *cfg.LdapSettings.BindPassword != model.FakeSetting && *cfg.LdapSettings.BindPassword != "" { require.FailNow(t, "did not sanitize properly") } - require.Equal(t, model.FAKE_SETTING, *cfg.FileSettings.PublicLinkSalt, "did not sanitize properly") + require.Equal(t, model.FakeSetting, *cfg.FileSettings.PublicLinkSalt, "did not sanitize properly") - if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FAKE_SETTING && *cfg.FileSettings.AmazonS3SecretAccessKey != "" { + if *cfg.FileSettings.AmazonS3SecretAccessKey != model.FakeSetting && *cfg.FileSettings.AmazonS3SecretAccessKey != "" { require.FailNow(t, "did not sanitize properly") } - if *cfg.EmailSettings.SMTPPassword != model.FAKE_SETTING && *cfg.EmailSettings.SMTPPassword != "" { + if *cfg.EmailSettings.SMTPPassword != model.FakeSetting && *cfg.EmailSettings.SMTPPassword != "" { require.FailNow(t, "did not sanitize properly") } - if *cfg.GitLabSettings.Secret != model.FAKE_SETTING && *cfg.GitLabSettings.Secret != "" { + if *cfg.GitLabSettings.Secret != model.FakeSetting && *cfg.GitLabSettings.Secret != "" { require.FailNow(t, "did not sanitize properly") } - require.Equal(t, model.FAKE_SETTING, *cfg.SqlSettings.DataSource, "did not sanitize properly") - require.Equal(t, model.FAKE_SETTING, *cfg.SqlSettings.AtRestEncryptKey, "did not sanitize properly") - if !strings.Contains(strings.Join(cfg.SqlSettings.DataSourceReplicas, " "), model.FAKE_SETTING) && len(cfg.SqlSettings.DataSourceReplicas) != 0 { + require.Equal(t, model.FakeSetting, *cfg.SqlSettings.DataSource, "did not sanitize properly") + require.Equal(t, model.FakeSetting, *cfg.SqlSettings.AtRestEncryptKey, "did not sanitize properly") + if !strings.Contains(strings.Join(cfg.SqlSettings.DataSourceReplicas, " "), model.FakeSetting) && len(cfg.SqlSettings.DataSourceReplicas) != 0 { require.FailNow(t, "did not sanitize properly") } - if !strings.Contains(strings.Join(cfg.SqlSettings.DataSourceSearchReplicas, " "), model.FAKE_SETTING) && len(cfg.SqlSettings.DataSourceSearchReplicas) != 0 { + if !strings.Contains(strings.Join(cfg.SqlSettings.DataSourceSearchReplicas, " "), model.FakeSetting) && len(cfg.SqlSettings.DataSourceSearchReplicas) != 0 { require.FailNow(t, "did not sanitize properly") } }) @@ -81,8 +81,8 @@ func TestGetConfigWithAccessTag(t *testing.T) { th.Client.Login(th.BasicUser.Username, th.BasicUser.Password) // add read sysconsole environment config - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId) cfg, resp := th.Client.GetConfig() CheckNoError(t, resp) @@ -112,8 +112,8 @@ func TestGetConfigAnyFlagsAccess(t *testing.T) { }) // add read sysconsole environment config - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId) cfg, resp := th.Client.GetConfig() CheckNoError(t, resp) @@ -258,7 +258,7 @@ func TestGetConfigWithoutManageSystemPermission(t *testing.T) { CheckForbiddenStatus(t, resp) // add any sysconsole read permission - th.AddPermissionToRole(model.SysconsoleReadPermissions[0].Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.SysconsoleReadPermissions[0].Id, model.SystemUserRoleId) _, resp = th.Client.GetConfig() // should be readable now @@ -272,8 +272,8 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) { th.Client.Login(th.BasicUser.Username, th.BasicUser.Password) // add read sysconsole integrations config - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, model.SystemUserRoleId) t.Run("sysconsole read permission does not provides config write access", func(t *testing.T) { // should be readable because has a sysconsole read permission @@ -293,8 +293,8 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) { originalValue := *cfg.ServiceSettings.AllowCorsFrom // add the wrong write permission - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleWriteAboutEditionAndLicense.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteAboutEditionAndLicense.Id, model.SystemUserRoleId) // try update a config value allowed by sysconsole WRITE integrations mockVal := model.NewId() @@ -313,10 +313,10 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) { cfg, resp := th.SystemAdminClient.GetConfig() CheckNoError(t, resp) - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleWriteIntegrationsCors.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteIntegrationsCors.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionSysconsoleReadIntegrationsCors.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadIntegrationsCors.Id, model.SystemUserRoleId) // try update a config value allowed by sysconsole WRITE integrations mockVal := model.NewId() @@ -704,7 +704,7 @@ func TestPatchConfig(t *testing.T) { updatedConfig, _ := client.PatchConfig(&config) - assert.Equal(t, model.FAKE_SETTING, *updatedConfig.SqlSettings.DataSource) + assert.Equal(t, model.FakeSetting, *updatedConfig.SqlSettings.DataSource) }) t.Run("not allowing to toggle enable uploads for plugin via api", func(t *testing.T) { diff --git a/api4/data_retention.go b/api4/data_retention.go index bf150992d0..9bcbd12d4b 100644 --- a/api4/data_retention.go +++ b/api4/data_retention.go @@ -44,8 +44,8 @@ func getGlobalPolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getPolicies(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -62,8 +62,8 @@ func getPolicies(c *Context, w http.ResponseWriter, r *http.Request) { } func getPoliciesCount(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -78,8 +78,8 @@ func getPoliciesCount(c *Context, w http.ResponseWriter, r *http.Request) { } func getPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -102,8 +102,8 @@ func createPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy", policy) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -131,8 +131,8 @@ func patchPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("patch", patch) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -152,8 +152,8 @@ func deletePolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deletePolicy", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy_id", policyId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -167,8 +167,8 @@ func deletePolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getTeamsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -194,8 +194,8 @@ func getTeamsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { func searchTeamsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) { c.RequirePolicyId() - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -231,8 +231,8 @@ func addTeamsToPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("team_ids", teamIDs) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -260,8 +260,8 @@ func removeTeamsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("team_ids", teamIDs) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -276,8 +276,8 @@ func removeTeamsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getChannelsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -308,8 +308,8 @@ func searchChannelsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } @@ -347,8 +347,8 @@ func addChannelsToPolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("channel_ids", channelIDs) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -376,8 +376,8 @@ func removeChannelsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("channel_ids", channelIDs) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy) return } @@ -400,8 +400,8 @@ func getTeamPoliciesForUser(c *Context, w http.ResponseWriter, r *http.Request) limit := c.Params.PerPage offset := c.Params.Page * limit - if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -423,8 +423,8 @@ func getChannelPoliciesForUser(c *Context, w http.ResponseWriter, r *http.Reques limit := c.Params.PerPage offset := c.Params.Page * limit - if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index 6d299338bd..8ec20adb7c 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -23,8 +23,8 @@ func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { // PERMISSION_TEST_ELASTICSEARCH is an ancillary permission of PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH, // which should prevent read-only managers from password sniffing - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_ELASTICSEARCH) { - c.SetPermissionError(model.PERMISSION_TEST_ELASTICSEARCH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestElasticsearch) { + c.SetPermissionError(model.PermissionTestElasticsearch) return } @@ -45,8 +45,8 @@ func purgeElasticsearchIndexes(c *Context, w http.ResponseWriter, r *http.Reques auditRec := c.MakeAuditRecord("purgeElasticsearchIndexes", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES) { - c.SetPermissionError(model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionPurgeElasticsearchIndexes) { + c.SetPermissionError(model.PermissionPurgeElasticsearchIndexes) return } diff --git a/api4/emoji.go b/api4/emoji.go index 198895bdee..59de0ac269 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -59,16 +59,16 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_EMOJIS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateEmojis) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PERMISSION_CREATE_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PermissionCreateEmojis) { hasPermission = true break } } if !hasPermission { - c.SetPermissionError(model.PERMISSION_CREATE_EMOJIS) + c.SetPermissionError(model.PermissionCreateEmojis) return } } @@ -106,7 +106,7 @@ func getEmojiList(c *Context, w http.ResponseWriter, r *http.Request) { } sort := r.URL.Query().Get("sort") - if sort != "" && sort != model.EMOJI_SORT_BY_NAME { + if sort != "" && sort != model.EmojiSortByName { c.SetInvalidUrlParam("sort") return } @@ -145,32 +145,32 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DELETE_EMOJIS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDeleteEmojis) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PERMISSION_DELETE_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PermissionDeleteEmojis) { hasPermission = true break } } if !hasPermission { - c.SetPermissionError(model.PERMISSION_DELETE_EMOJIS) + c.SetPermissionError(model.PermissionDeleteEmojis) return } } if c.AppContext.Session().UserId != emoji.CreatorId { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DELETE_OTHERS_EMOJIS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDeleteOthersEmojis) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PERMISSION_DELETE_OTHERS_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), membership.TeamId, model.PermissionDeleteOthersEmojis) { hasPermission = true break } } if !hasPermission { - c.SetPermissionError(model.PERMISSION_DELETE_OTHERS_EMOJIS) + c.SetPermissionError(model.PermissionDeleteOthersEmojis) return } } diff --git a/api4/emoji_test.go b/api4/emoji_test.go index 2dd6a6855e..f4313016e4 100644 --- a/api4/emoji_test.go +++ b/api4/emoji_test.go @@ -169,7 +169,7 @@ func TestCreateEmoji(t *testing.T) { CheckForbiddenStatus(t, resp) // try to create an emoji without permissions - th.RemovePermissionFromRole(model.PERMISSION_CREATE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionCreateEmojis.Id, model.SystemUserRoleId) emoji = &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -180,7 +180,7 @@ func TestCreateEmoji(t *testing.T) { CheckForbiddenStatus(t, resp) // create an emoji with permissions in one team - th.AddPermissionToRole(model.PERMISSION_CREATE_EMOJIS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionCreateEmojis.Id, model.TeamUserRoleId) emoji = &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -254,7 +254,7 @@ func TestGetEmojiList(t *testing.T) { require.Len(t, listEmoji, 1, "should only return 1") - listEmoji, resp = Client.GetSortedEmojiList(0, 100, model.EMOJI_SORT_BY_NAME) + listEmoji, resp = Client.GetSortedEmojiList(0, 100, model.EmojiSortByName) CheckNoError(t, resp) require.Greater(t, len(listEmoji), 0, "should return more than 0") @@ -320,10 +320,10 @@ func TestDeleteEmoji(t *testing.T) { newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) _, resp = Client.DeleteEmoji(newEmoji.Id) CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) //Try to delete other user's custom emoji without DELETE_EMOJIS permissions emoji = &model.Emoji{ @@ -334,8 +334,8 @@ func TestDeleteEmoji(t *testing.T) { newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId) Client.Logout() th.LoginBasic2() @@ -343,8 +343,8 @@ func TestDeleteEmoji(t *testing.T) { _, resp = Client.DeleteEmoji(newEmoji.Id) CheckForbiddenStatus(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) Client.Logout() th.LoginBasic() @@ -376,8 +376,8 @@ func TestDeleteEmoji(t *testing.T) { newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId) Client.Logout() th.LoginBasic2() @@ -392,12 +392,12 @@ func TestDeleteEmoji(t *testing.T) { newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId) _, resp = Client.DeleteEmoji(newEmoji.Id) CheckNoError(t, resp) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_EMOJIS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId) //Try to delete other user's custom emoji with permissions at team level emoji = &model.Emoji{ @@ -408,11 +408,11 @@ func TestDeleteEmoji(t *testing.T) { newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId) - th.AddPermissionToRole(model.PERMISSION_DELETE_EMOJIS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.TeamUserRoleId) Client.Logout() th.LoginBasic2() diff --git a/api4/export.go b/api4/export.go index b43999cdbe..69438d5182 100644 --- a/api4/export.go +++ b/api4/export.go @@ -21,7 +21,7 @@ func (api *API) InitExport() { func listExports(c *Context, w http.ResponseWriter, r *http.Request) { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } @@ -46,7 +46,7 @@ func deleteExport(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("export_name", c.Params.ExportName) if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } @@ -61,7 +61,7 @@ func deleteExport(c *Context, w http.ResponseWriter, r *http.Request) { func downloadExport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/file.go b/api4/file.go index 80444a0953..762c214e62 100644 --- a/api4/file.go +++ b/api4/file.go @@ -162,8 +162,8 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel_id", c.Params.ChannelId) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { - c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { + c.SetPermissionError(model.PermissionUploadFile) return nil } @@ -224,7 +224,7 @@ func uploadFileMultipart(c *Context, r *http.Request, asStream io.Reader, timest } nFiles := 0 -NEXT_PART: +NextPart: for { part, err := mr.NextPart() if err == io.EOF { @@ -285,7 +285,7 @@ NEXT_PART: return nil } - continue NEXT_PART + continue NextPart } // A file part. @@ -307,8 +307,8 @@ NEXT_PART: if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { - c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { + c.SetPermissionError(model.PermissionUploadFile) return nil } @@ -396,8 +396,8 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_UPLOAD_FILE) { - c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionUploadFile) { + c.SetPermissionError(model.PermissionUploadFile) return nil } @@ -481,8 +481,8 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("file", info) - if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -512,8 +512,8 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -554,8 +554,8 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("file", info) - if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -587,8 +587,8 @@ func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -620,8 +620,8 @@ func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -734,8 +734,8 @@ func searchFiles(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } diff --git a/api4/file_test.go b/api4/file_test.go index f5d7b8249d..f57ca494e4 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -68,7 +68,7 @@ func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob [] } req.Header.Set("Content-Type", contentType) if c.AuthToken != "" { - req.Header.Set(model.HEADER_AUTH, c.AuthType+" "+c.AuthToken) + req.Header.Set(model.HeaderAuth, c.AuthType+" "+c.AuthToken) } resp, err := c.HttpClient.Do(req) diff --git a/api4/group.go b/api4/group.go index 4e3bbc2911..046cd1eb9e 100644 --- a/api4/group.go +++ b/api4/group.go @@ -88,8 +88,8 @@ func getGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -128,8 +128,8 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementGroups) return } @@ -145,7 +145,7 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) { tmp := strings.ReplaceAll(strings.ToLower(group.DisplayName), " ", "-") groupPatch.Name = &tmp } else { - if *groupPatch.Name == model.USER_NOTIFY_ALL || *groupPatch.Name == model.CHANNEL_MENTIONS_NOTIFY_PROP || *groupPatch.Name == model.USER_NOTIFY_HERE { + if *groupPatch.Name == model.UserNotifyAll || *groupPatch.Name == model.ChannelMentionsNotifyProp || *groupPatch.Name == model.UserNotifyHere { c.Err = model.NewAppError("Api4.patchGroup", "api.ldap_groups.existing_reserved_name_error", nil, "", http.StatusNotImplemented) return } @@ -284,8 +284,8 @@ func getGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -321,8 +321,8 @@ func getGroupSyncables(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -473,8 +473,8 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType, syncableID string) *model.AppError { switch syncableType { case model.GroupSyncableTypeTeam: - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), syncableID, model.PERMISSION_MANAGE_TEAM) { - return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{model.PERMISSION_MANAGE_TEAM}) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), syncableID, model.PermissionManageTeam) { + return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{model.PermissionManageTeam}) } case model.GroupSyncableTypeChannel: channel, err := c.App.GetChannel(syncableID) @@ -483,10 +483,10 @@ func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType } var permission *model.Permission - if channel.Type == model.CHANNEL_PRIVATE { - permission = model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS + if channel.Type == model.ChannelTypePrivate { + permission = model.PermissionManagePrivateChannelMembers } else { - permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS + permission = model.PermissionManagePublicChannelMembers } if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), syncableID, permission) { @@ -508,8 +508,8 @@ func getGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -545,8 +545,8 @@ func getGroupStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -575,8 +575,8 @@ func getGroupsByUserId(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -617,10 +617,10 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } var permission *model.Permission - if channel.Type == model.CHANNEL_PRIVATE { - permission = model.PERMISSION_READ_PRIVATE_CHANNEL_GROUPS + if channel.Type == model.ChannelTypePrivate { + permission = model.PermissionReadPrivateChannelGroups } else { - permission = model.PERMISSION_READ_PUBLIC_CHANNEL_GROUPS + permission = model.PermissionReadPublicChannelGroups } if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, permission) { c.SetPermissionError(permission) @@ -779,10 +779,10 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { return } var permission *model.Permission - if channel.Type == model.CHANNEL_PRIVATE { - permission = model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS + if channel.Type == model.ChannelTypePrivate { + permission = model.PermissionManagePrivateChannelMembers } else { - permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS + permission = model.PermissionManagePublicChannelMembers } if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelID, permission) { c.SetPermissionError(permission) diff --git a/api4/group_test.go b/api4/group_test.go index 726942328a..4188772b67 100644 --- a/api4/group_test.go +++ b/api4/group_test.go @@ -691,7 +691,7 @@ func TestGetGroupsByChannel(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense("ldap")) - privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) + privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) _, _, response := th.Client.GetGroupsByChannel(privateChannel.Id, opts) CheckForbiddenStatus(t, response) @@ -980,7 +980,7 @@ func TestGetGroupsByUserId(t *testing.T) { }) assert.Nil(t, err) - user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId}) assert.Nil(t, err) user1.Password = "test-password-1" _, err = th.App.UpsertGroupMember(group1.Id, user1.Id) @@ -1064,7 +1064,7 @@ func TestGetGroupStats(t *testing.T) { assert.Equal(t, stats.TotalMemberCount, int64(0)) }) - user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId}) assert.Nil(t, err) _, err = th.App.UpsertGroupMember(group.Id, user1.Id) assert.Nil(t, err) @@ -1102,7 +1102,7 @@ func TestGetGroupsGroupConstrainedParentTeam(t *testing.T) { channel := &model.Channel{ DisplayName: "dn_" + id, Name: "name" + id, - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: team.Id, GroupConstrained: model.NewBool(true), } diff --git a/api4/handlers_test.go b/api4/handlers_test.go index 9d4d48b6a4..b654e7d591 100644 --- a/api4/handlers_test.go +++ b/api4/handlers_test.go @@ -23,7 +23,7 @@ func testAPIHandlerGzipMode(t *testing.T, name string, h http.Handler, token str t.Run("Handler: "+name+" No Accept-Encoding", func(t *testing.T) { resp := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v4/test", nil) - req.Header.Set(model.HEADER_AUTH, "Bearer "+token) + req.Header.Set(model.HeaderAuth, "Bearer "+token) h.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "", resp.Header().Get("Content-Encoding")) @@ -33,7 +33,7 @@ func testAPIHandlerGzipMode(t *testing.T, name string, h http.Handler, token str resp := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v4/test", nil) req.Header.Set("Accept-Encoding", "gzip") - req.Header.Set(model.HEADER_AUTH, "Bearer "+token) + req.Header.Set(model.HeaderAuth, "Bearer "+token) h.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) @@ -45,7 +45,7 @@ func testAPIHandlerNoGzipMode(t *testing.T, name string, h http.Handler, token s t.Run("Handler: "+name+" No Accept-Encoding", func(t *testing.T) { resp := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v4/test", nil) - req.Header.Set(model.HEADER_AUTH, "Bearer "+token) + req.Header.Set(model.HeaderAuth, "Bearer "+token) h.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) @@ -56,7 +56,7 @@ func testAPIHandlerNoGzipMode(t *testing.T, name string, h http.Handler, token s resp := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v4/test", nil) req.Header.Set("Accept-Encoding", "gzip") - req.Header.Set(model.HEADER_AUTH, "Bearer "+token) + req.Header.Set(model.HeaderAuth, "Bearer "+token) h.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) diff --git a/api4/image_test.go b/api4/image_test.go index 92bfa2d130..be25414139 100644 --- a/api4/image_test.go +++ b/api4/image_test.go @@ -35,7 +35,7 @@ func TestGetImage(t *testing.T) { r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err := th.Client.HttpClient.Do(r) require.NoError(t, err) @@ -56,7 +56,7 @@ func TestGetImage(t *testing.T) { r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err := th.Client.HttpClient.Do(r) require.NoError(t, err) @@ -83,7 +83,7 @@ func TestGetImage(t *testing.T) { r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageServer.URL+"/image.png"), nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err := th.Client.HttpClient.Do(r) require.NoError(t, err) @@ -96,7 +96,7 @@ func TestGetImage(t *testing.T) { // local images should not be proxied, but forwarded r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url=/plugins/test/image.png", nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err = th.Client.HttpClient.Do(r) require.NoError(t, err) @@ -108,7 +108,7 @@ func TestGetImage(t *testing.T) { }) r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+strings.TrimPrefix(imageServer.URL, "http:")+"/image.png", nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err = th.Client.HttpClient.Do(r) require.NoError(t, err) @@ -117,7 +117,7 @@ func TestGetImage(t *testing.T) { // opaque URLs are not supported, should return an error r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url=mailto:test@example.com", nil) require.NoError(t, err) - r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + r.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) resp, err = th.Client.HttpClient.Do(r) require.NoError(t, err) diff --git a/api4/import.go b/api4/import.go index b91d5c5a67..48363d79ce 100644 --- a/api4/import.go +++ b/api4/import.go @@ -16,7 +16,7 @@ func (api *API) InitImport() { func listImports(c *Context, w http.ResponseWriter, r *http.Request) { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/integration_action.go b/api4/integration_action.go index 9e44188055..e0e2992b9b 100644 --- a/api4/integration_action.go +++ b/api4/integration_action.go @@ -41,13 +41,13 @@ func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), cookie.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), cookie.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } else { - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } @@ -103,13 +103,13 @@ func submitDialog(c *Context, w http.ResponseWriter, r *http.Request) { submit.UserId = c.AppContext.Session().UserId - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), submit.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), submit.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), submit.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), submit.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } diff --git a/api4/integration_action_test.go b/api4/integration_action_test.go index d4a9d75b12..01dc582ed4 100644 --- a/api4/integration_action_test.go +++ b/api4/integration_action_test.go @@ -61,7 +61,7 @@ func TestPostActionCookies(t *testing.T) { Action: model.PostAction{ Id: model.NewId(), Name: "Test-action", - Type: model.POST_ACTION_TYPE_BUTTON, + Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, Context: map[string]interface{}{ @@ -76,7 +76,7 @@ func TestPostActionCookies(t *testing.T) { Action: model.PostAction{ Id: "someID", Name: "Test-action", - Type: model.POST_ACTION_TYPE_BUTTON, + Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, Context: map[string]interface{}{ @@ -91,7 +91,7 @@ func TestPostActionCookies(t *testing.T) { Action: model.PostAction{ Id: "", Name: "Test-action", - Type: model.POST_ACTION_TYPE_BUTTON, + Type: model.PostActionTypeButton, Integration: &model.PostActionIntegration{ URL: server.URL, Context: map[string]interface{}{ @@ -106,7 +106,7 @@ func TestPostActionCookies(t *testing.T) { t.Run(name, func(t *testing.T) { post := &model.Post{ Id: model.NewId(), - Type: model.POST_EPHEMERAL, + Type: model.PostTypeEphemeral, UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, CreateAt: model.GetMillis(), diff --git a/api4/job.go b/api4/job.go index cbbb91fc08..cf2e25d5b9 100644 --- a/api4/job.go +++ b/api4/job.go @@ -71,10 +71,10 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) { // Currently, this endpoint only supports downloading the compliance report. // If you need to download another job type, you will need to alter this section of the code to accommodate it. - if job.Type == model.JOB_TYPE_MESSAGE_EXPORT && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { - c.SetPermissionError(model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) + if job.Type == model.JobTypeMessageExport && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDownloadComplianceExportResult) { + c.SetPermissionError(model.PermissionDownloadComplianceExportResult) return - } else if job.Type != model.JOB_TYPE_MESSAGE_EXPORT { + } else if job.Type != model.JobTypeMessageExport { c.Err = model.NewAppError("unableToDownloadJob", "api.job.unable_to_download_job.incorrect_job_type", nil, "", http.StatusBadRequest) return } @@ -141,7 +141,7 @@ func getJobs(c *Context, w http.ResponseWriter, r *http.Request) { } var validJobTypes []string - for _, jobType := range model.ALL_JOB_TYPES { + for _, jobType := range model.AllJobTypes { hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), jobType) if permissionRequired == nil { mlog.Warn("The job types of a job you are trying to retrieve does not contain permissions", mlog.String("jobType", jobType)) diff --git a/api4/job_test.go b/api4/job_test.go index 76201397c0..dd46448db4 100644 --- a/api4/job_test.go +++ b/api4/job_test.go @@ -19,7 +19,7 @@ func TestCreateJob(t *testing.T) { defer th.TearDown() job := &model.Job{ - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Type: model.JobTypeMessageExport, Data: map[string]string{ "thing": "stuff", }, @@ -40,7 +40,7 @@ func TestCreateJob(t *testing.T) { _, resp = th.SystemAdminClient.CreateJob(job) CheckBadRequestStatus(t, resp) - job.Type = model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING + job.Type = model.JobTypeElasticsearchPostIndexing _, resp = th.Client.CreateJob(job) CheckForbiddenStatus(t, resp) } @@ -51,8 +51,8 @@ func TestGetJob(t *testing.T) { job := &model.Job{ Id: model.NewId(), - Status: model.JOB_STATUS_PENDING, - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Status: model.JobStatusPending, + Type: model.JobTypeMessageExport, } _, err := th.App.Srv().Store.Job().Save(job) require.NoError(t, err) @@ -79,7 +79,7 @@ func TestGetJobs(t *testing.T) { th := Setup(t) defer th.TearDown() - jobType := model.JOB_TYPE_DATA_RETENTION + jobType := model.JobTypeDataRetention t0 := model.GetMillis() jobs := []*model.Job{ @@ -126,7 +126,7 @@ func TestGetJobsByType(t *testing.T) { th := Setup(t) defer th.TearDown() - jobType := model.JOB_TYPE_DATA_RETENTION + jobType := model.JobTypeDataRetention jobs := []*model.Job{ { @@ -179,7 +179,7 @@ func TestGetJobsByType(t *testing.T) { _, resp = th.Client.GetJobsByType(jobType, 0, 60) CheckForbiddenStatus(t, resp) - _, resp = th.SystemManagerClient.GetJobsByType(model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING, 0, 60) + _, resp = th.SystemManagerClient.GetJobsByType(model.JobTypeElasticsearchPostIndexing, 0, 60) require.Nil(t, resp.Error) } @@ -189,11 +189,11 @@ func TestDownloadJob(t *testing.T) { jobName := model.NewId() job := &model.Job{ Id: jobName, - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Type: model.JobTypeMessageExport, Data: map[string]string{ "export_type": "csv", }, - Status: model.JOB_STATUS_SUCCESS, + Status: model.JobStatusSuccess, } // DownloadExportResults is not set to true so we should get a not implemented error status @@ -235,7 +235,7 @@ func TestDownloadJob(t *testing.T) { CheckBadRequestStatus(t, resp) job.Data["is_downloadable"] = "true" - updateStatus, err := th.App.Srv().Store.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS) + updateStatus, err := th.App.Srv().Store.Job().UpdateOptimistically(job, model.JobStatusSuccess) require.True(t, updateStatus) require.NoError(t, err) @@ -256,11 +256,11 @@ func TestDownloadJob(t *testing.T) { jobName = model.NewId() job = &model.Job{ Id: jobName, - Type: model.JOB_TYPE_CLOUD, + Type: model.JobTypeCloud, Data: map[string]string{ "export_type": "csv", }, - Status: model.JOB_STATUS_SUCCESS, + Status: model.JobStatusSuccess, } _, err = th.App.Srv().Store.Job().Save(job) require.NoError(t, err) @@ -275,22 +275,22 @@ func TestCancelJob(t *testing.T) { th := Setup(t) defer th.TearDown() - jobType := model.JOB_TYPE_MESSAGE_EXPORT + jobType := model.JobTypeMessageExport jobs := []*model.Job{ { Id: model.NewId(), Type: jobType, - Status: model.JOB_STATUS_PENDING, + Status: model.JobStatusPending, }, { Id: model.NewId(), Type: jobType, - Status: model.JOB_STATUS_IN_PROGRESS, + Status: model.JobStatusInProgress, }, { Id: model.NewId(), Type: jobType, - Status: model.JOB_STATUS_SUCCESS, + Status: model.JobStatusSuccess, }, } diff --git a/api4/ldap.go b/api4/ldap.go index 18102d4986..7c8137b9a6 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -56,8 +56,8 @@ func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("syncLdap", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_LDAP_SYNC_JOB) { - c.SetPermissionError(model.PERMISSION_CREATE_LDAP_SYNC_JOB) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateLdapSyncJob) { + c.SetPermissionError(model.PermissionCreateLdapSyncJob) return } @@ -73,8 +73,8 @@ func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_LDAP) { - c.SetPermissionError(model.PERMISSION_TEST_LDAP) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestLdap) { + c.SetPermissionError(model.PermissionTestLdap) return } @@ -87,8 +87,8 @@ func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { } func getLdapGroups(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -144,8 +144,8 @@ func linkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementGroups) return } @@ -245,8 +245,8 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("remote_id", c.Params.RemoteId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementGroups) return } @@ -285,8 +285,8 @@ func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("idMigrateLdap", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -325,8 +325,8 @@ func parseLdapCertificateRequest(r *http.Request, maxFileSize int64) (*multipart } func addLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_LDAP_PUBLIC_CERT) { - c.SetPermissionError(model.PERMISSION_ADD_LDAP_PUBLIC_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionAddLdapPublicCert) { + c.SetPermissionError(model.PermissionAddLdapPublicCert) return } @@ -349,8 +349,8 @@ func addLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request } func addLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_LDAP_PRIVATE_CERT) { - c.SetPermissionError(model.PERMISSION_ADD_LDAP_PRIVATE_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionAddLdapPrivateCert) { + c.SetPermissionError(model.PermissionAddLdapPrivateCert) return } @@ -373,8 +373,8 @@ func addLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Reques } func removeLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT) { - c.SetPermissionError(model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveLdapPublicCert) { + c.SetPermissionError(model.PermissionRemoveLdapPublicCert) return } @@ -391,8 +391,8 @@ func removeLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Requ } func removeLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT) { - c.SetPermissionError(model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveLdapPrivateCert) { + c.SetPermissionError(model.PermissionRemoveLdapPrivateCert) return } diff --git a/api4/license.go b/api4/license.go index 9476f60da1..b16d640c01 100644 --- a/api4/license.go +++ b/api4/license.go @@ -41,7 +41,7 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { var clientLicense map[string]string - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_LICENSE_INFORMATION) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadLicenseInformation) { clientLicense = c.App.Srv().ClientLicense() } else { clientLicense = c.App.Srv().GetSanitizedClientLicense() @@ -55,8 +55,8 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { - c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageLicenseInformation) { + c.SetPermissionError(model.PermissionManageLicenseInformation) return } @@ -120,9 +120,9 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { license, appErr = c.App.Srv().SaveLicense(licenseBytes) if appErr != nil { - if appErr.Id == model.EXPIRED_LICENSE_ERROR { + if appErr.Id == model.ExpiredLicenseError { c.LogAudit("failed - expired or non-started license") - } else if appErr.Id == model.INVALID_LICENSE_ERROR { + } else if appErr.Id == model.InvalidLicenseError { c.LogAudit("failed - invalid license") } else { c.LogAudit("failed - unable to save license") @@ -142,8 +142,8 @@ func removeLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { - c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageLicenseInformation) { + c.SetPermissionError(model.PermissionManageLicenseInformation) return } @@ -168,8 +168,8 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { - c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageLicenseInformation) { + c.SetPermissionError(model.PermissionManageLicenseInformation) return } @@ -218,7 +218,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { trialLicenseRequest := &model.TrialLicenseRequest{ ServerID: c.App.TelemetryId(), - Name: currentUser.GetDisplayName(model.SHOW_FULLNAME), + Name: currentUser.GetDisplayName(model.ShowFullName), Email: currentUser.Email, SiteName: *c.App.Config().TeamSettings.SiteName, SiteURL: *c.App.Config().ServiceSettings.SiteURL, @@ -248,8 +248,8 @@ func requestRenewalLink(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { - c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageLicenseInformation) { + c.SetPermissionError(model.PermissionManageLicenseInformation) return } @@ -283,7 +283,7 @@ func getPrevTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { var clientLicense map[string]string - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_LICENSE_INFORMATION) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadLicenseInformation) { clientLicense = utils.GetClientLicense(license) } else { clientLicense = utils.GetSanitizedClientLicense(utils.GetClientLicense(license)) diff --git a/api4/license_local.go b/api4/license_local.go index 36462f8da5..624bb0a9fa 100644 --- a/api4/license_local.go +++ b/api4/license_local.go @@ -56,9 +56,9 @@ func localAddLicense(c *Context, w http.ResponseWriter, r *http.Request) { license, appErr := c.App.Srv().SaveLicense(buf.Bytes()) if appErr != nil { - if appErr.Id == model.EXPIRED_LICENSE_ERROR { + if appErr.Id == model.ExpiredLicenseError { c.LogAudit("failed - expired or non-started license") - } else if appErr.Id == model.INVALID_LICENSE_ERROR { + } else if appErr.Id == model.InvalidLicenseError { c.LogAudit("failed - invalid license") } else { c.LogAudit("failed - unable to save license") diff --git a/api4/oauth.go b/api4/oauth.go index 8adf9cb772..5717cce553 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -33,12 +33,12 @@ func createOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createOAuthApp", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { + c.SetPermissionError(model.PermissionManageOAuth) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { oauthApp.IsTrusted = false } @@ -69,8 +69,8 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("oauth_app_id", c.Params.AppId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { + c.SetPermissionError(model.PermissionManageOAuth) return } @@ -86,49 +86,49 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - oldOauthApp, err := c.App.GetOAuthApp(c.Params.AppId) + oldOAuthApp, err := c.App.GetOAuthApp(c.Params.AppId) if err != nil { c.Err = err return } - auditRec.AddMeta("oauth_app", oldOauthApp) + auditRec.AddMeta("oauth_app", oldOAuthApp) - if c.AppContext.Session().UserId != oldOauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) + if c.AppContext.Session().UserId != oldOAuthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystemWideOAuth) { + c.SetPermissionError(model.PermissionManageSystemWideOAuth) return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - oauthApp.IsTrusted = oldOauthApp.IsTrusted + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + oauthApp.IsTrusted = oldOAuthApp.IsTrusted } - updatedOauthApp, err := c.App.UpdateOauthApp(oldOauthApp, oauthApp) + updatedOAuthApp, err := c.App.UpdateOAuthApp(oldOAuthApp, oauthApp) if err != nil { c.Err = err return } auditRec.Success() - auditRec.AddMeta("update", updatedOauthApp) + auditRec.AddMeta("update", updatedOAuthApp) c.LogAudit("success") - w.Write([]byte(updatedOauthApp.ToJson())) + w.Write([]byte(updatedOAuthApp.ToJson())) } func getOAuthApps(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { c.Err = model.NewAppError("getOAuthApps", "api.command.admin_only.app_error", nil, "", http.StatusForbidden) return } var apps []*model.OAuthApp var err *model.AppError - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystemWideOAuth) { apps, err = c.App.GetOAuthApps(c.Params.Page, c.Params.PerPage) - } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { + } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { apps, err = c.App.GetOAuthAppsByCreator(c.AppContext.Session().UserId, c.Params.Page, c.Params.PerPage) } else { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + c.SetPermissionError(model.PermissionManageOAuth) return } @@ -146,8 +146,8 @@ func getOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { + c.SetPermissionError(model.PermissionManageOAuth) return } @@ -157,8 +157,8 @@ func getOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if oauthApp.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) + if oauthApp.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystemWideOAuth) { + c.SetPermissionError(model.PermissionManageSystemWideOAuth) return } @@ -192,8 +192,8 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("oauth_app_id", c.Params.AppId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { + c.SetPermissionError(model.PermissionManageOAuth) return } @@ -204,8 +204,8 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("oauth_app", oauthApp) - if c.AppContext.Session().UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) + if c.AppContext.Session().UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystemWideOAuth) { + c.SetPermissionError(model.PermissionManageSystemWideOAuth) return } @@ -231,8 +231,8 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request defer c.LogAuditRec(auditRec) auditRec.AddMeta("oauth_app_id", c.Params.AppId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOAuth) { + c.SetPermissionError(model.PermissionManageOAuth) return } @@ -243,8 +243,8 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request } auditRec.AddMeta("oauth_app", oauthApp) - if oauthApp.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) + if oauthApp.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystemWideOAuth) { + c.SetPermissionError(model.PermissionManageSystemWideOAuth) return } @@ -267,7 +267,7 @@ func getAuthorizedOAuthApps(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } diff --git a/api4/oauth_test.go b/api4/oauth_test.go index 164442576f..cdd301131e 100644 --- a/api4/oauth_test.go +++ b/api4/oauth_test.go @@ -28,7 +28,7 @@ func TestCreateOAuthApp(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) @@ -41,12 +41,12 @@ func TestCreateOAuthApp(t *testing.T) { assert.Equal(t, oapp.IsTrusted, rapp.IsTrusted, "trusted did no match") // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.CreateOAuthApp(oapp) CheckForbiddenStatus(t, resp) // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) rapp, resp = Client.CreateOAuthApp(oapp) CheckNoError(t, resp) @@ -86,7 +86,7 @@ func TestUpdateOAuthApp(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{ @@ -134,7 +134,7 @@ func TestUpdateOAuthApp(t *testing.T) { th.LoginBasic() // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.UpdateOAuthApp(oapp) CheckForbiddenStatus(t, resp) @@ -157,7 +157,7 @@ func TestUpdateOAuthApp(t *testing.T) { CheckBadRequestStatus(t, resp) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.LoginBasic() userOapp := &model.OAuthApp{ @@ -202,7 +202,7 @@ func TestGetOAuthApps(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -239,7 +239,7 @@ func TestGetOAuthApps(t *testing.T) { require.True(t, len(apps) == 1 || apps[0].Id == rapp2.Id, "wrong apps returned") // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.GetOAuthApps(0, 1000) CheckForbiddenStatus(t, resp) @@ -268,7 +268,7 @@ func TestGetOAuthApp(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -297,7 +297,7 @@ func TestGetOAuthApp(t *testing.T) { CheckForbiddenStatus(t, resp) // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.GetOAuthApp(rapp2.Id) CheckForbiddenStatus(t, resp) @@ -332,7 +332,7 @@ func TestGetOAuthAppInfo(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -361,7 +361,7 @@ func TestGetOAuthAppInfo(t *testing.T) { CheckNoError(t, resp) // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.GetOAuthAppInfo(rapp2.Id) CheckNoError(t, resp) @@ -396,7 +396,7 @@ func TestDeleteOAuthApp(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -429,7 +429,7 @@ func TestDeleteOAuthApp(t *testing.T) { CheckNoError(t, resp) // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.DeleteOAuthApp(rapp.Id) CheckForbiddenStatus(t, resp) @@ -463,7 +463,7 @@ func TestRegenerateOAuthAppSecret(t *testing.T) { }() // Grant permission to regular users. - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -497,7 +497,7 @@ func TestRegenerateOAuthAppSecret(t *testing.T) { CheckNoError(t, resp) // Revoke permission from regular users. - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) _, resp = Client.RegenerateOAuthAppSecret(rapp.Id) CheckForbiddenStatus(t, resp) @@ -535,7 +535,7 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) { CheckNoError(t, resp) authRequest := &model.AuthorizeRequest{ - ResponseType: model.AUTHCODE_RESPONSE_TYPE, + ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, RedirectUri: rapp.CallbackUrls[0], Scope: "", diff --git a/api4/permissions_test.go b/api4/permissions_test.go index c82c1a1eef..0de01b93c5 100644 --- a/api4/permissions_test.go +++ b/api4/permissions_test.go @@ -18,8 +18,8 @@ func TestGetAncillaryPermissions(t *testing.T) { var subsectionPermissions []string var expectedAncillaryPermissions []string t.Run("Valid Case, Passing in SubSection Permissions", func(t *testing.T) { - subsectionPermissions = []string{model.PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id} - expectedAncillaryPermissions = []string{model.PERMISSION_GET_ANALYTICS.Id} + subsectionPermissions = []string{model.PermissionSysconsoleReadReportingSiteStatistics.Id} + expectedAncillaryPermissions = []string{model.PermissionGetAnalytics.Id} actualAncillaryPermissions, resp := th.Client.GetAncillaryPermissions(subsectionPermissions) CheckNoError(t, resp) assert.Equal(t, append(subsectionPermissions, expectedAncillaryPermissions...), actualAncillaryPermissions) diff --git a/api4/plugin.go b/api4/plugin.go index 6330f76775..98027c80db 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -55,8 +55,8 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("uploadPlugin", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -106,8 +106,8 @@ func installPluginFromUrl(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("installPluginFromUrl", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -139,8 +139,8 @@ func installMarketplacePlugin(c *Context, w http.ResponseWriter, r *http.Request auditRec := c.MakeAuditRecord("installMarketplacePlugin", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -171,8 +171,8 @@ func getPlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadPlugins) { + c.SetPermissionError(model.PermissionSysconsoleReadPlugins) return } @@ -191,8 +191,8 @@ func getPluginStatuses(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadPlugins) { + c.SetPermissionError(model.PermissionSysconsoleReadPlugins) return } @@ -220,8 +220,8 @@ func removePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -272,8 +272,8 @@ func getMarketplacePlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadPlugins) { + c.SetPermissionError(model.PermissionSysconsoleReadPlugins) return } @@ -313,8 +313,8 @@ func enablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -342,8 +342,8 @@ func disablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWritePlugins) { + c.SetPermissionError(model.PermissionSysconsoleWritePlugins) return } @@ -394,13 +394,13 @@ func setFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } firstAdminVisitMarketplaceObj := model.System{ - Name: model.SYSTEM_FIRST_ADMIN_VISIT_MARKETPLACE, + Name: model.SystemFirstAdminVisitMarketplace, Value: "true", } @@ -409,7 +409,7 @@ func setFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h return } - message := model.NewWebSocketEvent(model.WEBSOCKET_FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketFirstAdminVisitMarketplaceStatusReceived, "", "", "", nil) message.Add("firstAdminVisitMarketplaceStatus", firstAdminVisitMarketplaceObj.Value) c.App.Publish(message) @@ -422,18 +422,18 @@ func getFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } - firstAdminVisitMarketplaceObj, err := c.App.Srv().Store.System().GetByName(model.SYSTEM_FIRST_ADMIN_VISIT_MARKETPLACE) + firstAdminVisitMarketplaceObj, err := c.App.Srv().Store.System().GetByName(model.SystemFirstAdminVisitMarketplace) if err != nil { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): firstAdminVisitMarketplaceObj = &model.System{ - Name: model.SYSTEM_FIRST_ADMIN_VISIT_MARKETPLACE, + Name: model.SystemFirstAdminVisitMarketplace, Value: "false", } default: diff --git a/api4/plugin_test.go b/api4/plugin_test.go index 5f4ab74870..4c1e5fde73 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -305,12 +305,12 @@ func TestNotifyClusterPluginEvent(t *testing.T) { Id: manifest.Id, } expectedInstallMessage := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INSTALL_PLUGIN, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventInstallPlugin, + SendType: model.ClusterSendReliable, WaitForAllToSend: true, Data: expectedPluginData.ToJson(), } - actualMessages := findClusterMessages(model.CLUSTER_EVENT_INSTALL_PLUGIN, messages) + actualMessages := findClusterMessages(model.ClusterEventInstallPlugin, messages) require.Equal(t, []*model.ClusterMessage{expectedInstallMessage}, actualMessages) // Upgrade @@ -329,7 +329,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) { for { select { case resp := <-webSocketClient.EventChannel: - if resp.EventType() == model.WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED && len(resp.GetData()["plugin_statuses"].([]interface{})) == 0 { + if resp.EventType() == model.WebsocketEventPluginStatusesChanged && len(resp.GetData()["plugin_statuses"].([]interface{})) == 0 { done <- true return } @@ -351,12 +351,12 @@ func TestNotifyClusterPluginEvent(t *testing.T) { messages = testCluster.GetMessages() expectedRemoveMessage := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_REMOVE_PLUGIN, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventRemovePlugin, + SendType: model.ClusterSendReliable, WaitForAllToSend: true, Data: expectedPluginData.ToJson(), } - actualMessages = findClusterMessages(model.CLUSTER_EVENT_REMOVE_PLUGIN, messages) + actualMessages = findClusterMessages(model.ClusterEventRemovePlugin, messages) require.Equal(t, []*model.ClusterMessage{expectedRemoveMessage}, actualMessages) pluginStored, appErr = th.App.FileExists(expectedPath) diff --git a/api4/post.go b/api4/post.go index cada1fba2d..5e8b332ce0 100644 --- a/api4/post.go +++ b/api4/post.go @@ -49,21 +49,21 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("post", post) hasPermission := false - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_CREATE_POST) { + if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionCreatePost) { hasPermission = true } else if channel, err := c.App.GetChannel(post.ChannelId); err == nil { // Temporary permission check method until advanced permissions, please do not copy - if channel.Type == model.CHANNEL_OPEN && c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_CREATE_POST_PUBLIC) { + if channel.Type == model.ChannelTypeOpen && c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionCreatePostPublic) { hasPermission = true } } if !hasPermission { - c.SetPermissionError(model.PERMISSION_CREATE_POST) + c.SetPermissionError(model.PermissionCreatePost) return } - if post.CreateAt != 0 && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if post.CreateAt != 0 && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { post.CreateAt = 0 } @@ -116,8 +116,8 @@ func createEphemeralPost(c *Context, w http.ResponseWriter, r *http.Request) { ephRequest.Post.UserId = c.AppContext.Session().UserId ephRequest.Post.CreateAt = model.GetMillis() - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_POST_EPHEMERAL) { - c.SetPermissionError(model.PERMISSION_CREATE_POST_EPHEMERAL) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreatePostEphemeral) { + c.SetPermissionError(model.PermissionCreatePostEphemeral) return } @@ -164,8 +164,8 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { page := c.Params.Page perPage := c.Params.PerPage - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -207,7 +207,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if etag != "" { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) } c.App.AddCursorIdsForPostList(list, afterPost, beforePost, since, page, perPage, collapsedThreads) @@ -224,13 +224,13 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht userId := c.Params.UserId if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), userId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } channelId := c.Params.ChannelId - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -270,7 +270,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht clientPostList := c.App.PreparePostListForClient(postList) if etag != "" { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) } w.Write([]byte(clientPostList.ToJson())) } @@ -282,7 +282,7 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -313,7 +313,7 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) if !ok { allowed = false - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { + if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { allowed = true } @@ -350,14 +350,14 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { - if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if channel.Type == model.ChannelTypeOpen { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) { + c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + c.SetPermissionError(model.PermissionReadChannel) return } } @@ -368,7 +368,7 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - w.Header().Set(model.HEADER_ETAG_SERVER, post.Etag()) + w.Header().Set(model.HeaderEtagServer, post.Etag()) w.Write([]byte(post.ToJson())) } @@ -384,19 +384,19 @@ func deletePost(c *Context, w http.ResponseWriter, _ *http.Request) { post, err := c.App.GetSinglePost(c.Params.PostId) if err != nil { - c.SetPermissionError(model.PERMISSION_DELETE_POST) + c.SetPermissionError(model.PermissionDeletePost) return } auditRec.AddMeta("post", post) if c.AppContext.Session().UserId == post.UserId { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_DELETE_POST) { - c.SetPermissionError(model.PERMISSION_DELETE_POST) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionDeletePost) { + c.SetPermissionError(model.PermissionDeletePost) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_DELETE_OTHERS_POSTS) { - c.SetPermissionError(model.PERMISSION_DELETE_OTHERS_POSTS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionDeleteOthersPosts) { + c.SetPermissionError(model.PermissionDeleteOthersPosts) return } } @@ -436,14 +436,14 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { - if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if channel.Type == model.ChannelTypeOpen { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) { + c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + c.SetPermissionError(model.PermissionReadChannel) return } } @@ -454,7 +454,7 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { clientPostList := c.App.PreparePostListForClient(list) - w.Header().Set(model.HEADER_ETAG_SERVER, clientPostList.Etag()) + w.Header().Set(model.HeaderEtagServer, clientPostList.Etag()) w.Write([]byte(clientPostList.ToJson())) } @@ -465,8 +465,8 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -553,14 +553,14 @@ func updatePost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_EDIT_POST) { - c.SetPermissionError(model.PERMISSION_EDIT_POST) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionEditPost) { + c.SetPermissionError(model.PermissionEditPost) return } originalPost, err := c.App.GetSinglePost(c.Params.PostId) if err != nil { - c.SetPermissionError(model.PERMISSION_EDIT_POST) + c.SetPermissionError(model.PermissionEditPost) return } auditRec.AddMeta("post", originalPost) @@ -569,8 +569,8 @@ func updatePost(c *Context, w http.ResponseWriter, r *http.Request) { post.FileIds = originalPost.FileIds if c.AppContext.Session().UserId != originalPost.UserId { - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHERS_POSTS) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionEditOthersPosts) { + c.SetPermissionError(model.PermissionEditOthersPosts) return } } @@ -610,16 +610,16 @@ func patchPost(c *Context, w http.ResponseWriter, r *http.Request) { originalPost, err := c.App.GetSinglePost(c.Params.PostId) if err != nil { - c.SetPermissionError(model.PERMISSION_EDIT_POST) + c.SetPermissionError(model.PermissionEditPost) return } auditRec.AddMeta("post", originalPost) var permission *model.Permission if c.AppContext.Session().UserId == originalPost.UserId { - permission = model.PERMISSION_EDIT_POST + permission = model.PermissionEditPost } else { - permission = model.PERMISSION_EDIT_OTHERS_POSTS + permission = model.PermissionEditOthersPosts } if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, permission) { @@ -649,11 +649,11 @@ func setPostUnread(c *Context, w http.ResponseWriter, r *http.Request) { collapsedThreadsSupported := props["collapsed_threads_supported"] if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -674,8 +674,8 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, isPinned bool) { auditRec := c.MakeAuditRecord("saveIsPinnedPost", audit.Fail) defer c.LogAuditRecWithLevel(auditRec, app.LevelContent) - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -701,8 +701,8 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, isPinned bool) { if c.App.Srv().License() != nil && *c.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && - channel.Name == model.DEFAULT_CHANNEL && - !c.App.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { + channel.Name == model.DefaultChannelName && + !c.App.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) { c.Err = model.NewAppError("saveIsPinnedPost", "api.post.save_is_pinned_post.town_square_read_only", nil, "", http.StatusForbidden) return } @@ -735,8 +735,8 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -751,6 +751,6 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { } w.Header().Set("Cache-Control", "max-age=2592000, private") - w.Header().Set(model.HEADER_ETAG_SERVER, model.GetEtagForFileInfos(infos)) + w.Header().Set(model.HeaderEtagServer, model.GetEtagForFileInfos(infos)) w.Write([]byte(model.FileInfosToJson(infos))) } diff --git a/api4/post_test.go b/api4/post_test.go index 43e9d7d61a..fcd6b8e10e 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -34,7 +34,7 @@ func TestCreatePost(t *testing.T) { defer th.TearDown() Client := th.Client - post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a", Props: model.StringInterface{model.PROPS_ADD_CHANNEL_MEMBER: "no good"}} + post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a", Props: model.StringInterface{model.PropsAddChannelMember: "no good"}} rpost, resp := Client.CreatePost(post) CheckNoError(t, resp) CheckCreatedStatus(t, resp) @@ -43,7 +43,7 @@ func TestCreatePost(t *testing.T) { require.Equal(t, "#hashtag", rpost.Hashtags, "hashtag didn't match") require.Empty(t, rpost.FileIds) require.Equal(t, 0, int(rpost.EditAt), "newly created post shouldn't have EditAt set") - require.Nil(t, rpost.GetProp(model.PROPS_ADD_CHANNEL_MEMBER), "newly created post shouldn't have Props['add_channel_member'] set") + require.Nil(t, rpost.GetProp(model.PropsAddChannelMember), "newly created post shouldn't have Props['add_channel_member'] set") post.RootId = rpost.Id post.ParentId = rpost.Id @@ -124,7 +124,7 @@ func TestCreatePost(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) post.RootId = rpost.Id post.ParentId = rpost.Id @@ -138,7 +138,7 @@ func TestCreatePost(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - require.NotEqual(t, model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE, event.EventType(), "should not have ephemeral message event") + require.NotEqual(t, model.WebsocketEventEphemeralMessage, event.EventType(), "should not have ephemeral message event") case <-timeout: waiting = false } @@ -167,8 +167,8 @@ func TestCreatePost(t *testing.T) { for eventsToGo > 0 { select { case event := <-WebSocketClient.EventChannel: - if event.Event == model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE { - require.Equal(t, model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE, event.Event) + if event.Event == model.WebsocketEventEphemeralMessage { + require.Equal(t, model.WebsocketEventEphemeralMessage, event.Event) eventsToGo = eventsToGo - 1 } case <-timeout: @@ -180,7 +180,7 @@ func TestCreatePost(t *testing.T) { post.RootId = "" post.ParentId = "" - post.Type = model.POST_SYSTEM_GENERIC + post.Type = model.PostTypeSystemGeneric _, resp = Client.CreatePost(post) CheckBadRequestStatus(t, resp) @@ -222,7 +222,7 @@ func TestCreatePostEphemeral(t *testing.T) { ephemeralPost := &model.PostEphemeral{ UserID: th.BasicUser2.Id, - Post: &model.Post{ChannelId: th.BasicChannel.Id, Message: "a" + model.NewId() + "a", Props: model.StringInterface{model.PROPS_ADD_CHANNEL_MEMBER: "no good"}}, + Post: &model.Post{ChannelId: th.BasicChannel.Id, Message: "a" + model.NewId() + "a", Props: model.StringInterface{model.PropsAddChannelMember: "no good"}}, } rpost, resp := Client.CreatePostEphemeral(ephemeralPost) @@ -334,7 +334,7 @@ func testCreatePostWithOutgoingHook( respPostType := "" //if is empty or post will do a normal post. if commentPostType { - respPostType = model.OUTGOING_HOOK_RESPONSE_TYPE_COMMENT + respPostType = model.OutgoingHookResponseTypeComment } outGoingHookResponse := &model.OutgoingWebhookResponse{ @@ -437,7 +437,7 @@ func TestCreatePostPublic(t *testing.T) { post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"} - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemUserRoleId} ruser, resp := Client.CreateUser(&user) CheckNoError(t, resp) @@ -447,7 +447,7 @@ func TestCreatePostPublic(t *testing.T) { _, resp = Client.CreatePost(post) CheckForbiddenStatus(t, resp) - th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_PUBLIC_ROLE_ID, false) + th.App.UpdateUserRoles(ruser.Id, model.SystemUserRoleId+" "+model.SystemPostAllPublicRoleId, false) th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -459,9 +459,9 @@ func TestCreatePostPublic(t *testing.T) { _, resp = Client.CreatePost(post) CheckForbiddenStatus(t, resp) - th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) + th.App.UpdateUserRoles(ruser.Id, model.SystemUserRoleId, false) th.App.JoinUserToTeam(th.Context, th.BasicTeam, ruser, "") - th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID) + th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TeamUserRoleId+" "+model.TeamPostAllPublicRoleId) th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -482,7 +482,7 @@ func TestCreatePostAll(t *testing.T) { post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"} - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemUserRoleId} directChannel, _ := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) @@ -494,7 +494,7 @@ func TestCreatePostAll(t *testing.T) { _, resp = Client.CreatePost(post) CheckForbiddenStatus(t, resp) - th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_ROLE_ID, false) + th.App.UpdateUserRoles(ruser.Id, model.SystemUserRoleId+" "+model.SystemPostAllRoleId, false) th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -510,9 +510,9 @@ func TestCreatePostAll(t *testing.T) { _, resp = Client.CreatePost(post) CheckNoError(t, resp) - th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) + th.App.UpdateUserRoles(ruser.Id, model.SystemUserRoleId, false) th.App.JoinUserToTeam(th.Context, th.BasicTeam, ruser, "") - th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID) + th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TeamUserRoleId+" "+model.TeamPostAllRoleId) th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -553,7 +553,7 @@ func TestCreatePostSendOutOfChannelMentions(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - require.NotEqual(t, model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE, event.EventType(), "should not have ephemeral message event") + require.NotEqual(t, model.WebsocketEventEphemeralMessage, event.EventType(), "should not have ephemeral message event") case <-timeout: waiting = false } @@ -572,14 +572,14 @@ func TestCreatePostSendOutOfChannelMentions(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - if event.EventType() != model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE { + if event.EventType() != model.WebsocketEventEphemeralMessage { // Ignore any other events continue } wpost := model.PostFromJson(strings.NewReader(event.GetData()["post"].(string))) - acm, ok := wpost.GetProp(model.PROPS_ADD_CHANNEL_MEMBER).(map[string]interface{}) + acm, ok := wpost.GetProp(model.PropsAddChannelMember).(map[string]interface{}) require.True(t, ok, "should have received ephemeral post with 'add_channel_member' in props") require.True(t, acm["post_id"] != nil, "should not be nil") require.True(t, acm["user_ids"] != nil, "should not be nil") @@ -613,7 +613,7 @@ func TestCreatePostCheckOnlineStatus(t *testing.T) { for { select { case ev := <-wsClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_POSTED { + if ev.EventType() == model.WebsocketEventPosted { assert.True(t, ev.GetData()["set_online"].(bool) == isSetOnline) return } @@ -634,7 +634,7 @@ func TestCreatePostCheckOnlineStatus(t *testing.T) { } req := httptest.NewRequest("POST", "/api/v4/posts?set_online=false", strings.NewReader(post.ToJson())) - req.Header.Set(model.HEADER_AUTH, "Bearer "+session.Token) + req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusCreated, resp.Code) @@ -645,7 +645,7 @@ func TestCreatePostCheckOnlineStatus(t *testing.T) { assert.Equal(t, "app.status.get.missing.app_error", err.Id) req = httptest.NewRequest("POST", "/api/v4/posts", strings.NewReader(post.ToJson())) - req.Header.Set(model.HEADER_AUTH, "Bearer "+session.Token) + req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusCreated, resp.Code) @@ -712,27 +712,27 @@ func TestUpdatePost(t *testing.T) { t.Run("new message, invalid props", func(t *testing.T) { msg1 := "#hashtag a" + model.NewId() + " update post again" rpost.Message = msg1 - rpost.AddProp(model.PROPS_ADD_CHANNEL_MEMBER, "no good") + rpost.AddProp(model.PropsAddChannelMember, "no good") rrupost, resp := Client.UpdatePost(rpost.Id, rpost) CheckNoError(t, resp) assert.Equal(t, msg1, rrupost.Message, "failed to update message") assert.Equal(t, "#hashtag", rrupost.Hashtags, "failed to update hashtags") - assert.Nil(t, rrupost.GetProp(model.PROPS_ADD_CHANNEL_MEMBER), "failed to sanitize Props['add_channel_member'], should be nil") + assert.Nil(t, rrupost.GetProp(model.PropsAddChannelMember), "failed to sanitize Props['add_channel_member'], should be nil") actual, resp := Client.GetPost(rpost.Id, "") CheckNoError(t, resp) assert.Equal(t, msg1, actual.Message, "failed to update message") assert.Equal(t, "#hashtag", actual.Hashtags, "failed to update hashtags") - assert.Nil(t, actual.GetProp(model.PROPS_ADD_CHANNEL_MEMBER), "failed to sanitize Props['add_channel_member'], should be nil") + assert.Nil(t, actual.GetProp(model.PropsAddChannelMember), "failed to sanitize Props['add_channel_member'], should be nil") }) t.Run("join/leave post", func(t *testing.T) { rpost2, err := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", - Type: model.POST_JOIN_LEAVE, + Type: model.PostTypeJoinLeave, UserId: th.BasicUser.Id, }, channel, false, true) require.Nil(t, err) @@ -955,8 +955,8 @@ func TestPatchPost(t *testing.T) { // Add permission to edit others' defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.RemovePermissionFromRole(model.PERMISSION_EDIT_POST.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_EDIT_OTHERS_POSTS.Id, model.CHANNEL_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionEditPost.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionEditOthersPosts.Id, model.ChannelUserRoleId) _, resp = Client.PatchPost(post.Id, patch) CheckNoError(t, resp) @@ -1203,7 +1203,7 @@ func TestGetFlaggedPostsForUser(t *testing.T) { preference := model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: post1.Id, Value: "true", } @@ -1293,7 +1293,7 @@ func TestGetFlaggedPostsForUser(t *testing.T) { CheckNoError(t, resp) require.Empty(t, rpl.Posts) - channel4 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) + channel4 := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) post5 := th.CreatePostWithClient(th.SystemAdminClient, channel4) preference.Name = post5.Id @@ -2031,7 +2031,7 @@ func TestDeletePostMessage(t *testing.T) { for { select { case ev := <-wsClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_POST_DELETED { + if ev.EventType() == model.WebsocketEventPostDeleted { assert.Equal(t, tc.delete_by, ev.GetData()["delete_by"]) return } @@ -2554,7 +2554,7 @@ func TestSetPostUnreadWithoutCollapsedThreads(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) // user2: first root mention @user1 diff --git a/api4/preference.go b/api4/preference.go index 82f9ad2241..b29991283e 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -25,7 +25,7 @@ func getPreferences(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -45,7 +45,7 @@ func getPreferencesByCategory(c *Context, w http.ResponseWriter, r *http.Request } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -65,7 +65,7 @@ func getPreferenceByCategoryAndName(c *Context, w http.ResponseWriter, r *http.R } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -88,7 +88,7 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -101,15 +101,15 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { var sanitizedPreferences model.Preferences for _, pref := range preferences { - if pref.Category == model.PREFERENCE_CATEGORY_FLAGGED_POST { + if pref.Category == model.PreferenceCategoryFlaggedPost { post, err := c.App.GetSinglePost(pref.Name) if err != nil { c.SetInvalidParam("preference.name") return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } @@ -136,7 +136,7 @@ func deletePreferences(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } diff --git a/api4/preference_test.go b/api4/preference_test.go index 8a6b625664..36015cb0a5 100644 --- a/api4/preference_test.go +++ b/api4/preference_test.go @@ -139,13 +139,13 @@ func TestGetPreferenceByCategoryAndName(t *testing.T) { preferences := model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: name, Value: value, }, { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: model.NewId(), Value: model.NewId(), }, @@ -153,7 +153,7 @@ func TestGetPreferenceByCategoryAndName(t *testing.T) { Client.UpdatePreferences(user.Id, &preferences) - pref, resp := Client.GetPreferenceByCategoryAndName(user.Id, model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, name) + pref, resp := Client.GetPreferenceByCategoryAndName(user.Id, model.PreferenceCategoryDirectChannelShow, name) CheckNoError(t, resp) require.Equal(t, preferences[0].UserId, pref.UserId, "UserId preference not saved") @@ -250,7 +250,7 @@ func TestUpdatePreferencesWebsocket(t *testing.T) { WebSocketClient.Listen() time.Sleep(300 * time.Millisecond) wsResp := <-WebSocketClient.ResponseChannel - require.Equal(t, wsResp.Status, model.STATUS_OK, "expected OK from auth challenge") + require.Equal(t, wsResp.Status, model.StatusOk, "expected OK from auth challenge") userId := th.BasicUser.Id preferences := &model.Preferences{ @@ -275,7 +275,7 @@ func TestUpdatePreferencesWebsocket(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - if event.EventType() != model.WEBSOCKET_EVENT_PREFERENCES_CHANGED { + if event.EventType() != model.WebsocketEventPreferencesChanged { // Ignore any other events continue } @@ -309,7 +309,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "") require.Nil(t, resp.Error) - channel := th.CreateChannelWithClientAndTeam(th.Client, model.CHANNEL_OPEN, team1.Id) + channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id) th.AddUserToChannel(user, channel) // Confirm that the sidebar is populated correctly to begin with @@ -324,7 +324,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -343,7 +343,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "false", }, @@ -377,7 +377,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp := th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: dmChannel.Id, Value: "true", }, @@ -403,7 +403,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: dmChannel.Id, Value: "false", }, @@ -445,7 +445,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "") require.Nil(t, resp.Error) - channel := th.CreateChannelWithClientAndTeam(th.Client, model.CHANNEL_OPEN, team1.Id) + channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id) th.AddUserToChannel(user, channel) th.AddUserToChannel(user2, channel) @@ -468,7 +468,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -487,7 +487,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = client2.UpdatePreferences(user2.Id, &model.Preferences{ { UserId: user2.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -506,7 +506,7 @@ func TestUpdateSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "false", }, @@ -538,7 +538,7 @@ func TestDeletePreferences(t *testing.T) { for i := 0; i < 10; i++ { preference := model.Preference{ UserId: th.BasicUser.Id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: model.NewId(), } preferences = append(preferences, preference) @@ -593,7 +593,7 @@ func TestDeletePreferencesWebsocket(t *testing.T) { WebSocketClient.Listen() wsResp := <-WebSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, wsResp.Status, "should have responded OK to authentication challenge") + require.Equal(t, model.StatusOk, wsResp.Status, "should have responded OK to authentication challenge") _, resp = th.Client.DeletePreferences(userId, preferences) CheckNoError(t, resp) @@ -604,7 +604,7 @@ func TestDeletePreferencesWebsocket(t *testing.T) { for waiting { select { case event := <-WebSocketClient.EventChannel: - if event.EventType() != model.WEBSOCKET_EVENT_PREFERENCES_DELETED { + if event.EventType() != model.WebsocketEventPreferencesDeleted { // Ignore any other events continue } @@ -638,7 +638,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "") require.Nil(t, resp.Error) - channel := th.CreateChannelWithClientAndTeam(th.Client, model.CHANNEL_OPEN, team1.Id) + channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id) th.AddUserToChannel(user, channel) // Confirm that the sidebar is populated correctly to begin with @@ -653,7 +653,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -672,7 +672,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = th.Client.DeletePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, }, }) @@ -705,7 +705,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp := th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: dmChannel.Id, Value: "true", }, @@ -731,7 +731,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = th.Client.DeletePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: dmChannel.Id, }, }) @@ -772,7 +772,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "") require.Nil(t, resp.Error) - channel := th.CreateChannelWithClientAndTeam(th.Client, model.CHANNEL_OPEN, team1.Id) + channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id) th.AddUserToChannel(user, channel) th.AddUserToChannel(user2, channel) @@ -795,7 +795,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -805,7 +805,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = client2.UpdatePreferences(user2.Id, &model.Preferences{ { UserId: user2.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }, @@ -824,7 +824,7 @@ func TestDeleteSidebarPreferences(t *testing.T) { _, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{ { UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "false", }, diff --git a/api4/reaction.go b/api4/reaction.go index e852897929..83a02ca3ce 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -23,7 +23,7 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || reaction.EmojiName == "" || len(reaction.EmojiName) > model.EMOJI_NAME_MAX_LENGTH { + if !model.IsValidId(reaction.UserId) || !model.IsValidId(reaction.PostId) || reaction.EmojiName == "" || len(reaction.EmojiName) > model.EmojiNameMaxLength { c.Err = model.NewAppError("saveReaction", "api.reaction.save_reaction.invalid.app_error", nil, "", http.StatusBadRequest) return } @@ -33,8 +33,8 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), reaction.PostId, model.PERMISSION_ADD_REACTION) { - c.SetPermissionError(model.PERMISSION_ADD_REACTION) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), reaction.PostId, model.PermissionAddReaction) { + c.SetPermissionError(model.PermissionAddReaction) return } @@ -53,8 +53,8 @@ func getReactions(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } @@ -83,13 +83,13 @@ func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_REMOVE_REACTION) { - c.SetPermissionError(model.PERMISSION_REMOVE_REACTION) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PermissionRemoveReaction) { + c.SetPermissionError(model.PermissionRemoveReaction) return } - if c.Params.UserId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_OTHERS_REACTIONS) { - c.SetPermissionError(model.PERMISSION_REMOVE_OTHERS_REACTIONS) + if c.Params.UserId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveOthersReactions) { + c.SetPermissionError(model.PermissionRemoveOthersReactions) return } @@ -111,8 +111,8 @@ func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) { func getBulkReactions(c *Context, w http.ResponseWriter, r *http.Request) { postIds := model.ArrayFromJson(r.Body) for _, postId := range postIds { - if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), postId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), postId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } diff --git a/api4/reaction_test.go b/api4/reaction_test.go index 52a2250173..211e990dbc 100644 --- a/api4/reaction_test.go +++ b/api4/reaction_test.go @@ -145,14 +145,14 @@ func TestSaveReaction(t *testing.T) { t.Run("unable-to-create-reaction-without-permissions", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_ADD_REACTION.Id, model.CHANNEL_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionAddReaction.Id, model.ChannelUserRoleId) _, resp := Client.SaveReaction(reaction) CheckForbiddenStatus(t, resp) reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 3, len(reactions), "should have not created a reactions") - th.AddPermissionToRole(model.PERMISSION_ADD_REACTION.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionAddReaction.Id, model.ChannelUserRoleId) }) t.Run("unable-to-react-in-read-only-town-square", func(t *testing.T) { @@ -455,7 +455,7 @@ func TestDeleteReaction(t *testing.T) { t.Run("unable-to-delete-reaction-without-permissions", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_REMOVE_REACTION.Id, model.CHANNEL_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionRemoveReaction.Id, model.ChannelUserRoleId) th.App.SaveReactionForPost(th.Context, r1) _, resp := Client.DeleteReaction(r1) @@ -464,11 +464,11 @@ func TestDeleteReaction(t *testing.T) { reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 1, len(reactions), "should have not deleted a reactions") - th.AddPermissionToRole(model.PERMISSION_REMOVE_REACTION.Id, model.CHANNEL_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionRemoveReaction.Id, model.ChannelUserRoleId) }) t.Run("unable-to-delete-others-reactions-without-permissions", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id, model.SYSTEM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionRemoveOthersReactions.Id, model.SystemAdminRoleId) th.App.SaveReactionForPost(th.Context, r1) _, resp := th.SystemAdminClient.DeleteReaction(r1) @@ -477,7 +477,7 @@ func TestDeleteReaction(t *testing.T) { reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 1, len(reactions), "should have not deleted a reactions") - th.AddPermissionToRole(model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id, model.SYSTEM_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionRemoveOthersReactions.Id, model.SystemAdminRoleId) }) t.Run("unable-to-delete-reactions-in-read-only-town-square", func(t *testing.T) { diff --git a/api4/role.go b/api4/role.go index 5c1eba832b..06a0929817 100644 --- a/api4/role.go +++ b/api4/role.go @@ -11,21 +11,21 @@ import ( ) var allowedPermissions = []string{ - model.PERMISSION_CREATE_TEAM.Id, - model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_OAUTH.Id, - model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH.Id, - model.PERMISSION_CREATE_EMOJIS.Id, - model.PERMISSION_DELETE_EMOJIS.Id, - model.PERMISSION_EDIT_OTHERS_POSTS.Id, + model.PermissionCreateTeam.Id, + model.PermissionManageIncomingWebhooks.Id, + model.PermissionManageOutgoingWebhooks.Id, + model.PermissionManageSlashCommands.Id, + model.PermissionManageOAuth.Id, + model.PermissionManageSystemWideOAuth.Id, + model.PermissionCreateEmojis.Id, + model.PermissionDeleteEmojis.Id, + model.PermissionEditOthersPosts.Id, } var notAllowedPermissions = []string{ - model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES.Id, - model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES.Id, - model.PERMISSION_MANAGE_ROLES.Id, + model.PermissionSysconsoleWriteUserManagementSystemRoles.Id, + model.PermissionSysconsoleReadUserManagementSystemRoles.Id, + model.PermissionManageRoles.Id, } func (api *API) InitRole() { @@ -111,11 +111,11 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("role", oldRole) // manage_system permission is required to patch system_admin - requiredPermission := model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS - specialProtectedSystemRoles := append(model.NewSystemRoleIDs, model.SYSTEM_ADMIN_ROLE_ID) + requiredPermission := model.PermissionSysconsoleWriteUserManagementPermissions + specialProtectedSystemRoles := append(model.NewSystemRoleIDs, model.SystemAdminRoleId) for _, roleID := range specialProtectedSystemRoles { if oldRole.Name == roleID { - requiredPermission = model.PERMISSION_MANAGE_SYSTEM + requiredPermission = model.PermissionManageSystem } } if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), requiredPermission) { @@ -123,7 +123,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { return } - isGuest := oldRole.Name == model.SYSTEM_GUEST_ROLE_ID || oldRole.Name == model.TEAM_GUEST_ROLE_ID || oldRole.Name == model.CHANNEL_GUEST_ROLE_ID + isGuest := oldRole.Name == model.SystemGuestRoleId || oldRole.Name == model.TeamGuestRoleId || oldRole.Name == model.ChannelGuestRoleId if c.App.Srv().License() == nil && patch.Permissions != nil { if isGuest { c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented) @@ -171,14 +171,14 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { return } - if oldRole.Name == model.TEAM_ADMIN_ROLE_ID || oldRole.Name == model.CHANNEL_ADMIN_ROLE_ID || oldRole.Name == model.SYSTEM_USER_ROLE_ID || oldRole.Name == model.TEAM_USER_ROLE_ID || oldRole.Name == model.CHANNEL_USER_ROLE_ID || oldRole.Name == model.SYSTEM_GUEST_ROLE_ID || oldRole.Name == model.TEAM_GUEST_ROLE_ID || oldRole.Name == model.CHANNEL_GUEST_ROLE_ID { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) + if oldRole.Name == model.TeamAdminRoleId || oldRole.Name == model.ChannelAdminRoleId || oldRole.Name == model.SystemUserRoleId || oldRole.Name == model.TeamUserRoleId || oldRole.Name == model.ChannelUserRoleId || oldRole.Name == model.SystemGuestRoleId || oldRole.Name == model.TeamGuestRoleId || oldRole.Name == model.ChannelGuestRoleId { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementPermissions) return } } else { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementSystemRoles) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementSystemRoles) return } } diff --git a/api4/role_test.go b/api4/role_test.go index 1b275013a6..b1c4e417c6 100644 --- a/api4/role_test.go +++ b/api4/role_test.go @@ -194,21 +194,21 @@ func TestPatchRole(t *testing.T) { defer th.App.Srv().Store.Job().Delete(systemManager.Id) patchWriteSystemRoles := &model.RolePatch{ - Permissions: &[]string{model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES.Id}, + Permissions: &[]string{model.PermissionSysconsoleWriteUserManagementSystemRoles.Id}, } _, resp = client.PatchRole(systemManager.Id, patchWriteSystemRoles) CheckNotImplementedStatus(t, resp) patchReadSystemRoles := &model.RolePatch{ - Permissions: &[]string{model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES.Id}, + Permissions: &[]string{model.PermissionSysconsoleReadUserManagementSystemRoles.Id}, } _, resp = client.PatchRole(systemManager.Id, patchReadSystemRoles) CheckNotImplementedStatus(t, resp) patchManageRoles := &model.RolePatch{ - Permissions: &[]string{model.PERMISSION_MANAGE_ROLES.Id}, + Permissions: &[]string{model.PermissionManageRoles.Id}, } _, resp = client.PatchRole(systemManager.Id, patchManageRoles) diff --git a/api4/saml.go b/api4/saml.go index 0cd98c6bdb..13003dbb80 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -69,8 +69,8 @@ func parseSamlCertificateRequest(r *http.Request, maxFileSize int64) (*multipart } func addSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_PUBLIC_CERT) { - c.SetPermissionError(model.PERMISSION_ADD_SAML_PUBLIC_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionAddSamlPublicCert) { + c.SetPermissionError(model.PermissionAddSamlPublicCert) return } @@ -93,8 +93,8 @@ func addSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request } func addSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_PRIVATE_CERT) { - c.SetPermissionError(model.PERMISSION_ADD_SAML_PRIVATE_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionAddSamlPrivateCert) { + c.SetPermissionError(model.PermissionAddSamlPrivateCert) return } @@ -117,8 +117,8 @@ func addSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Reques } func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_IDP_CERT) { - c.SetPermissionError(model.PERMISSION_ADD_SAML_IDP_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionAddSamlIdpCert) { + c.SetPermissionError(model.PermissionAddSamlIdpCert) return } @@ -170,8 +170,8 @@ func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { } func removeSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_PUBLIC_CERT) { - c.SetPermissionError(model.PERMISSION_REMOVE_SAML_PUBLIC_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveSamlPublicCert) { + c.SetPermissionError(model.PermissionRemoveSamlPublicCert) return } @@ -188,8 +188,8 @@ func removeSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Requ } func removeSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_PRIVATE_CERT) { - c.SetPermissionError(model.PERMISSION_REMOVE_SAML_PRIVATE_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveSamlPrivateCert) { + c.SetPermissionError(model.PermissionRemoveSamlPrivateCert) return } @@ -206,8 +206,8 @@ func removeSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Req } func removeSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_IDP_CERT) { - c.SetPermissionError(model.PERMISSION_REMOVE_SAML_IDP_CERT) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRemoveSamlIdpCert) { + c.SetPermissionError(model.PermissionRemoveSamlIdpCert) return } @@ -224,8 +224,8 @@ func removeSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request } func getSamlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_SAML_CERT_STATUS) { - c.SetPermissionError(model.PERMISSION_GET_SAML_CERT_STATUS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionGetSamlCertStatus) { + c.SetPermissionError(model.PermissionGetSamlCertStatus) return } @@ -234,8 +234,8 @@ func getSamlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request } func getSamlMetadataFromIdp(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_SAML_METADATA_FROM_IDP) { - c.SetPermissionError(model.PERMISSION_GET_SAML_METADATA_FROM_IDP) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionGetSamlMetadataFromIdp) { + c.SetPermissionError(model.PermissionGetSamlMetadataFromIdp) return } @@ -256,8 +256,8 @@ func getSamlMetadataFromIdp(c *Context, w http.ResponseWriter, r *http.Request) } func resetAuthDataToEmail(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } type ResetAuthDataParams struct { diff --git a/api4/saml_test.go b/api4/saml_test.go index 67224c0b9a..09e32c80c3 100644 --- a/api4/saml_test.go +++ b/api4/saml_test.go @@ -35,11 +35,11 @@ func TestSamlCompleteCSRFPass(t *testing.T) { } cookie1 := &http.Cookie{ - Name: model.SESSION_COOKIE_USER, + Name: model.SessionCookieUser, Value: th.BasicUser.Username, } cookie2 := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: th.Client.AuthToken, } req.AddCookie(cookie1) @@ -60,7 +60,7 @@ func TestSamlResetId(t *testing.T) { user := th.BasicUser _, appErr := th.App.UpdateUserAuth(user.Id, &model.UserAuth{ AuthData: model.NewString(model.NewId()), - AuthService: model.USER_AUTH_SERVICE_SAML, + AuthService: model.UserAuthServiceSaml, }) require.Nil(t, appErr) diff --git a/api4/scheme.go b/api4/scheme.go index 9bbaa2c079..041c979e63 100644 --- a/api4/scheme.go +++ b/api4/scheme.go @@ -36,8 +36,8 @@ func createScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementPermissions) return } @@ -60,8 +60,8 @@ func getScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementPermissions) return } @@ -75,13 +75,13 @@ func getScheme(c *Context, w http.ResponseWriter, r *http.Request) { } func getSchemes(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementPermissions) return } scope := c.Params.Scope - if scope != "" && scope != model.SCHEME_SCOPE_TEAM && scope != model.SCHEME_SCOPE_CHANNEL { + if scope != "" && scope != model.SchemeScopeTeam && scope != model.SchemeScopeChannel { c.SetInvalidParam("scope") return } @@ -101,8 +101,8 @@ func getTeamsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementTeams) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementTeams) return } @@ -112,7 +112,7 @@ func getTeamsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if scheme.Scope != model.SCHEME_SCOPE_TEAM { + if scheme.Scope != model.SchemeScopeTeam { c.Err = model.NewAppError("Api4.GetTeamsForScheme", "api.scheme.get_teams_for_scheme.scope.error", nil, "", http.StatusBadRequest) return } @@ -132,8 +132,8 @@ func getChannelsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementChannels) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementChannels) return } @@ -143,7 +143,7 @@ func getChannelsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if scheme.Scope != model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope != model.SchemeScopeChannel { c.Err = model.NewAppError("Api4.GetChannelsForScheme", "api.scheme.get_channels_for_scheme.scope.error", nil, "", http.StatusBadRequest) return } @@ -184,8 +184,8 @@ func patchScheme(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("scheme", scheme) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementPermissions) return } @@ -216,8 +216,8 @@ func deleteScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementPermissions) return } diff --git a/api4/scheme_test.go b/api4/scheme_test.go index 2c25791d29..41ff16ed13 100644 --- a/api4/scheme_test.go +++ b/api4/scheme_test.go @@ -27,7 +27,7 @@ func TestCreateScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, r1 := th.SystemAdminClient.CreateScheme(scheme1) @@ -66,7 +66,7 @@ func TestCreateScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s2, r2 := th.SystemAdminClient.CreateScheme(scheme2) @@ -130,7 +130,7 @@ func TestCreateScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } _, r5 := th.Client.CreateScheme(scheme5) CheckForbiddenStatus(t, r5) @@ -141,7 +141,7 @@ func TestCreateScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } _, r6 := th.SystemAdminClient.CreateScheme(scheme6) CheckNotImplementedStatus(t, r6) @@ -155,7 +155,7 @@ func TestCreateScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } _, r7 := th.SystemAdminClient.CreateScheme(scheme7) CheckNotImplementedStatus(t, r7) @@ -172,7 +172,7 @@ func TestGetScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } th.App.SetPhase2PermissionsMigrationStatus(true) @@ -233,14 +233,14 @@ func TestGetSchemes(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } scheme2 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } th.App.SetPhase2PermissionsMigrationStatus(true) @@ -298,7 +298,7 @@ func TestGetTeamsForScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } scheme1, r1 := th.SystemAdminClient.CreateScheme(scheme1) CheckNoError(t, r1) @@ -306,7 +306,7 @@ func TestGetTeamsForScheme(t *testing.T) { team1 := &model.Team{ Name: GenerateTestUsername(), DisplayName: "A Test Team", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team1, err := th.App.Srv().Store.Team().Save(team1) @@ -328,7 +328,7 @@ func TestGetTeamsForScheme(t *testing.T) { team2 := &model.Team{ Name: GenerateTestUsername(), DisplayName: "B Test Team", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &scheme1.Id, } team2, err = th.App.Srv().Store.Team().Save(team2) @@ -364,7 +364,7 @@ func TestGetTeamsForScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } scheme2, rs2 := th.SystemAdminClient.CreateScheme(scheme2) CheckNoError(t, rs2) @@ -390,7 +390,7 @@ func TestGetChannelsForScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } scheme1, r1 := th.SystemAdminClient.CreateScheme(scheme1) CheckNoError(t, r1) @@ -399,7 +399,7 @@ func TestGetChannelsForScheme(t *testing.T) { TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel1, errCh := th.App.Srv().Store.Channel().Save(channel1, 1000000) @@ -422,7 +422,7 @@ func TestGetChannelsForScheme(t *testing.T) { TeamId: model.NewId(), DisplayName: "B Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &scheme1.Id, } channel2, nErr := th.App.Srv().Store.Channel().Save(channel2, 1000000) @@ -458,7 +458,7 @@ func TestGetChannelsForScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } scheme2, rs2 := th.SystemAdminClient.CreateScheme(scheme2) CheckNoError(t, rs2) @@ -485,7 +485,7 @@ func TestPatchScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, r1 := th.SystemAdminClient.CreateScheme(scheme1) @@ -593,7 +593,7 @@ func TestDeleteScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, r1 := th.SystemAdminClient.CreateScheme(scheme1) @@ -625,7 +625,7 @@ func TestDeleteScheme(t *testing.T) { Name: "zz" + model.NewId(), DisplayName: model.NewId(), Email: model.NewId() + "@nowhere.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, }) require.NoError(t, err) @@ -671,7 +671,7 @@ func TestDeleteScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s1, r1 := th.SystemAdminClient.CreateScheme(scheme1) @@ -694,7 +694,7 @@ func TestDeleteScheme(t *testing.T) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1.Id, }, -1) assert.NoError(t, err) @@ -730,7 +730,7 @@ func TestDeleteScheme(t *testing.T) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s1, r1 := th.SystemAdminClient.CreateScheme(scheme1) @@ -783,14 +783,14 @@ func TestUpdateTeamSchemeWithTeamMembers(t *testing.T) { th.LoginBasic() - _, resp := th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}) + _, resp := th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id}) require.Nil(t, resp.Error) team.SchemeId = &teamScheme.Id team, err = th.App.UpdateTeamScheme(team) require.Nil(t, err) - _, resp = th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.CHANNEL_OPEN, TeamId: team.Id}) + _, resp = th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id}) require.NotNil(t, resp.Error) }) } diff --git a/api4/shared_channel_test.go b/api4/shared_channel_test.go index 36d48f8368..0a590e39a1 100644 --- a/api4/shared_channel_test.go +++ b/api4/shared_channel_test.go @@ -35,7 +35,7 @@ func TestGetAllSharedChannels(t *testing.T) { // make some shared channels for i := 0; i < pages*pageSize; i++ { - channel := th.CreateChannelWithClientAndTeam(th.Client, model.CHANNEL_OPEN, th.BasicTeam.Id) + channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, th.BasicTeam.Id) sc := &model.SharedChannel{ ChannelId: channel.Id, TeamId: channel.TeamId, diff --git a/api4/status.go b/api4/status.go index c2240d47c1..d4172f2f58 100644 --- a/api4/status.go +++ b/api4/status.go @@ -89,12 +89,12 @@ func updateUserStatus(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } currentStatus, err := c.App.GetStatus(c.Params.UserId) - if err == nil && currentStatus.Status == model.STATUS_OUT_OF_OFFICE && status.Status != model.STATUS_OUT_OF_OFFICE { + if err == nil && currentStatus.Status == model.StatusOutOfOffice && status.Status != model.StatusOutOfOffice { c.App.DisableAutoResponder(c.Params.UserId, c.IsSystemAdmin()) } @@ -137,7 +137,7 @@ func updateUserCustomStatus(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -163,7 +163,7 @@ func removeUserCustomStatus(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -193,7 +193,7 @@ func removeUserRecentCustomStatus(c *Context, w http.ResponseWriter, r *http.Req } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } diff --git a/api4/system.go b/api4/system.go index 4108ccc290..3dbd2c8f91 100644 --- a/api4/system.go +++ b/api4/system.go @@ -126,7 +126,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { reqs := c.App.Config().ClientRequirements s := make(map[string]string) - s[model.STATUS] = model.STATUS_OK + s[model.STATUS] = model.StatusOk s["AndroidLatestVersion"] = reqs.AndroidLatestVersion s["AndroidMinVersion"] = reqs.AndroidMinVersion s["DesktopLatestVersion"] = reqs.DesktopLatestVersion @@ -142,7 +142,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { actualGoroutines := runtime.NumGoroutine() if *c.App.Config().ServiceSettings.GoroutineHealthThreshold > 0 && actualGoroutines >= *c.App.Config().ServiceSettings.GoroutineHealthThreshold { mlog.Warn("The number of running goroutines is over the health threshold", mlog.Int("goroutines", actualGoroutines), mlog.Int("health_threshold", *c.App.Config().ServiceSettings.GoroutineHealthThreshold)) - s[model.STATUS] = model.STATUS_UNHEALTHY + s[model.STATUS] = model.StatusUnhealthy } // Enhanced ping health check: @@ -150,32 +150,32 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { // database and file storage backends. if r.FormValue("get_server_status") != "" { dbStatusKey := "database_status" - s[dbStatusKey] = model.STATUS_OK + s[dbStatusKey] = model.StatusOk writeErr := c.App.DBHealthCheckWrite() if writeErr != nil { mlog.Warn("Unable to write to database.", mlog.Err(writeErr)) - s[dbStatusKey] = model.STATUS_UNHEALTHY - s[model.STATUS] = model.STATUS_UNHEALTHY + s[dbStatusKey] = model.StatusUnhealthy + s[model.STATUS] = model.StatusUnhealthy } writeErr = c.App.DBHealthCheckDelete() if writeErr != nil { mlog.Warn("Unable to remove ping health check value from database.", mlog.Err(writeErr)) - s[dbStatusKey] = model.STATUS_UNHEALTHY - s[model.STATUS] = model.STATUS_UNHEALTHY + s[dbStatusKey] = model.StatusUnhealthy + s[model.STATUS] = model.StatusUnhealthy } - if s[dbStatusKey] == model.STATUS_OK { + if s[dbStatusKey] == model.StatusOk { mlog.Debug("Able to write to database.") } filestoreStatusKey := "filestore_status" - s[filestoreStatusKey] = model.STATUS_OK + s[filestoreStatusKey] = model.StatusOk appErr := c.App.TestFileStoreConnection() if appErr != nil { - s[filestoreStatusKey] = model.STATUS_UNHEALTHY - s[model.STATUS] = model.STATUS_UNHEALTHY + s[filestoreStatusKey] = model.StatusUnhealthy + s[model.STATUS] = model.StatusUnhealthy } w.Header().Set(model.STATUS, s[model.STATUS]) @@ -183,7 +183,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set(filestoreStatusKey, s[filestoreStatusKey]) } - if s[model.STATUS] != model.STATUS_OK { + if s[model.STATUS] != model.StatusOk { w.WriteHeader(http.StatusInternalServerError) } w.Write([]byte(model.MapToJson(s))) @@ -195,8 +195,8 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_EMAIL) { - c.SetPermissionError(model.PERMISSION_TEST_EMAIL) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestEmail) { + c.SetPermissionError(model.PermissionTestEmail) return } @@ -215,8 +215,8 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { } func testSiteURL(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_SITE_URL) { - c.SetPermissionError(model.PERMISSION_TEST_SITE_URL) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestSiteUrl) { + c.SetPermissionError(model.PermissionTestSiteUrl) return } @@ -245,8 +245,8 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("getAudits", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_AUDITS) { - c.SetPermissionError(model.PERMISSION_READ_AUDITS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadAudits) { + c.SetPermissionError(model.PermissionReadAudits) return } @@ -264,8 +264,8 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { } func databaseRecycle(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS) { - c.SetPermissionError(model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRecycleDatabaseConnections) { + c.SetPermissionError(model.PermissionRecycleDatabaseConnections) return } @@ -284,8 +284,8 @@ func databaseRecycle(c *Context, w http.ResponseWriter, r *http.Request) { } func invalidateCaches(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_INVALIDATE_CACHES) { - c.SetPermissionError(model.PERMISSION_INVALIDATE_CACHES) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionInvalidateCaches) { + c.SetPermissionError(model.PermissionInvalidateCaches) return } @@ -318,8 +318,8 @@ func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_LOGS) { - c.SetPermissionError(model.PERMISSION_GET_LOGS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionGetLogs) { + c.SetPermissionError(model.PermissionGetLogs) return } @@ -344,7 +344,7 @@ func postLog(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { forceToDebug = true } } @@ -381,8 +381,8 @@ func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { name = "standard" } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_ANALYTICS) { - c.SetPermissionError(model.PERMISSION_GET_ANALYTICS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionGetAnalytics) { + c.SetPermissionError(model.PermissionGetAnalytics) return } @@ -421,8 +421,8 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_S3) { - c.SetPermissionError(model.PERMISSION_TEST_S3) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionTestS3) { + c.SetPermissionError(model.PermissionTestS3) return } @@ -437,7 +437,7 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) { return } - if *cfg.FileSettings.AmazonS3SecretAccessKey == model.FAKE_SETTING { + if *cfg.FileSettings.AmazonS3SecretAccessKey == model.FakeSetting { cfg.FileSettings.AmazonS3SecretAccessKey = c.App.Config().FileSettings.AmazonS3SecretAccessKey } @@ -551,8 +551,8 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { } func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -580,8 +580,8 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { } func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -596,8 +596,8 @@ func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { } func getServerBusyExpires(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } w.Write([]byte(c.App.Srv().Busy.ToJson())) @@ -607,8 +607,8 @@ func upgradeToEnterprise(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("upgradeToEnterprise", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -663,8 +663,8 @@ func upgradeToEnterprise(c *Context, w http.ResponseWriter, r *http.Request) { } func upgradeToEnterpriseStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -691,8 +691,8 @@ func restart(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("restartServer", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -731,8 +731,8 @@ func sendWarnMetricAckEmail(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -768,8 +768,8 @@ func requestTrialLicenseAndAckWarnMetric(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/system_test.go b/api4/system_test.go index 6f87e2f65e..178e32653a 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -29,7 +29,7 @@ func TestGetPing(t *testing.T) { t.Run("healthy", func(t *testing.T) { status, resp := client.GetPing() CheckNoError(t, resp) - assert.Equal(t, model.STATUS_OK, status) + assert.Equal(t, model.StatusOk, status) }) t.Run("unhealthy", func(t *testing.T) { @@ -41,7 +41,7 @@ func TestGetPing(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = 10 }) status, resp := client.GetPing() CheckInternalErrorStatus(t, resp) - assert.Equal(t, model.STATUS_UNHEALTHY, status) + assert.Equal(t, model.StatusUnhealthy, status) }) }, "basic ping") @@ -50,7 +50,7 @@ func TestGetPing(t *testing.T) { status, resp := client.GetPingWithServerStatus() CheckNoError(t, resp) - assert.Equal(t, model.STATUS_OK, status) + assert.Equal(t, model.StatusOk, status) }) t.Run("unhealthy", func(t *testing.T) { @@ -63,7 +63,7 @@ func TestGetPing(t *testing.T) { status, resp := client.GetPingWithServerStatus() CheckInternalErrorStatus(t, resp) - assert.Equal(t, model.STATUS_UNHEALTHY, status) + assert.Equal(t, model.StatusUnhealthy, status) }) }, "with server status") @@ -148,7 +148,7 @@ func TestEmailTest(t *testing.T) { SMTPServerTimeout: model.NewInt(15), }, FileSettings: model.FileSettings{ - DriverName: model.NewString(model.IMAGE_DRIVER_LOCAL), + DriverName: model.NewString(model.ImageDriverLocal), Directory: model.NewString(dir), }, } @@ -472,9 +472,9 @@ func TestS3TestConnection(t *testing.T) { s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port) config := model.Config{ FileSettings: model.FileSettings{ - DriverName: model.NewString(model.IMAGE_DRIVER_S3), - AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY), - AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY), + DriverName: model.NewString(model.ImageDriverS3), + AmazonS3AccessKeyId: model.NewString(model.MinioAccessKey), + AmazonS3SecretAccessKey: model.NewString(model.MinioSecretKey), AmazonS3Bucket: model.NewString(""), AmazonS3Endpoint: model.NewString(s3Endpoint), AmazonS3Region: model.NewString(""), @@ -494,7 +494,7 @@ func TestS3TestConnection(t *testing.T) { require.Equal(t, resp.Error.Message, "S3 Bucket is required", "should return error - missing s3 bucket") // If this fails, check the test configuration to ensure minio is setup with the // `mattermost-test` bucket defined by model.MINIO_BUCKET. - *config.FileSettings.AmazonS3Bucket = model.MINIO_BUCKET + *config.FileSettings.AmazonS3Bucket = model.MinioBucket config.FileSettings.AmazonS3PathPrefix = model.NewString("") *config.FileSettings.AmazonS3Region = "us-east-1" _, resp = th.SystemAdminClient.TestS3Connection(&config) @@ -741,7 +741,7 @@ func TestPushNotificationAck(t *testing.T) { handler := api.ApiHandler(pushNotificationAck) resp := httptest.NewRecorder() req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) - req.Header.Set(model.HEADER_AUTH, "Bearer "+session.Token) + req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusBadRequest, resp.Code) diff --git a/api4/team.go b/api4/team.go index bf00ecc203..aea6c5f687 100644 --- a/api4/team.go +++ b/api4/team.go @@ -88,7 +88,7 @@ func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_TEAM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateTeam) { c.Err = model.NewAppError("createTeam", "api.team.is_team_creation_allowed.disabled.app_error", nil, "", http.StatusForbidden) return } @@ -120,8 +120,8 @@ func getTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if (!team.AllowOpenInvite || team.Type != model.TeamOpen) && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), team.Id, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -141,8 +141,8 @@ func getTeamByName(c *Context, w http.ResponseWriter, r *http.Request) { return } - if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if (!team.AllowOpenInvite || team.Type != model.TeamOpen) && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), team.Id, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -174,8 +174,8 @@ func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -208,8 +208,8 @@ func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchTeam", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -243,8 +243,8 @@ func restoreTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -282,9 +282,9 @@ func updateTeamPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { var openInvite bool switch privacy { - case model.TEAM_OPEN: + case model.TeamOpen: openInvite = true - case model.TEAM_INVITE: + case model.TeamInvite: openInvite = false default: c.SetInvalidParam("privacy") @@ -295,9 +295,9 @@ func updateTeamPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("privacy", privacy) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { auditRec.AddMeta("team_id", c.Params.TeamId) - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + c.SetPermissionError(model.PermissionManageTeam) return } @@ -325,8 +325,8 @@ func regenerateTeamInviteId(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -354,8 +354,8 @@ func deleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -392,8 +392,8 @@ func getTeamsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) + if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementUsers) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementUsers) return } @@ -413,8 +413,8 @@ func getTeamsUnreadForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -436,8 +436,8 @@ func getTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -448,7 +448,7 @@ func getTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -471,8 +471,8 @@ func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { excludeDeletedUsers := r.URL.Query().Get("exclude_deleted_users") excludeDeletedUsersBool, _ := strconv.ParseBool(excludeDeletedUsers) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -503,8 +503,8 @@ func getTeamMembersForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_OTHER_USERS_TEAMS) { - c.SetPermissionError(model.PERMISSION_READ_OTHER_USERS_TEAMS) + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadOtherUsersTeams) { + c.SetPermissionError(model.PermissionReadOtherUsersTeams) return } @@ -515,7 +515,7 @@ func getTeamMembersForUser(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -541,8 +541,8 @@ func getTeamMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -595,17 +595,17 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_JOIN_PUBLIC_TEAMS) { - c.SetPermissionError(model.PERMISSION_JOIN_PUBLIC_TEAMS) + if team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionJoinPublicTeams) { + c.SetPermissionError(model.PermissionJoinPublicTeams) return } - if !team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_JOIN_PRIVATE_TEAMS) { - c.SetPermissionError(model.PERMISSION_JOIN_PRIVATE_TEAMS) + if !team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionJoinPrivateTeams) { + c.SetPermissionError(model.PermissionJoinPrivateTeams) return } } else { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), member.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { - c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), member.TeamId, model.PermissionAddUserToTeam) { + c.SetPermissionError(model.PermissionAddUserToTeam) return } } @@ -660,7 +660,7 @@ func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request) if tokenId != "" { member, err = c.App.AddTeamMemberByToken(c.AppContext, c.AppContext.Session().UserId, tokenId) } else if inviteId != "" { - if c.AppContext.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { + if c.AppContext.Session().Props[model.SessionPropIsGuest] == "true" { c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden) return } @@ -753,8 +753,8 @@ func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { userIds = append(userIds, member.UserId) } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { - c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionAddUserToTeam) { + c.SetPermissionError(model.PermissionAddUserToTeam) return } @@ -797,8 +797,8 @@ func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if c.AppContext.Session().UserId != c.Params.UserId { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_REMOVE_USER_FROM_TEAM) { - c.SetPermissionError(model.PERMISSION_REMOVE_USER_FROM_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionRemoveUserFromTeam) { + c.SetPermissionError(model.PermissionRemoveUserFromTeam) return } } @@ -838,12 +838,12 @@ func getTeamUnread(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -862,8 +862,8 @@ func getTeamStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -900,8 +900,8 @@ func updateTeamMemberRoles(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeamRoles) { + c.SetPermissionError(model.PermissionManageTeamRoles) return } @@ -933,8 +933,8 @@ func updateTeamMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.Requ defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", schemeRoles) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeamRoles) { + c.SetPermissionError(model.PermissionManageTeamRoles) return } @@ -957,18 +957,18 @@ func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { opts := &model.TeamSearch{} if c.Params.ExcludePolicyConstrained { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } opts.ExcludePolicyConstrained = model.NewBool(true) } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { opts.IncludePolicyID = model.NewBool(true) } - listPrivate := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) - listPublic := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) + listPrivate := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPrivateTeams) + listPublic := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPublicTeams) limit := c.Params.PerPage offset := limit * c.Params.Page if listPrivate && listPublic { @@ -1012,13 +1012,13 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } // Only system managers may use the ExcludePolicyConstrained field - if props.ExcludePolicyConstrained != nil && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) + if props.ExcludePolicyConstrained != nil && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { + c.SetPermissionError(model.PermissionSysconsoleReadComplianceDataRetentionPolicy) return } // policy ID may only be used through the /data_retention/policies endpoint props.PolicyID = nil - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadComplianceDataRetentionPolicy) { props.IncludePolicyID = model.NewBool(true) } @@ -1026,15 +1026,15 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { var totalCount int64 var err *model.AppError - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPrivateTeams) && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPublicTeams) { teams, totalCount, err = c.App.SearchAllTeams(props) - } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPrivateTeams) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.private_team_search", nil, "", http.StatusNotImplemented) return } teams, err = c.App.SearchPrivateTeams(props) - } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPublicTeams) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.public_team_search", nil, "", http.StatusNotImplemented) return @@ -1086,8 +1086,8 @@ func teamExists(c *Context, w http.ResponseWriter, r *http.Request) { // Verify that the user can see the team (be a member or have the permission to list the team) if (teamMember != nil && teamMember.DeleteAt == 0) || - (team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS)) || - (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS)) { + (team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPublicTeams)) || + (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListPrivateTeams)) { exists = true } } @@ -1107,8 +1107,8 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_IMPORT_TEAM) { - c.SetPermissionError(model.PERMISSION_IMPORT_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionImportTeam) { + c.SetPermissionError(model.PermissionImportTeam) return } @@ -1193,13 +1193,13 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_INVITE_USER) { - c.SetPermissionError(model.PERMISSION_INVITE_USER) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionInviteUser) { + c.SetPermissionError(model.PermissionInviteUser) return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { - c.SetPermissionError(model.PERMISSION_INVITE_USER) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionAddUserToTeam) { + c.SetPermissionError(model.PermissionInviteUser) return } @@ -1250,7 +1250,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { } // we then manually schedule the job - _, e := c.App.Srv().Jobs.CreateJob(model.JOB_TYPE_RESEND_INVITATION_EMAIL, jobData) + _, e := c.App.Srv().Jobs.CreateJob(model.JobTypeResendInvitationEmail, jobData) if e != nil { c.Err = model.NewAppError("Api4.inviteUsersToTeam", e.Id, nil, e.Error(), e.StatusCode) return @@ -1313,8 +1313,8 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { - c.SetPermissionError(model.PERMISSION_INVITE_GUEST) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionInviteGuest) { + c.SetPermissionError(model.PermissionInviteGuest) return } @@ -1400,7 +1400,7 @@ func getInviteInfo(c *Context, w http.ResponseWriter, r *http.Request) { return } - if team.Type != model.TEAM_OPEN { + if team.Type != model.TeamOpen { c.Err = model.NewAppError("getInviteInfo", "api.team.get_invite_info.not_open_team", nil, "id="+c.Params.InviteId, http.StatusForbidden) return } @@ -1414,8 +1414,8 @@ func getInviteInfo(c *Context, w http.ResponseWriter, r *http.Request) { } func invalidateAllEmailInvites(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_INVALIDATE_EMAIL_INVITE) { - c.SetPermissionError(model.PERMISSION_INVALIDATE_EMAIL_INVITE) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionInvalidateEmailInvite) { + c.SetPermissionError(model.PermissionInvalidateEmailInvite) return } @@ -1444,9 +1444,9 @@ func getTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) && - (team.Type != model.TEAM_OPEN || !team.AllowOpenInvite) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionViewTeam) && + (team.Type != model.TeamOpen || !team.AllowOpenInvite) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -1464,7 +1464,7 @@ func getTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "image/png") w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, private", 24*60*60)) // 24 hrs - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write(img) } @@ -1480,8 +1480,8 @@ func setTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -1531,8 +1531,8 @@ func removeTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { - c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionManageTeam) { + c.SetPermissionError(model.PermissionManageTeam) return } @@ -1567,8 +1567,8 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementPermissions) { + c.SetPermissionError(model.PermissionSysconsoleWriteUserManagementPermissions) return } @@ -1580,7 +1580,7 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("scheme", scheme) - if scheme.Scope != model.SCHEME_SCOPE_TEAM { + if scheme.Scope != model.SchemeScopeTeam { c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.scheme_scope.error", nil, "", http.StatusBadRequest) return } @@ -1627,8 +1627,8 @@ func teamMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http.Req groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } diff --git a/api4/team_test.go b/api4/team_test.go index ea5c39971e..a6673164d8 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -27,7 +27,7 @@ func TestCreateTeam(t *testing.T) { defer th.TearDown() th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { - team := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TEAM_OPEN} + team := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TeamOpen} rteam, resp := client.CreateTeam(team) CheckNoError(t, resp) CheckCreatedStatus(t, resp) @@ -57,7 +57,7 @@ func TestCreateTeam(t *testing.T) { require.Equalf(t, r.StatusCode, http.StatusBadRequest, "wrong status code, actual: %s, expected: %s", strconv.Itoa(r.StatusCode), strconv.Itoa(http.StatusBadRequest)) // Test GroupConstrained flag - groupConstrainedTeam := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TEAM_OPEN, GroupConstrained: model.NewBool(true)} + groupConstrainedTeam := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TeamOpen, GroupConstrained: model.NewBool(true)} rteam, resp = client.CreateTeam(groupConstrainedTeam) CheckNoError(t, resp) CheckCreatedStatus(t, resp) @@ -67,7 +67,7 @@ func TestCreateTeam(t *testing.T) { th.Client.Logout() - team := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TEAM_OPEN} + team := &model.Team{Name: GenerateTestUsername(), DisplayName: "Some Team", Type: model.TeamOpen} _, resp := th.Client.CreateTeam(team) CheckUnauthorizedStatus(t, resp) @@ -79,8 +79,8 @@ func TestCreateTeam(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.RemovePermissionFromRole(model.PERMISSION_CREATE_TEAM.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_TEAM.Id, model.SYSTEM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionCreateTeam.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionCreateTeam.Id, model.SystemAdminRoleId) _, resp = th.Client.CreateTeam(team) CheckForbiddenStatus(t, resp) @@ -97,7 +97,7 @@ func TestCreateTeamSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", } @@ -112,7 +112,7 @@ func TestCreateTeamSanitization(t *testing.T) { DisplayName: t.Name() + "_2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", } @@ -147,10 +147,10 @@ func TestGetTeam(t *testing.T) { th.LoginTeamAdmin() - team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: false} + team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: false} rteam2, _ := Client.CreateTeam(team2) - team3 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_INVITE, AllowOpenInvite: true} + team3 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamInvite, AllowOpenInvite: true} rteam3, _ := Client.CreateTeam(team3) th.LoginBasic() @@ -180,7 +180,7 @@ func TestGetTeamSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -199,7 +199,7 @@ func TestGetTeamSanitization(t *testing.T) { }) t.Run("team user without invite permissions", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) th.LinkUserToTeam(th.BasicUser2, team) client := th.CreateClient() @@ -264,7 +264,7 @@ func TestUpdateTeam(t *testing.T) { defer th.TearDown() th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { - team := &model.Team{DisplayName: "Name", Description: "Some description", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "Name", Description: "Some description", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} var resp *model.Response team, resp = th.Client.CreateTeam(team) CheckNoError(t, resp) @@ -321,11 +321,11 @@ func TestUpdateTeam(t *testing.T) { require.NotEqual(t, uteam.Email, "test@domain.com", "Should not update email") - team.Type = model.TEAM_INVITE + team.Type = model.TeamInvite uteam, resp = client.UpdateTeam(team) CheckNoError(t, resp) - require.NotEqual(t, uteam.Type, model.TEAM_INVITE, "Should not update type") + require.NotEqual(t, uteam.Type, model.TeamInvite, "Should not update type") originalTeamId := team.Id team.Id = model.NewId() @@ -346,7 +346,7 @@ func TestUpdateTeam(t *testing.T) { }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - team := &model.Team{DisplayName: "New", Description: "Some description", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "New", Description: "Some description", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} var resp *model.Response team, resp = client.CreateTeam(team) CheckNoError(t, resp) @@ -365,7 +365,7 @@ func TestUpdateTeamSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -393,7 +393,7 @@ func TestPatchTeam(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - team := &model.Team{DisplayName: "Name", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "Name", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} team, _ = th.Client.CreateTeam(team) patch := &model.TeamPatch{} @@ -425,7 +425,7 @@ func TestPatchTeam(t *testing.T) { require.True(t, rteam.AllowOpenInvite, "AllowOpenInvite did not update properly") t.Run("Changing AllowOpenInvite to false regenerates InviteID", func(t *testing.T) { - team2 := &model.Team{DisplayName: "Name2", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: true, InviteId: model.NewId(), Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team2 := &model.Team{DisplayName: "Name2", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: true, InviteId: model.NewId(), Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} team2, _ = client.CreateTeam(team2) patch2 := &model.TeamPatch{ @@ -440,7 +440,7 @@ func TestPatchTeam(t *testing.T) { }) t.Run("Changing AllowOpenInvite to true doesn't regenerate InviteID", func(t *testing.T) { - team2 := &model.Team{DisplayName: "Name3", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: model.NewId(), Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team2 := &model.Team{DisplayName: "Name3", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: model.NewId(), Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} team2, _ = client.CreateTeam(team2) patch2 := &model.TeamPatch{ @@ -487,7 +487,7 @@ func TestRestoreTeam(t *testing.T) { DisplayName: "Some Team", Description: "Some description", CompanyName: "Some company name", - AllowOpenInvite: (teamType == model.TEAM_OPEN), + AllowOpenInvite: (teamType == model.TeamOpen), InviteId: model.NewId(), Name: "aa-" + model.NewRandomTeamName() + "zz", Email: "success+" + model.NewId() + "@simulator.amazonses.com", @@ -501,7 +501,7 @@ func TestRestoreTeam(t *testing.T) { } return team } - teamPublic := createTeam(t, true, model.TEAM_OPEN) + teamPublic := createTeam(t, true, model.TeamOpen) t.Run("invalid team", func(t *testing.T) { _, resp := Client.RestoreTeam(model.NewId()) @@ -509,27 +509,27 @@ func TestRestoreTeam(t *testing.T) { }) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { - team := createTeam(t, true, model.TEAM_OPEN) + team := createTeam(t, true, model.TeamOpen) team, resp := client.RestoreTeam(team.Id) CheckOKStatus(t, resp) require.Zero(t, team.DeleteAt) - require.Equal(t, model.TEAM_OPEN, team.Type) + require.Equal(t, model.TeamOpen, team.Type) }, "restore archived public team") th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { - team := createTeam(t, true, model.TEAM_INVITE) + team := createTeam(t, true, model.TeamInvite) team, resp := client.RestoreTeam(team.Id) CheckOKStatus(t, resp) require.Zero(t, team.DeleteAt) - require.Equal(t, model.TEAM_INVITE, team.Type) + require.Equal(t, model.TeamInvite, team.Type) }, "restore archived private team") th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { - team := createTeam(t, false, model.TEAM_OPEN) + team := createTeam(t, false, model.TeamOpen) team, resp := client.RestoreTeam(team.Id) CheckOKStatus(t, resp) require.Zero(t, team.DeleteAt) - require.Equal(t, model.TEAM_OPEN, team.Type) + require.Equal(t, model.TeamOpen, team.Type) }, "restore active public team") t.Run("not logged in", func(t *testing.T) { @@ -558,7 +558,7 @@ func TestPatchTeamSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -602,11 +602,11 @@ func TestUpdateTeamPrivacy(t *testing.T) { return team } - teamPublic := createTeam(model.TEAM_OPEN, true) - teamPrivate := createTeam(model.TEAM_INVITE, false) + teamPublic := createTeam(model.TeamOpen, true) + teamPrivate := createTeam(model.TeamInvite, false) - teamPublic2 := createTeam(model.TEAM_OPEN, true) - teamPrivate2 := createTeam(model.TEAM_INVITE, false) + teamPublic2 := createTeam(model.TeamOpen, true) + teamPrivate2 := createTeam(model.TeamInvite, false) tests := []struct { name string @@ -618,11 +618,11 @@ func TestUpdateTeamPrivacy(t *testing.T) { wantInviteIdChanged bool originalInviteId string }{ - {name: "bad privacy", team: teamPublic, privacy: "blap", errChecker: CheckBadRequestStatus, wantType: model.TEAM_OPEN, wantOpenInvite: true}, - {name: "public to private", team: teamPublic, privacy: model.TEAM_INVITE, errChecker: nil, wantType: model.TEAM_INVITE, wantOpenInvite: false, originalInviteId: teamPublic.InviteId, wantInviteIdChanged: true}, - {name: "private to public", team: teamPrivate, privacy: model.TEAM_OPEN, errChecker: nil, wantType: model.TEAM_OPEN, wantOpenInvite: true, originalInviteId: teamPrivate.InviteId, wantInviteIdChanged: false}, - {name: "public to public", team: teamPublic2, privacy: model.TEAM_OPEN, errChecker: nil, wantType: model.TEAM_OPEN, wantOpenInvite: true, originalInviteId: teamPublic2.InviteId, wantInviteIdChanged: false}, - {name: "private to private", team: teamPrivate2, privacy: model.TEAM_INVITE, errChecker: nil, wantType: model.TEAM_INVITE, wantOpenInvite: false, originalInviteId: teamPrivate2.InviteId, wantInviteIdChanged: false}, + {name: "bad privacy", team: teamPublic, privacy: "blap", errChecker: CheckBadRequestStatus, wantType: model.TeamOpen, wantOpenInvite: true}, + {name: "public to private", team: teamPublic, privacy: model.TeamInvite, errChecker: nil, wantType: model.TeamInvite, wantOpenInvite: false, originalInviteId: teamPublic.InviteId, wantInviteIdChanged: true}, + {name: "private to public", team: teamPrivate, privacy: model.TeamOpen, errChecker: nil, wantType: model.TeamOpen, wantOpenInvite: true, originalInviteId: teamPrivate.InviteId, wantInviteIdChanged: false}, + {name: "public to public", team: teamPublic2, privacy: model.TeamOpen, errChecker: nil, wantType: model.TeamOpen, wantOpenInvite: true, originalInviteId: teamPublic2.InviteId, wantInviteIdChanged: false}, + {name: "private to private", team: teamPrivate2, privacy: model.TeamInvite, errChecker: nil, wantType: model.TeamInvite, wantOpenInvite: false, originalInviteId: teamPrivate2.InviteId, wantInviteIdChanged: false}, } for _, test := range tests { @@ -647,24 +647,24 @@ func TestUpdateTeamPrivacy(t *testing.T) { } t.Run("non-existent team", func(t *testing.T) { - _, resp := Client.UpdateTeamPrivacy(model.NewId(), model.TEAM_INVITE) + _, resp := Client.UpdateTeamPrivacy(model.NewId(), model.TeamInvite) CheckForbiddenStatus(t, resp) }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - _, resp := client.UpdateTeamPrivacy(model.NewId(), model.TEAM_INVITE) + _, resp := client.UpdateTeamPrivacy(model.NewId(), model.TeamInvite) CheckNotFoundStatus(t, resp) }, "non-existent team for admins") t.Run("not logged in", func(t *testing.T) { Client.Logout() - _, resp := Client.UpdateTeamPrivacy(teamPublic.Id, model.TEAM_INVITE) + _, resp := Client.UpdateTeamPrivacy(teamPublic.Id, model.TeamInvite) CheckUnauthorizedStatus(t, resp) }) t.Run("no permission to manage team", func(t *testing.T) { th.LoginBasic2() - _, resp := Client.UpdateTeamPrivacy(teamPublic.Id, model.TEAM_INVITE) + _, resp := Client.UpdateTeamPrivacy(teamPublic.Id, model.TeamInvite) CheckForbiddenStatus(t, resp) }) } @@ -680,7 +680,7 @@ func TestTeamUnicodeNames(t *testing.T) { DisplayName: "Some\u206c Team", Description: "A \ufffatest\ufffb channel.", CompanyName: "\ufeffAcme Inc\ufffc", - Type: model.TEAM_OPEN} + Type: model.TeamOpen} rteam, resp := Client.CreateTeam(team) CheckNoError(t, resp) CheckCreatedStatus(t, resp) @@ -697,7 +697,7 @@ func TestTeamUnicodeNames(t *testing.T) { CompanyName: "Bad Company", Name: model.NewRandomTeamName(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN} + Type: model.TeamOpen} team, _ = Client.CreateTeam(team) team.DisplayName = "\u206eThe Team\u206f" @@ -718,7 +718,7 @@ func TestTeamUnicodeNames(t *testing.T) { CompanyName: "Some company name", Name: model.NewRandomTeamName(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN} + Type: model.TeamOpen} team, _ = Client.CreateTeam(team) patch := &model.TeamPatch{} @@ -741,7 +741,7 @@ func TestRegenerateTeamInviteId(t *testing.T) { defer th.TearDown() Client := th.Client - team := &model.Team{DisplayName: "Name", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "Name", Description: "Some description", CompanyName: "Some company name", AllowOpenInvite: false, InviteId: "inviteid0", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", Type: model.TeamOpen} team, _ = Client.CreateTeam(team) assert.NotEqual(t, team.InviteId, "") @@ -766,7 +766,7 @@ func TestSoftDeleteTeam(t *testing.T) { CheckUnauthorizedStatus(t, resp) th.LoginBasic() - team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen} team, _ = th.Client.CreateTeam(team) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { @@ -802,7 +802,7 @@ func TestPermanentDeleteTeam(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableAPITeamDeletion = false }) t.Run("Permanent deletion not available through API if EnableAPITeamDeletion is not set", func(t *testing.T) { - team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen} team, _ = th.Client.CreateTeam(team) _, resp := th.Client.PermanentDeleteTeam(team.Id) @@ -813,7 +813,7 @@ func TestPermanentDeleteTeam(t *testing.T) { }) t.Run("Permanent deletion available through local mode even if EnableAPITeamDeletion is not set", func(t *testing.T) { - team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen} team, _ = th.Client.CreateTeam(team) ok, resp := th.LocalClient.PermanentDeleteTeam(team.Id) @@ -827,7 +827,7 @@ func TestPermanentDeleteTeam(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableAPITeamDeletion = true }) - team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN} + team := &model.Team{DisplayName: "DisplayName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen} team, _ = client.CreateTeam(team) ok, resp := client.PermanentDeleteTeam(team.Id) CheckNoError(t, resp) @@ -848,19 +848,19 @@ func TestGetAllTeams(t *testing.T) { defer th.TearDown() Client := th.Client - team1 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: true} + team1 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: true} team1, resp := Client.CreateTeam(team1) CheckNoError(t, resp) - team2 := &model.Team{DisplayName: "Name2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: true} + team2 := &model.Team{DisplayName: "Name2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: true} team2, resp = Client.CreateTeam(team2) CheckNoError(t, resp) - team3 := &model.Team{DisplayName: "Name3", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: false} + team3 := &model.Team{DisplayName: "Name3", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: false} team3, resp = Client.CreateTeam(team3) CheckNoError(t, resp) - team4 := &model.Team{DisplayName: "Name4", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: false} + team4 := &model.Team{DisplayName: "Name4", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: false} team4, resp = Client.CreateTeam(team4) CheckNoError(t, resp) @@ -880,42 +880,42 @@ func TestGetAllTeams(t *testing.T) { Name: "Get 1 team per page", Page: 0, PerPage: 1, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id}, ExpectedTeams: []string{team1.Id}, }, { Name: "Get second page with 1 team per page", Page: 1, PerPage: 1, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id}, ExpectedTeams: []string{team2.Id}, }, { Name: "Get no items per page", Page: 1, PerPage: 0, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id}, ExpectedTeams: []string{}, }, { Name: "Get all open teams", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id}, ExpectedTeams: []string{team1.Id, team2.Id}, }, { Name: "Get all private teams", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PRIVATE_TEAMS.Id}, + Permissions: []string{model.PermissionListPrivateTeams.Id}, ExpectedTeams: []string{th.BasicTeam.Id, team3.Id, team4.Id}, }, { Name: "Get all teams", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.PERMISSION_LIST_PRIVATE_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id, model.PermissionListPrivateTeams.Id}, ExpectedTeams: []string{th.BasicTeam.Id, team1.Id, team2.Id, team3.Id, team4.Id}, }, { @@ -941,7 +941,7 @@ func TestGetAllTeams(t *testing.T) { Name: "Get all teams with count", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.PERMISSION_LIST_PRIVATE_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id, model.PermissionListPrivateTeams.Id}, ExpectedTeams: []string{th.BasicTeam.Id, team1.Id, team2.Id, team3.Id, team4.Id}, WithCount: true, ExpectedCount: 5, @@ -950,7 +950,7 @@ func TestGetAllTeams(t *testing.T) { Name: "Get all public teams with count", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PUBLIC_TEAMS.Id}, + Permissions: []string{model.PermissionListPublicTeams.Id}, ExpectedTeams: []string{team1.Id, team2.Id}, WithCount: true, ExpectedCount: 2, @@ -959,7 +959,7 @@ func TestGetAllTeams(t *testing.T) { Name: "Get all private teams with count", Page: 0, PerPage: 10, - Permissions: []string{model.PERMISSION_LIST_PRIVATE_TEAMS.Id}, + Permissions: []string{model.PermissionListPrivateTeams.Id}, ExpectedTeams: []string{th.BasicTeam.Id, team3.Id, team4.Id}, WithCount: true, ExpectedCount: 3, @@ -972,12 +972,12 @@ func TestGetAllTeams(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.RemovePermissionFromRole(model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_LIST_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_JOIN_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListPublicTeams.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionJoinPublicTeams.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionListPrivateTeams.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionJoinPrivateTeams.Id, model.SystemUserRoleId) for _, permission := range tc.Permissions { - th.AddPermissionToRole(permission, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(permission, model.SystemUserRoleId) } var teams []*model.Team @@ -1092,7 +1092,7 @@ func TestGetAllTeamsSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", AllowOpenInvite: true, }) @@ -1101,7 +1101,7 @@ func TestGetAllTeamsSanitization(t *testing.T) { DisplayName: t.Name() + "_2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", AllowOpenInvite: true, }) @@ -1178,10 +1178,10 @@ func TestGetTeamByName(t *testing.T) { th.LoginTeamAdmin() - team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, AllowOpenInvite: false} + team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen, AllowOpenInvite: false} rteam2, _ := th.Client.CreateTeam(team2) - team3 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_INVITE, AllowOpenInvite: true} + team3 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamInvite, AllowOpenInvite: true} rteam3, _ := th.Client.CreateTeam(team3) th.LoginBasic() @@ -1202,7 +1202,7 @@ func TestGetTeamByNameSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -1221,7 +1221,7 @@ func TestGetTeamByNameSanitization(t *testing.T) { }) t.Run("team user without invite permissions", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) th.LinkUserToTeam(th.BasicUser2, team) client := th.CreateClient() @@ -1263,7 +1263,7 @@ func TestSearchAllTeams(t *testing.T) { require.Nil(t, err, err) oTeam.UpdateAt = updatedTeam.UpdateAt - pTeam := &model.Team{DisplayName: "PName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_INVITE} + pTeam := &model.Team{DisplayName: "PName", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamInvite} th.Client.CreateTeam(pTeam) rteams, resp := th.Client.SearchTeams(&model.TeamSearch{Term: pTeam.Name}) @@ -1362,7 +1362,7 @@ func TestSearchAllTeamsPaged(t *testing.T) { newTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: fmt.Sprintf("%s %d %s", commonRandom, i, uid), Name: fmt.Sprintf("%s-%d-%s", commonRandom, i, uid), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, Email: th.GenerateTestEmail(), }) require.Nil(t, err) @@ -1372,7 +1372,7 @@ func TestSearchAllTeamsPaged(t *testing.T) { foobarTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "FOOBARDISPLAYNAME", Name: "whatever", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, Email: th.GenerateTestEmail(), }) require.Nil(t, err) @@ -1488,7 +1488,7 @@ func TestSearchAllTeamsSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -1496,7 +1496,7 @@ func TestSearchAllTeamsSanitization(t *testing.T) { DisplayName: t.Name() + "_2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -1555,7 +1555,7 @@ func TestGetTeamsForUser(t *testing.T) { defer th.TearDown() Client := th.Client - team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_INVITE} + team2 := &model.Team{DisplayName: "Name", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamInvite} rteam2, _ := Client.CreateTeam(team2) teams, resp := Client.GetTeamsForUser(th.BasicUser.Id, "") @@ -1597,7 +1597,7 @@ func TestGetTeamsForUserSanitization(t *testing.T) { DisplayName: t.Name() + "_1", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -1605,7 +1605,7 @@ func TestGetTeamsForUserSanitization(t *testing.T) { DisplayName: t.Name() + "_2", Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, AllowedDomains: "simulator.amazonses.com,localhost", }) CheckNoError(t, resp) @@ -1634,7 +1634,7 @@ func TestGetTeamsForUserSanitization(t *testing.T) { th.LinkUserToTeam(th.BasicUser2, team2) client := th.CreateClient() - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) th.LoginBasic2WithClient(client) rteams, resp := client.GetTeamsForUser(th.BasicUser2.Id, "") @@ -1923,10 +1923,10 @@ func TestAddTeamMember(t *testing.T) { }() // Set the config so that only team admins can add a user to a team. - th.AddPermissionToRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionInviteUser.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionAddUserToTeam.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) + th.RemovePermissionFromRole(model.PermissionAddUserToTeam.Id, model.TeamUserRoleId) th.LoginBasic() @@ -1944,10 +1944,10 @@ func TestAddTeamMember(t *testing.T) { CheckNoError(t, resp) // Change permission level to team user - th.AddPermissionToRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionAddUserToTeam.Id, model.TeamUserRoleId) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionAddUserToTeam.Id, model.TeamAdminRoleId) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.App.Srv().InvalidateAllCaches() @@ -2147,14 +2147,14 @@ func TestAddTeamMemberMyself(t *testing.T) { team.AllowOpenInvite = tc.Public th.App.UpdateTeam(team) if tc.PublicPermission { - th.AddPermissionToRole(model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionJoinPublicTeams.Id, model.SystemUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionJoinPublicTeams.Id, model.SystemUserRoleId) } if tc.PrivatePermission { - th.AddPermissionToRole(model.PERMISSION_JOIN_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionJoinPrivateTeams.Id, model.SystemUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_JOIN_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionJoinPrivateTeams.Id, model.SystemUserRoleId) } _, resp := Client.AddTeamMember(team.Id, th.BasicUser.Id) if tc.ExpectedSuccess { @@ -2291,10 +2291,10 @@ func TestAddTeamMembers(t *testing.T) { }() // Set the config so that only team admins can add a user to a team. - th.AddPermissionToRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionInviteUser.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionAddUserToTeam.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) + th.RemovePermissionFromRole(model.PermissionAddUserToTeam.Id, model.TeamUserRoleId) th.LoginBasic() @@ -2312,10 +2312,10 @@ func TestAddTeamMembers(t *testing.T) { CheckNoError(t, resp) // Change permission level to team user - th.AddPermissionToRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_INVITE_USER.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionInviteUser.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionAddUserToTeam.Id, model.TeamUserRoleId) + th.RemovePermissionFromRole(model.PermissionInviteUser.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionAddUserToTeam.Id, model.TeamAdminRoleId) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.App.Srv().InvalidateAllCaches() @@ -2675,20 +2675,20 @@ func TestTeamExists(t *testing.T) { defer th.TearDown() Client := th.Client public_member_team := th.BasicTeam - err := th.App.UpdateTeamPrivacy(public_member_team.Id, model.TEAM_OPEN, true) + err := th.App.UpdateTeamPrivacy(public_member_team.Id, model.TeamOpen, true) require.Nil(t, err) public_not_member_team := th.CreateTeamWithClient(th.SystemAdminClient) - err = th.App.UpdateTeamPrivacy(public_not_member_team.Id, model.TEAM_OPEN, true) + err = th.App.UpdateTeamPrivacy(public_not_member_team.Id, model.TeamOpen, true) require.Nil(t, err) private_member_team := th.CreateTeamWithClient(th.SystemAdminClient) th.LinkUserToTeam(th.BasicUser, private_member_team) - err = th.App.UpdateTeamPrivacy(private_member_team.Id, model.TEAM_INVITE, false) + err = th.App.UpdateTeamPrivacy(private_member_team.Id, model.TeamInvite, false) require.Nil(t, err) private_not_member_team := th.CreateTeamWithClient(th.SystemAdminClient) - err = th.App.UpdateTeamPrivacy(private_not_member_team.Id, model.TEAM_INVITE, false) + err = th.App.UpdateTeamPrivacy(private_not_member_team.Id, model.TeamInvite, false) require.Nil(t, err) // Check the appropriate permissions are enforced. @@ -2697,8 +2697,8 @@ func TestTeamExists(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_LIST_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionListPublicTeams.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionListPrivateTeams.Id, model.SystemUserRoleId) t.Run("Logged user with permissions and valid public team", func(t *testing.T) { th.LoginBasic() @@ -2729,7 +2729,7 @@ func TestTeamExists(t *testing.T) { t.Run("Logged without LIST_PUBLIC_TEAMS permissions and member public team", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListPublicTeams.Id, model.SystemUserRoleId) exists, resp := Client.TeamExists(public_member_team.Name, "") CheckNoError(t, resp) @@ -2738,7 +2738,7 @@ func TestTeamExists(t *testing.T) { t.Run("Logged without LIST_PUBLIC_TEAMS permissions and not member public team", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_LIST_PUBLIC_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListPublicTeams.Id, model.SystemUserRoleId) exists, resp := Client.TeamExists(public_not_member_team.Name, "") CheckNoError(t, resp) @@ -2747,7 +2747,7 @@ func TestTeamExists(t *testing.T) { t.Run("Logged without LIST_PRIVATE_TEAMS permissions and member private team", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_LIST_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListPrivateTeams.Id, model.SystemUserRoleId) exists, resp := Client.TeamExists(private_member_team.Name, "") CheckNoError(t, resp) @@ -2756,7 +2756,7 @@ func TestTeamExists(t *testing.T) { t.Run("Logged without LIST_PRIVATE_TEAMS permissions and not member private team", func(t *testing.T) { th.LoginBasic() - th.RemovePermissionFromRole(model.PERMISSION_LIST_PRIVATE_TEAMS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionListPrivateTeams.Id, model.SystemUserRoleId) exists, resp := Client.TeamExists(private_not_member_team.Name, "") CheckNoError(t, resp) @@ -3272,7 +3272,7 @@ func TestUpdateTeamScheme(t *testing.T) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, _ = th.SystemAdminClient.CreateTeam(team) @@ -3280,14 +3280,14 @@ func TestUpdateTeamScheme(t *testing.T) { DisplayName: "DisplayName", Name: model.NewId(), Description: "Some description", - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } teamScheme, _ = th.SystemAdminClient.CreateScheme(teamScheme) channelScheme := &model.Scheme{ DisplayName: "DisplayName", Name: model.NewId(), Description: "Some description", - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } channelScheme, _ = th.SystemAdminClient.CreateScheme(channelScheme) @@ -3431,8 +3431,8 @@ func TestInvalidateAllEmailInvites(t *testing.T) { }) t.Run("OK when request performed by system user with requisite system permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_INVALIDATE_EMAIL_INVITE.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_INVALIDATE_EMAIL_INVITE.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionInvalidateEmailInvite.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionInvalidateEmailInvite.Id, model.SystemUserRoleId) ok, res := th.Client.InvalidateEmailInvites() require.Equal(t, true, ok) CheckOKStatus(t, res) diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 8367a86432..bdf219fc3e 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -27,8 +27,8 @@ func getLatestTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) } func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } diff --git a/api4/upload.go b/api4/upload.go index 7e3b8c16ad..73b711c3f9 100644 --- a/api4/upload.go +++ b/api4/upload.go @@ -43,12 +43,12 @@ func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { if us.Type == model.UploadTypeImport { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { - c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { + c.SetPermissionError(model.PermissionUploadFile) return } us.Type = model.UploadTypeAttachment @@ -113,12 +113,12 @@ func uploadData(c *Context, w http.ResponseWriter, r *http.Request) { if us.Type == model.UploadTypeImport { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + c.SetPermissionError(model.PermissionManageSystem) return } } else { - if us.UserId != c.AppContext.Session().UserId || !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { - c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) + if us.UserId != c.AppContext.Session().UserId || !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { + c.SetPermissionError(model.PermissionUploadFile) return } } diff --git a/api4/upload_test.go b/api4/upload_test.go index 0031756d40..a8ffb180f4 100644 --- a/api4/upload_test.go +++ b/api4/upload_test.go @@ -333,7 +333,7 @@ func TestUploadDataMultipart(t *testing.T) { req, err := http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+us.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) - req.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) res, err := th.Client.HttpClient.Do(req) require.NoError(t, err) info := model.FileInfoFromJson(res.Body) @@ -357,7 +357,7 @@ func TestUploadDataMultipart(t *testing.T) { req, err := http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+u.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) - req.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) res, err := th.Client.HttpClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusNoContent, res.StatusCode) @@ -368,7 +368,7 @@ func TestUploadDataMultipart(t *testing.T) { req, err = http.NewRequest("POST", th.Client.ApiUrl+"/uploads/"+u.Id, mpData) require.NoError(t, err) req.Header.Set("Content-Type", contentType) - req.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken) + req.Header.Set(model.HeaderAuth, th.Client.AuthType+" "+th.Client.AuthToken) res, err = th.Client.HttpClient.Do(req) require.NoError(t, err) info := model.FileInfoFromJson(res.Body) diff --git a/api4/user.go b/api4/user.go index 5e8d677039..7ce35f9f03 100644 --- a/api4/user.go +++ b/api4/user.go @@ -187,12 +187,12 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { canSee, err := c.App.UserCanSeeOtherUser(c.AppContext.Session().UserId, c.Params.UserId) if err != nil { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -227,7 +227,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { c.App.SanitizeProfile(user, c.IsSystemAdmin()) } c.App.UpdateLastActivityAtIfNeeded(*c.AppContext.Session()) - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } @@ -245,7 +245,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } if restrictions != nil { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } c.Err = err @@ -259,7 +259,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -287,7 +287,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { } else { c.App.SanitizeProfile(user, c.IsSystemAdmin()) } - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } @@ -311,7 +311,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { return } if restrictions != nil { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } c.Err = err @@ -325,7 +325,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -336,7 +336,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.SanitizeProfile(user, c.IsSystemAdmin()) - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } @@ -353,7 +353,7 @@ func getDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request) } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -387,7 +387,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { } if !canSee { - c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) + c.SetPermissionError(model.PermissionViewMembers) return } @@ -412,7 +412,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, private", 5*60)) // 5 mins } else { w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, private", 24*60*60)) // 24 hrs - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) } w.Header().Set("Content-Type", "image/png") @@ -428,7 +428,7 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -499,7 +499,7 @@ func setDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -597,8 +597,8 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) { TeamRoles: teamRoles, } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementUsers) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementUsers) return } @@ -732,22 +732,22 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { if withoutTeamBool, _ := strconv.ParseBool(withoutTeam); withoutTeamBool { // Use a special permission for now - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_USERS_WITHOUT_TEAM) { - c.SetPermissionError(model.PERMISSION_LIST_USERS_WITHOUT_TEAM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionListUsersWithoutTeam) { + c.SetPermissionError(model.PermissionListUsersWithoutTeam) return } profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) } else if notInChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), notInChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) } else if notInTeamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), notInTeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -758,8 +758,8 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) } else if inTeamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), inTeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } @@ -775,8 +775,8 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } } else if inChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), inChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } if sort == "status" { @@ -790,8 +790,8 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { - c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleReadUserManagementGroups) { + c.SetPermissionError(model.PermissionSysconsoleReadUserManagementGroups) return } @@ -815,7 +815,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } if etag != "" { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) } c.App.UpdateLastActivityAtIfNeeded(*c.AppContext.Session()) w.Write([]byte(model.UserListToJson(profiles))) @@ -918,33 +918,33 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } } - if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.InChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.InChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } - if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.NotInChannelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.NotInChannelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } - if props.TeamId != "" && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), props.TeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if props.TeamId != "" && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), props.TeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } - if props.NotInTeamId != "" && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), props.NotInTeamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if props.NotInTeamId != "" && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), props.NotInTeamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } - if props.Limit <= 0 || props.Limit > model.USER_SEARCH_MAX_LIMIT { + if props.Limit <= 0 || props.Limit > model.UserSearchMaxLimit { c.SetInvalidParam("limit") return } @@ -960,7 +960,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { TeamRoles: props.TeamRoles, } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { options.AllowEmails = true options.AllowFullNames = true } else { @@ -990,9 +990,9 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { limitStr := r.URL.Query().Get("limit") limit, _ := strconv.Atoi(limitStr) if limitStr == "" { - limit = model.USER_SEARCH_DEFAULT_LIMIT - } else if limit > model.USER_SEARCH_MAX_LIMIT { - limit = model.USER_SEARCH_MAX_LIMIT + limit = model.UserSearchDefaultLimit + } else if limit > model.UserSearchMaxLimit { + limit = model.UserSearchMaxLimit } options := &model.UserSearchOptions{ @@ -1002,22 +1002,22 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { Limit: limit, } - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { options.AllowFullNames = true } else { options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName } if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + c.SetPermissionError(model.PermissionReadChannel) return } } if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_VIEW_TEAM) { - c.SetPermissionError(model.PERMISSION_VIEW_TEAM) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionViewTeam) { + c.SetPermissionError(model.PermissionViewTeam) return } } @@ -1094,13 +1094,13 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) // Cannot update a system admin unless user making request is a systemadmin also. - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), user.Id) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1113,7 +1113,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { if c.AppContext.Session().IsOAuth { if ouser.Email != user.Email { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) c.Err.DetailedError += ", attempted email update by oauth app" return } @@ -1166,7 +1166,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1178,14 +1178,14 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", ouser) // Cannot update a system admin unless user making request is a systemadmin also - if ouser.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if ouser.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } if c.AppContext.Session().IsOAuth && patch.Email != nil { if ouser.Email != *patch.Email { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) c.Err.DetailedError += ", attempted email update by oauth app" return } @@ -1239,12 +1239,12 @@ func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), userId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } // if EnableUserDeactivation flag is disabled the user cannot deactivate himself. - if c.Params.UserId == c.AppContext.Session().UserId && !*c.App.Config().TeamSettings.EnableUserDeactivation && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.Params.UserId == c.AppContext.Session().UserId && !*c.App.Config().TeamSettings.EnableUserDeactivation && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { c.Err = model.NewAppError("deleteUser", "api.user.update_active.not_enable.app_error", nil, "userId="+c.Params.UserId, http.StatusUnauthorized) return } @@ -1257,8 +1257,8 @@ func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) // Cannot update a system admin unless user making request is a systemadmin also - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -1310,8 +1310,8 @@ func updateUserRoles(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_ROLES) { - c.SetPermissionError(model.PERMISSION_MANAGE_ROLES) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageRoles) { + c.SetPermissionError(model.PermissionManageRoles) return } @@ -1349,7 +1349,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { // true when you're trying to de-activate yourself isSelfDeactive := !active && c.Params.UserId == c.AppContext.Session().UserId - if !isSelfDeactive && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) { + if !isSelfDeactive && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementUsers) { c.Err = model.NewAppError("updateUserActive", "api.user.update_active.permissions.app_error", nil, "userId="+c.Params.UserId, http.StatusForbidden) return } @@ -1367,8 +1367,8 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("user", user) - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -1404,7 +1404,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { }) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ACTIVATION_STATUS_CHANGE, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserActivationStatusChange, "", "", "", nil) c.App.Publish(message) // If activating, run cloud check for limit overages @@ -1421,7 +1421,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { func updateUserAuth(c *Context, w http.ResponseWriter, r *http.Request) { if !c.IsSystemAdmin() { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1505,13 +1505,13 @@ func updateUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if c.AppContext.Session().IsOAuth { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) c.Err.DetailedError += ", attempted access by oauth app" return } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1556,13 +1556,13 @@ func generateMfaSecret(c *Context, w http.ResponseWriter, r *http.Request) { } if c.AppContext.Session().IsOAuth { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) c.Err.DetailedError += ", attempted access by oauth app" return } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1596,9 +1596,9 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) if user.IsSystemAdmin() { - canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) + canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) } else { - canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) + canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementUsers) } } @@ -1646,7 +1646,7 @@ func resetPassword(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) token := props["token"] - if len(token) != model.TOKEN_SIZE { + if len(token) != model.TokenSize { c.SetInvalidParam("token") return } @@ -1781,7 +1781,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { return } - if *c.App.Config().ExperimentalSettings.ClientSideCertCheck == model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH { + if *c.App.Config().ExperimentalSettings.ClientSideCertCheck == model.ClientSideCertCheckPrimaryAuth { loginId = certEmail password = "certificate" } @@ -1823,7 +1823,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(user.Id, "success") - if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML { + if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml { c.App.AttachSessionCookies(c.AppContext, w, r) } @@ -1914,7 +1914,7 @@ func getSessions(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1941,7 +1941,7 @@ func revokeSession(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -1986,7 +1986,7 @@ func revokeAllSessionsForUser(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("user_id", c.Params.UserId) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2002,8 +2002,8 @@ func revokeAllSessionsForUser(c *Context, w http.ResponseWriter, r *http.Request } func revokeAllSessionsAllUsers(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2054,7 +2054,7 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0) sessionCookie := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: c.AppContext.Session().Token, Path: subpath, MaxAge: maxAge, @@ -2091,7 +2091,7 @@ func getUserAudits(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2112,7 +2112,7 @@ func verifyUserEmail(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) token := props["token"] - if len(token) != model.TOKEN_SIZE { + if len(token) != model.TokenSize { c.SetInvalidParam("token") return } @@ -2224,7 +2224,7 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } if c.AppContext.Session().IsOAuth { - c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) + c.SetPermissionError(model.PermissionCreateUserAccessToken) c.Err.DetailedError += ", attempted access by oauth app" return } @@ -2242,13 +2242,13 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateUserAccessToken) { + c.SetPermissionError(model.PermissionCreateUserAccessToken) return } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2269,8 +2269,8 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } props := model.UserAccessTokenSearchFromJson(r.Body) @@ -2294,8 +2294,8 @@ func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) } func getUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2314,13 +2314,13 @@ func getUserAccessTokensForUser(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_READ_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadUserAccessToken) { + c.SetPermissionError(model.PermissionReadUserAccessToken) return } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2339,8 +2339,8 @@ func getUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_READ_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionReadUserAccessToken) { + c.SetPermissionError(model.PermissionReadUserAccessToken) return } @@ -2351,7 +2351,7 @@ func getUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2371,8 +2371,8 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("token_id", tokenId) c.LogAudit("") - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRevokeUserAccessToken) { + c.SetPermissionError(model.PermissionRevokeUserAccessToken) return } @@ -2387,7 +2387,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2416,8 +2416,8 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) c.LogAudit("") // No separate permission for this action for now - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionRevokeUserAccessToken) { + c.SetPermissionError(model.PermissionRevokeUserAccessToken) return } @@ -2432,7 +2432,7 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2461,8 +2461,8 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") // No separate permission for this action for now - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { - c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionCreateUserAccessToken) { + c.SetPermissionError(model.PermissionCreateUserAccessToken) return } @@ -2477,7 +2477,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2551,8 +2551,8 @@ func promoteGuestToUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("promoteGuestToUser", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PROMOTE_GUEST) { - c.SetPermissionError(model.PERMISSION_PROMOTE_GUEST) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionPromoteGuest) { + c.SetPermissionError(model.PermissionPromoteGuest) return } @@ -2596,8 +2596,8 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("demoteUserToGuest", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DEMOTE_TO_GUEST) { - c.SetPermissionError(model.PERMISSION_DEMOTE_TO_GUEST) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionDemoteToGuest) { + c.SetPermissionError(model.PermissionDemoteToGuest) return } @@ -2607,8 +2607,8 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { return } - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2640,13 +2640,13 @@ func publishUserTyping(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.Params.UserId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if c.Params.UserId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } - if !c.App.HasPermissionToChannel(c.Params.UserId, typingRequest.ChannelId, model.PERMISSION_CREATE_POST) { - c.SetPermissionError(model.PERMISSION_CREATE_POST) + if !c.App.HasPermissionToChannel(c.Params.UserId, typingRequest.ChannelId, model.PermissionCreatePost) { + c.SetPermissionError(model.PermissionCreatePost) return } @@ -2674,8 +2674,8 @@ func verifyUserEmailWithoutToken(c *Context, w http.ResponseWriter, r *http.Requ defer c.LogAuditRec(auditRec) auditRec.AddMeta("user_id", user.Id) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2706,8 +2706,8 @@ func convertUserToBot(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("user", user) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2773,8 +2773,8 @@ func migrateAuthToLDAP(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("match_field", matchField) auditRec.AddMeta("force", force) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2832,8 +2832,8 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("matches", matches) auditRec.AddMeta("auto", auto) - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { - c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) { + c.SetPermissionError(model.PermissionManageSystem) return } @@ -2867,7 +2867,7 @@ func getThreadForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } extendedStr := r.URL.Query().Get("extended") @@ -2895,7 +2895,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { } if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2966,7 +2966,7 @@ func updateReadStateThreadByUser(c *Context, w http.ResponseWriter, r *http.Requ auditRec.AddMeta("team_id", c.Params.TeamId) auditRec.AddMeta("timestamp", c.Params.Timestamp) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -2994,7 +2994,7 @@ func unfollowThreadByUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -3022,7 +3022,7 @@ func followThreadByUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -3048,7 +3048,7 @@ func updateReadStateAllThreadsByUser(c *Context, w http.ResponseWriter, r *http. auditRec.AddMeta("team_id", c.Params.TeamId) if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) return } diff --git a/api4/user_local.go b/api4/user_local.go index 71cc9a25e5..bdd19e65a6 100644 --- a/api4/user_local.go +++ b/api4/user_local.go @@ -141,7 +141,7 @@ func localGetUsers(c *Context, w http.ResponseWriter, r *http.Request) { } if etag != "" { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) } w.Write([]byte(model.UserListToJson(profiles))) } @@ -208,7 +208,7 @@ func localGetUser(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.SanitizeProfile(user, c.IsSystemAdmin()) - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } @@ -287,7 +287,7 @@ func localGetUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) } c.App.SanitizeProfile(user, c.IsSystemAdmin()) - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } @@ -316,7 +316,7 @@ func localGetUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.SanitizeProfile(user, c.IsSystemAdmin()) - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.Write([]byte(user.ToJson())) } diff --git a/api4/user_test.go b/api4/user_test.go index fae1ce4746..dfff41765e 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -35,7 +35,7 @@ func TestCreateUser(t *testing.T) { Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), - Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId, EmailVerified: true, } @@ -48,7 +48,7 @@ func TestCreateUser(t *testing.T) { _, _ = th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname, "nickname didn't match") - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "did not clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "did not clear roles") CheckUserSanitization(t, ruser) @@ -213,7 +213,7 @@ func TestCreateUserWithToken(t *testing.T) { defer th.TearDown() t.Run("CreateWithTokenHappyPath", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), @@ -226,7 +226,7 @@ func TestCreateUserWithToken(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) _, err := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after being used") @@ -238,7 +238,7 @@ func TestCreateUserWithToken(t *testing.T) { }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), @@ -251,7 +251,7 @@ func TestCreateUserWithToken(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) _, err := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after being used") @@ -263,7 +263,7 @@ func TestCreateUserWithToken(t *testing.T) { }, "CreateWithTokenHappyPath") t.Run("NoToken", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), @@ -277,7 +277,7 @@ func TestCreateUserWithToken(t *testing.T) { }) t.Run("TokenExpired", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} timeNow := time.Now() past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond) token := model.NewToken( @@ -294,7 +294,7 @@ func TestCreateUserWithToken(t *testing.T) { }) t.Run("WrongToken", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} _, resp := th.Client.CreateUserWithToken(&user, "wrong") CheckNotFoundStatus(t, resp) @@ -308,7 +308,7 @@ func TestCreateUserWithToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = enableUserCreation }) }() - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, @@ -328,7 +328,7 @@ func TestCreateUserWithToken(t *testing.T) { enableUserCreation := th.App.Config().TeamSettings.EnableUserCreation defer th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = enableUserCreation }) - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, @@ -345,7 +345,7 @@ func TestCreateUserWithToken(t *testing.T) { }, "EnableUserCreationDisable") t.Run("EnableOpenServerDisable", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} token := model.NewToken( app.TokenTypeTeamInvitation, @@ -366,7 +366,7 @@ func TestCreateUserWithToken(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) _, err := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after be used") @@ -416,7 +416,7 @@ func TestCreateUserWebSocketEvent(t *testing.T) { defer userWSClient.Close() userWSClient.Listen() - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} inviteId := th.BasicTeam.InviteId @@ -431,11 +431,11 @@ func TestCreateUserWebSocketEvent(t *testing.T) { for { select { case ev := <-userWSClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_NEW_USER { + if ev.EventType() == model.WebsocketEventNewUser { userHasReceived = true } case ev := <-guestWSClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_NEW_USER { + if ev.EventType() == model.WebsocketEventNewUser { guestHasReceived = true } case <-time.After(2 * time.Second): @@ -444,8 +444,8 @@ func TestCreateUserWebSocketEvent(t *testing.T) { } }() - require.Truef(t, userHasReceived, "User should have received %s event", model.WEBSOCKET_EVENT_NEW_USER) - require.Falsef(t, guestHasReceived, "Guest should not have received %s event", model.WEBSOCKET_EVENT_NEW_USER) + require.Truef(t, userHasReceived, "User should have received %s event", model.WebsocketEventNewUser) + require.Falsef(t, guestHasReceived, "Guest should not have received %s event", model.WebsocketEventNewUser) }) } @@ -454,7 +454,7 @@ func TestCreateUserWithInviteId(t *testing.T) { defer th.TearDown() t.Run("CreateWithInviteIdHappyPath", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} inviteId := th.BasicTeam.InviteId @@ -464,11 +464,11 @@ func TestCreateUserWithInviteId(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} inviteId := th.BasicTeam.InviteId @@ -478,12 +478,12 @@ func TestCreateUserWithInviteId(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) }, "CreateWithInviteIdHappyPath") t.Run("GroupConstrainedTeam", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} th.BasicTeam.GroupConstrained = model.NewBool(true) team, err := th.App.UpdateTeam(th.BasicTeam) @@ -502,7 +502,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} th.BasicTeam.GroupConstrained = model.NewBool(true) team, err := th.App.UpdateTeam(th.BasicTeam) @@ -521,7 +521,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }, "GroupConstrainedTeam") t.Run("WrongInviteId", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} inviteId := model.NewId() @@ -531,7 +531,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }) t.Run("NoInviteId", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} _, resp := th.Client.CreateUserWithInviteId(&user, "") CheckBadRequestStatus(t, resp) @@ -539,7 +539,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }) t.Run("ExpiredInviteId", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} inviteId := th.BasicTeam.InviteId @@ -552,7 +552,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }) t.Run("EnableUserCreationDisable", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} enableUserCreation := th.App.Config().TeamSettings.EnableUserCreation defer func() { @@ -568,7 +568,7 @@ func TestCreateUserWithInviteId(t *testing.T) { CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error") }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} enableUserCreation := th.App.Config().TeamSettings.EnableUserCreation defer th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = enableUserCreation }) @@ -582,7 +582,7 @@ func TestCreateUserWithInviteId(t *testing.T) { }, "EnableUserCreationDisable") t.Run("EnableOpenServerDisable", func(t *testing.T) { - user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} enableOpenServer := th.App.Config().TeamSettings.EnableOpenServer defer func() { @@ -601,7 +601,7 @@ func TestCreateUserWithInviteId(t *testing.T) { th.Client.Login(user.Email, user.Password) require.Equal(t, user.Nickname, ruser.Nickname) - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) }) } @@ -765,8 +765,8 @@ func TestGetBotUser(t *testing.T) { defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true @@ -1250,7 +1250,7 @@ func TestAutocompleteUsersInChannel(t *testing.T) { for _, tc := range tt { t.Run(tc.Name, func(t *testing.T) { th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.UserSearchDefaultLimit, "") if tc.ShouldFail { CheckErrorMessage(t, resp, "api.user.autocomplete_users.missing_team_id.app_error") } else { @@ -1263,11 +1263,11 @@ func TestAutocompleteUsersInChannel(t *testing.T) { } th.Client.Logout() - _, resp = th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.UserSearchDefaultLimit, "") CheckUnauthorizedStatus(t, resp) th.Client.Login(newUser.Email, newUser.Password) - _, resp = th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, tc.Username, model.UserSearchDefaultLimit, "") CheckForbiddenStatus(t, resp) }) } @@ -1276,7 +1276,7 @@ func TestAutocompleteUsersInChannel(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false }) th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsersInChannel(teamId, channelId, username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Equal(t, rusers.Users[0].FirstName, "", "should not show first/last name") @@ -1295,7 +1295,7 @@ func TestAutocompleteUsersInChannel(t *testing.T) { th.Client.Login(permissionsUser.Email, permissionsUser.Password) - rusers, resp := th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Len(t, rusers.OutOfChannel, 1) @@ -1304,22 +1304,22 @@ func TestAutocompleteUsersInChannel(t *testing.T) { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) - rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Empty(t, rusers.OutOfChannel) th.App.GetOrCreateDirectChannel(th.Context, permissionsUser.Id, otherUser.Id) - rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Len(t, rusers.OutOfChannel, 1) }) t.Run("user must have access to team id, especially when it does not match channel's team id", func(t *testing.T) { - _, resp := th.Client.AutocompleteUsersInChannel("otherTeamId", channelId, username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp := th.Client.AutocompleteUsersInChannel("otherTeamId", channelId, username, model.UserSearchDefaultLimit, "") CheckErrorMessage(t, resp, "api.context.permissions.app_error") }) } @@ -1364,7 +1364,7 @@ func TestAutocompleteUsersInTeam(t *testing.T) { for _, tc := range tt { t.Run(tc.Name, func(t *testing.T) { th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) if tc.MoreThan { assert.True(t, len(rusers.Users) >= tc.ExpectedResults) @@ -1372,11 +1372,11 @@ func TestAutocompleteUsersInTeam(t *testing.T) { assert.Len(t, rusers.Users, tc.ExpectedResults) } th.Client.Logout() - _, resp = th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.UserSearchDefaultLimit, "") CheckUnauthorizedStatus(t, resp) th.Client.Login(newUser.Email, newUser.Password) - _, resp = th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsersInTeam(tc.TeamId, tc.Username, model.UserSearchDefaultLimit, "") CheckForbiddenStatus(t, resp) }) } @@ -1385,7 +1385,7 @@ func TestAutocompleteUsersInTeam(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false }) th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsersInTeam(teamId, username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsersInTeam(teamId, username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Equal(t, rusers.Users[0].FirstName, "", "should not show first/last name") @@ -1428,7 +1428,7 @@ func TestAutocompleteUsers(t *testing.T) { for _, tc := range tt { t.Run(tc.Name, func(t *testing.T) { th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsers(tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsers(tc.Username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) if tc.MoreThan { assert.True(t, len(rusers.Users) >= tc.ExpectedResults) @@ -1437,11 +1437,11 @@ func TestAutocompleteUsers(t *testing.T) { } th.Client.Logout() - _, resp = th.Client.AutocompleteUsers(tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsers(tc.Username, model.UserSearchDefaultLimit, "") CheckUnauthorizedStatus(t, resp) th.Client.Login(newUser.Email, newUser.Password) - _, resp = th.Client.AutocompleteUsers(tc.Username, model.USER_SEARCH_DEFAULT_LIMIT, "") + _, resp = th.Client.AutocompleteUsers(tc.Username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) }) } @@ -1450,7 +1450,7 @@ func TestAutocompleteUsers(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false }) th.LoginBasic() - rusers, resp := th.Client.AutocompleteUsers(username, model.USER_SEARCH_DEFAULT_LIMIT, "") + rusers, resp := th.Client.AutocompleteUsers(username, model.UserSearchDefaultLimit, "") CheckNoError(t, resp) assert.Equal(t, rusers.Users[0].FirstName, "", "should not show first/last name") @@ -1642,7 +1642,7 @@ func TestUpdateUser(t *testing.T) { th.Client.Login(user.Email, user.Password) user.Nickname = "Joram Wilander" - user.Roles = model.SYSTEM_USER_ROLE_ID + user.Roles = model.SystemUserRoleId user.LastPasswordUpdate = 123 ruser, resp := th.Client.UpdateUser(user) @@ -1650,7 +1650,7 @@ func TestUpdateUser(t *testing.T) { CheckUserSanitization(t, ruser) require.Equal(t, "Joram Wilander", ruser.Nickname, "Nickname should update properly") - require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "Roles should not update") + require.Equal(t, model.SystemUserRoleId, ruser.Roles, "Roles should not update") require.NotEqual(t, 123, ruser.LastPasswordUpdate, "LastPasswordUpdate should not update") ruser.Email = th.GenerateTestEmail() @@ -1713,7 +1713,7 @@ func TestPatchUser(t *testing.T) { t.Run("Timezone limit error", func(t *testing.T) { patch := &model.UserPatch{} patch.Timezone = model.StringMap{} - patch.Timezone["manualTimezone"] = string(make([]byte, model.USER_TIMEZONE_MAX_RUNES)) + patch.Timezone["manualTimezone"] = string(make([]byte, model.UserTimezoneMaxRunes)) ruser, resp := th.Client.PatchUser(user.Id, patch) CheckBadRequestStatus(t, resp) require.Equal(t, "model.user.is_valid.timezone_limit.app_error", resp.Error.Id) @@ -1820,7 +1820,7 @@ func TestUserUnicodeNames(t *testing.T) { Nickname: "Ender\u2028 Wiggin", Password: "hello1", Username: "\ufeffwiggin77", - Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} ruser, resp := Client.CreateUser(&user) CheckNoError(t, resp) @@ -1829,7 +1829,7 @@ func TestUserUnicodeNames(t *testing.T) { _, _ = Client.Login(user.Email, user.Password) require.Equal(t, "wiggin77", ruser.Username, "Bad Unicode not filtered from username") - require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.SHOW_FULLNAME), "Bad Unicode not filtered from displayname") + require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.ShowFullName), "Bad Unicode not filtered from displayname") require.Equal(t, "Ender Wiggin", ruser.Nickname, "Bad Unicode not filtered from nickname") }) @@ -1847,7 +1847,7 @@ func TestUserUnicodeNames(t *testing.T) { require.Equal(t, "wiggin", ruser.Username, "bad unicode should be filtered from username") require.Equal(t, "Ender Wiggin", ruser.Nickname, "bad unicode should be filtered from nickname") - require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.SHOW_FULLNAME), "bad unicode should be filtered from display name") + require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.ShowFullName), "bad unicode should be filtered from display name") }) t.Run("patch user unicode", func(t *testing.T) { @@ -1866,7 +1866,7 @@ func TestUserUnicodeNames(t *testing.T) { require.Equal(t, "Ender Wiggin", ruser.Nickname, "Bad unicode should be filtered from nickname") require.Equal(t, "Andrew", ruser.FirstName, "Bad unicode should be filtered from first name") require.Equal(t, "Wiggin", ruser.LastName, "Bad unicode should be filtered from last name") - require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.SHOW_FULLNAME), "Bad unicode should be filtered from display name") + require.Equal(t, "Andrew Wiggin", ruser.GetDisplayName(model.ShowFullName), "Bad unicode should be filtered from display name") }) } @@ -1892,14 +1892,14 @@ func TestUpdateUserAuth(t *testing.T) { require.NotNil(t, respErr, "Shouldn't have permissions. Only Admins") userAuth.AuthData = model.NewString("test@test.com") - userAuth.AuthService = model.USER_AUTH_SERVICE_SAML + userAuth.AuthService = model.UserAuthServiceSaml userAuth.Password = "newpassword" ruser, resp := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth) CheckNoError(t, resp) // AuthData and AuthService are set, password is set to empty require.Equal(t, *userAuth.AuthData, *ruser.AuthData) - require.Equal(t, model.USER_AUTH_SERVICE_SAML, ruser.AuthService) + require.Equal(t, model.UserAuthServiceSaml, ruser.AuthService) require.Empty(t, ruser.Password) // When AuthData or AuthService are empty, password must be valid @@ -2025,14 +2025,14 @@ func TestPermanentDeleteAllUsers(t *testing.T) { DisplayName: "User Created Team", Name: "user-created-team", Email: "usercreatedteam@test.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }, th.BasicUser.Id) require.Nil(t, err) channel, err := th.App.CreateChannelWithUser(th.Context, &model.Channel{ DisplayName: "User Created Channel", Name: "user-created-channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, }, th.BasicUser.Id) require.Nil(t, err) @@ -2074,23 +2074,23 @@ func TestUpdateUserRoles(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, resp := th.Client.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID) + _, resp := th.Client.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId) CheckForbiddenStatus(t, resp) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - _, resp = client.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID) + _, resp = client.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId) CheckNoError(t, resp) - _, resp = client.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID) + _, resp = client.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId) CheckNoError(t, resp) _, resp = client.UpdateUserRoles(th.BasicUser.Id, "junk") CheckBadRequestStatus(t, resp) - _, resp = client.UpdateUserRoles("junk", model.SYSTEM_USER_ROLE_ID) + _, resp = client.UpdateUserRoles("junk", model.SystemUserRoleId) CheckBadRequestStatus(t, resp) - _, resp = client.UpdateUserRoles(model.NewId(), model.SYSTEM_USER_ROLE_ID) + _, resp = client.UpdateUserRoles(model.NewId(), model.SystemUserRoleId) CheckBadRequestStatus(t, resp) }) } @@ -2111,7 +2111,7 @@ func assertExpectedWebsocketEvent(t *testing.T, client *model.WebSocketClient, e } func assertWebsocketEventUserUpdatedWithEmail(t *testing.T, client *model.WebSocketClient, email string) { - assertExpectedWebsocketEvent(t, client, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, client, model.WebsocketEventUserUpdated, func(event *model.WebSocketEvent) { eventUser, ok := event.GetData()["user"].(*model.User) require.True(t, ok, "expected user") assert.Equal(t, email, eventUser.Email) @@ -2233,7 +2233,7 @@ func TestUpdateUserActive(t *testing.T) { time.Sleep(300 * time.Millisecond) resp := <-webSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) adminWebSocketClient, err := th.CreateWebSocketSystemAdminClient() assert.Nil(t, err) @@ -2243,7 +2243,7 @@ func TestUpdateUserActive(t *testing.T) { time.Sleep(300 * time.Millisecond) resp = <-adminWebSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) // Verify that both admins and regular users see the email when privacy settings allow same, // and confirm event is fired for SystemAdmin and Local mode @@ -2651,7 +2651,7 @@ func TestGetUsersInGroup(t *testing.T) { CheckForbiddenStatus(t, response) }) - user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId}) assert.Nil(t, err) _, err = th.App.UpsertGroupMember(group.Id, user1.Id) assert.Nil(t, err) @@ -2963,7 +2963,7 @@ func TestResetPassword(t *testing.T) { loc := strings.Index(resultsEmail.Body.Text, "token=") require.NotEqual(t, -1, loc, "Code should be found in email") loc += 6 - recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] + recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TokenSize] } recoveryToken, err := th.App.Srv().Store.Token().GetByToken(recoveryTokenString) require.NoError(t, err, "Recovery token not found (%s)", recoveryTokenString) @@ -2977,7 +2977,7 @@ func TestResetPassword(t *testing.T) { _, resp = th.Client.ResetPassword("junk", "newpwd") CheckBadRequestStatus(t, resp) code := "" - for i := 0; i < model.TOKEN_SIZE; i++ { + for i := 0; i < model.TokenSize; i++ { code += "a" } _, resp = th.Client.ResetPassword(code, "newpwd") @@ -3167,7 +3167,7 @@ func TestAttachDeviceId(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - deviceId := model.PUSH_NOTIFY_APPLE + ":1234567890" + deviceId := model.PushNotifyApple + ":1234567890" t.Run("success", func(t *testing.T) { testCases := []struct { @@ -3240,7 +3240,7 @@ func TestVerifyUserEmail(t *testing.T) { defer th.TearDown() email := th.GenerateTestEmail() - user := model.User{Email: email, Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: email, Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} ruser, _ := th.Client.CreateUser(&user) @@ -3429,8 +3429,8 @@ func TestLoginWithLag(t *testing.T) { t.Skipf("requires test flag: -mysql-replica") } - if *th.App.Srv().Config().SqlSettings.DriverName != model.DATABASE_DRIVER_MYSQL { - t.Skipf("requires %q database driver", model.DATABASE_DRIVER_MYSQL) + if *th.App.Srv().Config().SqlSettings.DriverName != model.DatabaseDriverMysql { + t.Skipf("requires %q database driver", model.DatabaseDriverMysql) } mainHelper.SQLStore.UpdateLicense(model.NewTestLicense("ldap")) @@ -3463,7 +3463,7 @@ func TestLoginCookies(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.Client.HttpHeader[model.HEADER_REQUESTED_WITH] = model.HEADER_REQUESTED_WITH_XML + th.Client.HttpHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXml user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) @@ -3472,11 +3472,11 @@ func TestLoginCookies(t *testing.T) { csrfCookie := "" for _, cookie := range resp.Header["Set-Cookie"] { - if match := regexp.MustCompile("^" + model.SESSION_COOKIE_TOKEN + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { + if match := regexp.MustCompile("^" + model.SessionCookieToken + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { sessionCookie = match[1] - } else if match := regexp.MustCompile("^" + model.SESSION_COOKIE_USER + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { + } else if match := regexp.MustCompile("^" + model.SessionCookieUser + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { userCookie = match[1] - } else if match := regexp.MustCompile("^" + model.SESSION_COOKIE_CSRF + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { + } else if match := regexp.MustCompile("^" + model.SessionCookieCsrf + "=([a-z0-9]+)").FindStringSubmatch(cookie); match != nil { csrfCookie = match[1] } } @@ -3501,7 +3501,7 @@ func TestLoginCookies(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.Client.HttpHeader[model.HEADER_REQUESTED_WITH] = model.HEADER_REQUESTED_WITH_XML + th.Client.HttpHeader[model.HeaderRequestedWith] = model.HeaderRequestedWithXml testCases := []struct { Description string @@ -3541,7 +3541,7 @@ func TestCBALogin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.ClientSideCertEnable = true - *cfg.ExperimentalSettings.ClientSideCertCheck = model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH + *cfg.ExperimentalSettings.ClientSideCertCheck = model.ClientSideCertCheckPrimaryAuth }) t.Run("missing cert header", func(t *testing.T) { @@ -3601,7 +3601,7 @@ func TestCBALogin(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.ClientSideCertEnable = true - *cfg.ExperimentalSettings.ClientSideCertCheck = model.CLIENT_SIDE_CERT_CHECK_SECONDARY_AUTH + *cfg.ExperimentalSettings.ClientSideCertCheck = model.ClientSideCertCheckSecondaryAuth }) t.Run("password required", func(t *testing.T) { @@ -3648,8 +3648,8 @@ func TestSwitchAccount(t *testing.T) { th.Client.Logout() sr := &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_EMAIL, - NewService: model.USER_AUTH_SERVICE_GITLAB, + CurrentService: model.UserAuthServiceEmail, + NewService: model.UserAuthServiceGitlab, Email: th.BasicUser.Email, Password: th.BasicUser.Password, } @@ -3663,8 +3663,8 @@ func TestSwitchAccount(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false }) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_EMAIL, - NewService: model.USER_AUTH_SERVICE_GITLAB, + CurrentService: model.UserAuthServiceEmail, + NewService: model.UserAuthServiceGitlab, } _, resp = th.Client.SwitchAccountType(sr) @@ -3673,8 +3673,8 @@ func TestSwitchAccount(t *testing.T) { th.LoginBasic() sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_SAML, - NewService: model.USER_AUTH_SERVICE_EMAIL, + CurrentService: model.UserAuthServiceSaml, + NewService: model.UserAuthServiceEmail, Email: th.BasicUser.Email, NewPassword: th.BasicUser.Password, } @@ -3683,16 +3683,16 @@ func TestSwitchAccount(t *testing.T) { CheckForbiddenStatus(t, resp) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_EMAIL, - NewService: model.USER_AUTH_SERVICE_LDAP, + CurrentService: model.UserAuthServiceEmail, + NewService: model.UserAuthServiceLdap, } _, resp = th.Client.SwitchAccountType(sr) CheckForbiddenStatus(t, resp) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_LDAP, - NewService: model.USER_AUTH_SERVICE_EMAIL, + CurrentService: model.UserAuthServiceLdap, + NewService: model.UserAuthServiceEmail, } _, resp = th.Client.SwitchAccountType(sr) @@ -3703,12 +3703,12 @@ func TestSwitchAccount(t *testing.T) { th.LoginBasic() fakeAuthData := model.NewId() - _, err := th.App.Srv().Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true) + _, err := th.App.Srv().Store.User().UpdateAuthData(th.BasicUser.Id, model.UserAuthServiceGitlab, &fakeAuthData, th.BasicUser.Email, true) require.NoError(t, err) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_GITLAB, - NewService: model.USER_AUTH_SERVICE_EMAIL, + CurrentService: model.UserAuthServiceGitlab, + NewService: model.UserAuthServiceEmail, Email: th.BasicUser.Email, NewPassword: th.BasicUser.Password, } @@ -3724,16 +3724,16 @@ func TestSwitchAccount(t *testing.T) { th.Client.Logout() sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_GITLAB, - NewService: model.SERVICE_GOOGLE, + CurrentService: model.UserAuthServiceGitlab, + NewService: model.ServiceGoogle, } _, resp = th.Client.SwitchAccountType(sr) CheckBadRequestStatus(t, resp) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_EMAIL, - NewService: model.USER_AUTH_SERVICE_GITLAB, + CurrentService: model.UserAuthServiceEmail, + NewService: model.UserAuthServiceGitlab, Password: th.BasicUser.Password, } @@ -3741,8 +3741,8 @@ func TestSwitchAccount(t *testing.T) { CheckNotFoundStatus(t, resp) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_EMAIL, - NewService: model.USER_AUTH_SERVICE_GITLAB, + CurrentService: model.UserAuthServiceEmail, + NewService: model.UserAuthServiceGitlab, Email: th.BasicUser.Email, } @@ -3750,8 +3750,8 @@ func TestSwitchAccount(t *testing.T) { CheckUnauthorizedStatus(t, resp) sr = &model.SwitchRequest{ - CurrentService: model.USER_AUTH_SERVICE_GITLAB, - NewService: model.USER_AUTH_SERVICE_EMAIL, + CurrentService: model.UserAuthServiceGitlab, + NewService: model.UserAuthServiceEmail, Email: th.BasicUser.Email, NewPassword: th.BasicUser.Password, } @@ -3843,7 +3843,7 @@ func TestCreateUserAccessToken(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { _, resp := client.CreateUserAccessToken(th.BasicUser.Id, "test token") @@ -3856,7 +3856,7 @@ func TestCreateUserAccessToken(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) rtoken, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -3917,9 +3917,9 @@ func TestCreateUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -3933,14 +3933,14 @@ func TestCreateUserAccessToken(t *testing.T) { defer th.App.PermanentDeleteBot(createdBot.UserId) t.Run("without MANAGE_BOT permission", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageBots.Id, model.TeamUserRoleId) _, resp = th.Client.CreateUserAccessToken(createdBot.UserId, "test token") CheckForbiddenStatus(t, resp) }) t.Run("with MANAGE_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) token, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token") CheckNoError(t, resp) @@ -3956,10 +3956,10 @@ func TestCreateUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -3978,7 +3978,7 @@ func TestCreateUserAccessToken(t *testing.T) { }) t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) rtoken, resp := th.Client.CreateUserAccessToken(createdBot.UserId, "test token") CheckNoError(t, resp) @@ -4015,7 +4015,7 @@ func TestGetUserAccessToken(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -4035,7 +4035,7 @@ func TestGetUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -4056,11 +4056,11 @@ func TestGetUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4077,14 +4077,14 @@ func TestGetUserAccessToken(t *testing.T) { CheckNoError(t, resp) t.Run("without MANAGE_BOTS permission", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageBots.Id, model.TeamUserRoleId) _, resp := th.Client.GetUserAccessToken(token.Id) CheckForbiddenStatus(t, resp) }) t.Run("with MANAGE_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) returnedToken, resp := th.Client.GetUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4102,11 +4102,11 @@ func TestGetUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionReadUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4128,7 +4128,7 @@ func TestGetUserAccessToken(t *testing.T) { }) t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) returnedToken, resp := th.Client.GetUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4147,7 +4147,7 @@ func TestGetUserAccessTokensForUser(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) _, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -4172,7 +4172,7 @@ func TestGetUserAccessTokensForUser(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) _, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -4199,7 +4199,7 @@ func TestGetUserAccessTokens(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) _, resp := th.Client.GetUserAccessTokens(0, 100) CheckForbiddenStatus(t, resp) @@ -4211,7 +4211,7 @@ func TestGetUserAccessTokens(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) _, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2") CheckNoError(t, resp) @@ -4231,7 +4231,7 @@ func TestGetUserAccessTokens(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) _, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token 2") CheckNoError(t, resp) @@ -4254,7 +4254,7 @@ func TestSearchUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckNoError(t, resp) @@ -4289,7 +4289,7 @@ func TestRevokeUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { token, resp := client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) @@ -4324,11 +4324,11 @@ func TestRevokeUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4345,14 +4345,14 @@ func TestRevokeUserAccessToken(t *testing.T) { CheckNoError(t, resp) t.Run("without MANAGE_BOTS permission", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageBots.Id, model.TeamUserRoleId) _, resp := th.Client.RevokeUserAccessToken(token.Id) CheckForbiddenStatus(t, resp) }) t.Run("with MANAGE_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) ok, resp := th.Client.RevokeUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4367,11 +4367,11 @@ func TestRevokeUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4393,7 +4393,7 @@ func TestRevokeUserAccessToken(t *testing.T) { }) t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) ok, resp := th.Client.RevokeUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4409,7 +4409,7 @@ func TestDisableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) assertToken(t, th, token, th.BasicUser.Id) @@ -4442,11 +4442,11 @@ func TestDisableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4463,14 +4463,14 @@ func TestDisableUserAccessToken(t *testing.T) { CheckNoError(t, resp) t.Run("without MANAGE_BOTS permission", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageBots.Id, model.TeamUserRoleId) _, resp := th.Client.DisableUserAccessToken(token.Id) CheckForbiddenStatus(t, resp) }) t.Run("with MANAGE_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) ok, resp := th.Client.DisableUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4485,11 +4485,11 @@ func TestDisableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4511,7 +4511,7 @@ func TestDisableUserAccessToken(t *testing.T) { }) t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) ok, resp := th.Client.DisableUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4527,7 +4527,7 @@ func TestEnableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, "test token") CheckNoError(t, resp) assertToken(t, th, token, th.BasicUser.Id) @@ -4570,11 +4570,11 @@ func TestEnableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4595,14 +4595,14 @@ func TestEnableUserAccessToken(t *testing.T) { assert.True(t, ok, "should have passed") t.Run("without MANAGE_BOTS permission", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageBots.Id, model.TeamUserRoleId) _, resp := th.Client.EnableUserAccessToken(token.Id) CheckForbiddenStatus(t, resp) }) t.Run("with MANAGE_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) ok, resp := th.Client.EnableUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4617,11 +4617,11 @@ func TestEnableUserAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions()) - th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, model.TEAM_USER_ROLE_ID) - th.App.UpdateUserRoles(th.BasicUser.Id, model.TEAM_USER_ROLE_ID, false) + th.AddPermissionToRole(model.PermissionCreateBot.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageBots.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionCreateUserAccessToken.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionRevokeUserAccessToken.Id, model.TeamUserRoleId) + th.App.UpdateUserRoles(th.BasicUser.Id, model.TeamUserRoleId, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) @@ -4647,7 +4647,7 @@ func TestEnableUserAccessToken(t *testing.T) { }) t.Run("with MANAGE_OTHERS_BOTS permission", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_OTHERS_BOTS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOthersBots.Id, model.TeamUserRoleId) ok, resp := th.Client.EnableUserAccessToken(token.Id) CheckNoError(t, resp) @@ -4664,7 +4664,7 @@ func TestUserAccessTokenInactiveUser(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckNoError(t, resp) @@ -4686,7 +4686,7 @@ func TestUserAccessTokenDisableConfig(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) - th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) + th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId+" "+model.SystemUserAccessTokenRoleId, false) token, resp := th.Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckNoError(t, resp) @@ -4737,7 +4737,7 @@ func TestGetUsersByStatus(t *testing.T) { DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err, "failed to create team") @@ -4745,7 +4745,7 @@ func TestGetUsersByStatus(t *testing.T) { channel, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, CreatorId: model.NewId(), }, false) @@ -4775,14 +4775,14 @@ func TestGetUsersByStatus(t *testing.T) { } // Creating these out of order in case that affects results - offlineUser1 := createUserWithStatus("offline1", model.STATUS_OFFLINE) - offlineUser2 := createUserWithStatus("offline2", model.STATUS_OFFLINE) - awayUser1 := createUserWithStatus("away1", model.STATUS_AWAY) - awayUser2 := createUserWithStatus("away2", model.STATUS_AWAY) - onlineUser1 := createUserWithStatus("online1", model.STATUS_ONLINE) - onlineUser2 := createUserWithStatus("online2", model.STATUS_ONLINE) - dndUser1 := createUserWithStatus("dnd1", model.STATUS_DND) - dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND) + offlineUser1 := createUserWithStatus("offline1", model.StatusOffline) + offlineUser2 := createUserWithStatus("offline2", model.StatusOffline) + awayUser1 := createUserWithStatus("away1", model.StatusAway) + awayUser2 := createUserWithStatus("away2", model.StatusAway) + onlineUser1 := createUserWithStatus("online1", model.StatusOnline) + onlineUser2 := createUserWithStatus("online2", model.StatusOnline) + dndUser1 := createUserWithStatus("dnd1", model.StatusDnd) + dndUser2 := createUserWithStatus("dnd2", model.StatusDnd) client := th.CreateClient() _, resp := client.Login(onlineUser2.Username, "Password1") @@ -5014,7 +5014,7 @@ func TestDemoteUserToGuest(t *testing.T) { time.Sleep(300 * time.Millisecond) resp := <-webSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) adminWebSocketClient, err := th.CreateWebSocketSystemAdminClient() assert.Nil(t, err) @@ -5024,7 +5024,7 @@ func TestDemoteUserToGuest(t *testing.T) { time.Sleep(300 * time.Millisecond) resp = <-adminWebSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) _, respErr := th.SystemAdminClient.GetUser(user.Id, "") CheckNoError(t, respErr) @@ -5032,12 +5032,12 @@ func TestDemoteUserToGuest(t *testing.T) { CheckNoError(t, respErr) defer th.SystemAdminClient.PromoteGuestToUser(user.Id) - assertExpectedWebsocketEvent(t, webSocketClient, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, webSocketClient, model.WebsocketEventUserUpdated, func(event *model.WebSocketEvent) { eventUser, ok := event.GetData()["user"].(*model.User) require.True(t, ok, "expected user") assert.Equal(t, "system_guest", eventUser.Roles) }) - assertExpectedWebsocketEvent(t, adminWebSocketClient, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, adminWebSocketClient, model.WebsocketEventUserUpdated, func(event *model.WebSocketEvent) { eventUser, ok := event.GetData()["user"].(*model.User) require.True(t, ok, "expected user") assert.Equal(t, "system_guest", eventUser.Roles) @@ -5058,7 +5058,7 @@ func TestPromoteGuestToUser(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense()) user := th.BasicUser - th.App.UpdateUserRoles(user.Id, model.SYSTEM_GUEST_ROLE_ID, false) + th.App.UpdateUserRoles(user.Id, model.SystemGuestRoleId, false) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { _, respErr := c.GetUser(user.Id, "") @@ -5079,7 +5079,7 @@ func TestPromoteGuestToUser(t *testing.T) { time.Sleep(300 * time.Millisecond) resp := <-webSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) adminWebSocketClient, err := th.CreateWebSocketSystemAdminClient() assert.Nil(t, err) @@ -5089,7 +5089,7 @@ func TestPromoteGuestToUser(t *testing.T) { time.Sleep(300 * time.Millisecond) resp = <-adminWebSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, resp.Status) + require.Equal(t, model.StatusOk, resp.Status) _, respErr := th.SystemAdminClient.GetUser(user.Id, "") CheckNoError(t, respErr) @@ -5097,12 +5097,12 @@ func TestPromoteGuestToUser(t *testing.T) { CheckNoError(t, respErr) defer th.SystemAdminClient.DemoteUserToGuest(user.Id) - assertExpectedWebsocketEvent(t, webSocketClient, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, webSocketClient, model.WebsocketEventUserUpdated, func(event *model.WebSocketEvent) { eventUser, ok := event.GetData()["user"].(*model.User) require.True(t, ok, "expected user") assert.Equal(t, "system_user", eventUser.Roles) }) - assertExpectedWebsocketEvent(t, adminWebSocketClient, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, adminWebSocketClient, model.WebsocketEventUserUpdated, func(event *model.WebSocketEvent) { eventUser, ok := event.GetData()["user"].(*model.User) require.True(t, ok, "expected user") assert.Equal(t, "system_user", eventUser.Roles) @@ -5116,7 +5116,7 @@ func TestVerifyUserEmailWithoutToken(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { email := th.GenerateTestEmail() - user := model.User{Email: email, Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID} + user := model.User{Email: email, Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SystemUserRoleId} ruser, _ := th.Client.CreateUser(&user) vuser, resp := client.VerifyUserEmailWithoutToken(ruser.Id) @@ -5148,7 +5148,7 @@ func TestGetKnownUsers(t *testing.T) { DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err, "failed to create team") @@ -5156,7 +5156,7 @@ func TestGetKnownUsers(t *testing.T) { DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err, "failed to create team") @@ -5164,14 +5164,14 @@ func TestGetKnownUsers(t *testing.T) { DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err, "failed to create team") c1, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: t1.Id, CreatorId: model.NewId(), }, false) @@ -5180,7 +5180,7 @@ func TestGetKnownUsers(t *testing.T) { c2, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: t2.Id, CreatorId: model.NewId(), }, false) @@ -5189,7 +5189,7 @@ func TestGetKnownUsers(t *testing.T) { c3, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: t3.Id, CreatorId: model.NewId(), }, false) @@ -5282,12 +5282,12 @@ func TestPublishUserTyping(t *testing.T) { time.Sleep(300 * time.Millisecond) wsResp := <-webSocketClient.ResponseChannel - require.Equal(t, model.STATUS_OK, wsResp.Status) + require.Equal(t, model.StatusOk, wsResp.Status) _, resp := th.SystemAdminClient.PublishUserTyping(th.BasicUser2.Id, tr) CheckNoError(t, resp) - assertExpectedWebsocketEvent(t, webSocketClient, model.WEBSOCKET_EVENT_TYPING, func(resp *model.WebSocketEvent) { + assertExpectedWebsocketEvent(t, webSocketClient, model.WebsocketEventTyping, func(resp *model.WebSocketEvent) { assert.Equal(t, th.BasicChannel.Id, resp.GetBroadcast().ChannelId) eventUserId, ok := resp.GetData()["user_id"].(string) @@ -5376,8 +5376,8 @@ func TestUpdatePassword(t *testing.T) { }) t.Run("OK when request performed by system user with requisite system permission, except if requested user is system admin", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS.Id, model.SYSTEM_USER_ROLE_ID) - defer th.RemovePermissionFromRole(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId) + defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId) res := th.Client.UpdatePassword(th.TeamAdminUser.Id, "Pa$$word11", "foobar") CheckOKStatus(t, res) @@ -5400,7 +5400,7 @@ func TestGetThreadsForUser(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) t.Run("empty", func(t *testing.T) { Client := th.Client @@ -5630,7 +5630,7 @@ func TestThreadSocketEvents(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) userWSClient, err := th.CreateWebSocketClient() @@ -5655,7 +5655,7 @@ func TestThreadSocketEvents(t *testing.T) { for { select { case ev := <-userWSClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_THREAD_UPDATED { + if ev.EventType() == model.WebsocketEventThreadUpdated { caught = true thread, err := model.ThreadResponseFromJson(ev.GetData()["thread"].(string)) require.NoError(t, err) @@ -5670,7 +5670,7 @@ func TestThreadSocketEvents(t *testing.T) { } } }() - require.Truef(t, caught, "User should have received %s event", model.WEBSOCKET_EVENT_THREAD_UPDATED) + require.Truef(t, caught, "User should have received %s event", model.WebsocketEventThreadUpdated) }) resp = th.Client.UpdateThreadFollowForUser(th.BasicUser.Id, th.BasicTeam.Id, rpost.Id, false) @@ -5683,7 +5683,7 @@ func TestThreadSocketEvents(t *testing.T) { for { select { case ev := <-userWSClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_THREAD_FOLLOW_CHANGED { + if ev.EventType() == model.WebsocketEventThreadFollowChanged { caught = true require.Equal(t, ev.GetData()["state"], false) require.Equal(t, ev.GetData()["reply_count"], float64(1)) @@ -5693,7 +5693,7 @@ func TestThreadSocketEvents(t *testing.T) { } } }() - require.Truef(t, caught, "User should have received %s event", model.WEBSOCKET_EVENT_THREAD_FOLLOW_CHANGED) + require.Truef(t, caught, "User should have received %s event", model.WebsocketEventThreadFollowChanged) }) _, resp = th.Client.UpdateThreadReadForUser(th.BasicUser.Id, th.BasicTeam.Id, rpost.Id, 123) @@ -5706,7 +5706,7 @@ func TestThreadSocketEvents(t *testing.T) { for { select { case ev := <-userWSClient.EventChannel: - if ev.EventType() == model.WEBSOCKET_EVENT_THREAD_READ_CHANGED { + if ev.EventType() == model.WebsocketEventThreadReadChanged { caught = true require.EqualValues(t, ev.GetData()["timestamp"], 123) } @@ -5716,7 +5716,7 @@ func TestThreadSocketEvents(t *testing.T) { } }() - require.Truef(t, caught, "User should have received %s event", model.WEBSOCKET_EVENT_THREAD_READ_CHANGED) + require.Truef(t, caught, "User should have received %s event", model.WebsocketEventThreadReadChanged) }) } @@ -5804,7 +5804,7 @@ func TestMaintainUnreadRepliesInThread(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client @@ -5861,7 +5861,7 @@ func TestThreadCounts(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client @@ -5907,7 +5907,7 @@ func TestSingleThreadGet(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client @@ -5947,7 +5947,7 @@ func TestMaintainUnreadMentionsInThread(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) checkThreadList := func(client *model.Client4, userId string, expectedMentions, expectedThreads int) (*model.Threads, *model.Response) { uss, resp := client.GetUserThreads(userId, th.BasicTeam.Id, model.GetUserThreadsOpts{ @@ -6011,7 +6011,7 @@ func TestReadThreads(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client t.Run("all threads", func(t *testing.T) { @@ -6080,7 +6080,7 @@ func TestMarkThreadUnreadMentionCount(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) Client := th.Client @@ -6118,7 +6118,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { t.Run("LDAP user", func(t *testing.T) { th := SetupEnterprise(t).InitBasic() defer th.TearDown() - user := th.CreateUserWithAuth(model.USER_AUTH_SERVICE_LDAP) + user := th.CreateUserWithAuth(model.UserAuthServiceLdap) ldapMock := &mocks.LdapInterface{} ldapMock.Mock.On( "CheckProviderAttributes", @@ -6142,7 +6142,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SamlSettings.EnableSyncWithLdap = true }) - user := th.CreateUserWithAuth(model.USER_AUTH_SERVICE_SAML) + user := th.CreateUserWithAuth(model.UserAuthServiceSaml) ldapMock := &mocks.LdapInterface{} ldapMock.Mock.On( "CheckProviderAttributes", mock.Anything, mock.Anything, mock.Anything, @@ -6156,7 +6156,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { t.Run("without LDAP sync", func(t *testing.T) { th := SetupEnterprise(t).InitBasic() defer th.TearDown() - user := th.CreateUserWithAuth(model.USER_AUTH_SERVICE_SAML) + user := th.CreateUserWithAuth(model.UserAuthServiceSaml) samlMock := &mocks.SamlInterface{} samlMock.Mock.On( "CheckProviderAttributes", mock.Anything, mock.Anything, mock.Anything, @@ -6171,7 +6171,7 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { t.Run("OpenID user", func(t *testing.T) { th := SetupEnterprise(t).InitBasic() defer th.TearDown() - user := th.CreateUserWithAuth(model.SERVICE_OPENID) + user := th.CreateUserWithAuth(model.ServiceOpenid) // OAUTH users cannot change these fields for _, fieldName := range []string{ "FirstName", @@ -6188,9 +6188,9 @@ func TestPatchAndUpdateWithProviderAttributes(t *testing.T) { defer th.TearDown() // For non-email users, the username must be changed through the provider for _, authService := range []string{ - model.USER_AUTH_SERVICE_LDAP, - model.USER_AUTH_SERVICE_SAML, - model.SERVICE_OPENID, + model.UserAuthServiceLdap, + model.UserAuthServiceSaml, + model.ServiceOpenid, } { user := th.CreateUserWithAuth(authService) patch := &model.UserPatch{Username: model.NewString("something new")} @@ -6244,7 +6244,7 @@ func TestSetProfileImageWithProviderAttributes(t *testing.T) { th := SetupEnterprise(t).InitBasic() defer th.TearDown() th.SetupLdapConfig() - user := th.CreateUserWithAuth(model.USER_AUTH_SERVICE_LDAP) + user := th.CreateUserWithAuth(model.UserAuthServiceLdap) for _, testCase := range testCases { doImageTest(t, th, user, testCase) } @@ -6256,7 +6256,7 @@ func TestSetProfileImageWithProviderAttributes(t *testing.T) { defer th.TearDown() th.SetupLdapConfig() th.SetupSamlConfig() - user := th.CreateUserWithAuth(model.USER_AUTH_SERVICE_SAML) + user := th.CreateUserWithAuth(model.UserAuthServiceSaml) t.Run("with LDAP sync", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { diff --git a/api4/user_viewmembers_test.go b/api4/user_viewmembers_test.go index 6c8409e699..cc050368f0 100644 --- a/api4/user_viewmembers_test.go +++ b/api4/user_viewmembers_test.go @@ -16,30 +16,30 @@ func TestApiResctrictedViewMembers(t *testing.T) { defer th.TearDown() // Create first account for system admin - _, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SYSTEM_USER_ROLE_ID}) + _, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SystemUserRoleId}) require.Nil(t, err) - user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId}) require.Nil(t, err) - user2, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SYSTEM_USER_ROLE_ID}) + user2, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SystemUserRoleId}) require.Nil(t, err) - user3, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SYSTEM_USER_ROLE_ID}) + user3, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SystemUserRoleId}) require.Nil(t, err) - user4, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SYSTEM_USER_ROLE_ID}) + user4, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SystemUserRoleId}) require.Nil(t, err) - user5, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SYSTEM_USER_ROLE_ID}) + user5, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SystemUserRoleId}) require.Nil(t, err) - team1, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) + team1, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen}) require.Nil(t, err) - team2, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) + team2, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen}) require.Nil(t, err) - channel1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) + channel1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) - channel2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) + channel2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) - channel3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team2.Id, CreatorId: model.NewId()}, false) + channel3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team2.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) th.LinkUserToTeam(user1, team1) @@ -124,14 +124,14 @@ func TestApiResctrictedViewMembers(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { if tc.RestrictedTo == "channels" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else if tc.RestrictedTo == "teams" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) } _, resp := th.Client.GetUser(tc.UserId, "") @@ -206,14 +206,14 @@ func TestApiResctrictedViewMembers(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { if tc.RestrictedTo == "channels" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else if tc.RestrictedTo == "teams" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) } _, resp := th.Client.GetUserByUsername(tc.Username, "") @@ -288,14 +288,14 @@ func TestApiResctrictedViewMembers(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { if tc.RestrictedTo == "channels" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else if tc.RestrictedTo == "teams" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) } _, resp := th.Client.GetUserByEmail(tc.Email, "") @@ -370,14 +370,14 @@ func TestApiResctrictedViewMembers(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { if tc.RestrictedTo == "channels" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else if tc.RestrictedTo == "teams" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) } _, resp := th.Client.GetDefaultProfileImage(tc.UserId) @@ -452,14 +452,14 @@ func TestApiResctrictedViewMembers(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { if tc.RestrictedTo == "channels" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else if tc.RestrictedTo == "teams" { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) } else { - th.RemovePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionViewMembers.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) } _, resp := th.Client.GetProfileImage(tc.UserId, "") diff --git a/api4/webhook.go b/api4/webhook.go index ca2b5d766a..503a372bbe 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -43,22 +43,22 @@ func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionManageIncomingWebhooks) { + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } - if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.LogAudit("fail - bad channel permissions") - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + c.SetPermissionError(model.PermissionReadChannel) return } userId := c.AppContext.Session().UserId if hook.UserId != "" && hook.UserId != userId { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionManageOthersIncomingWebhooks) { c.LogAudit("fail - innapropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersIncomingWebhooks) return } @@ -136,20 +136,20 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionManageIncomingWebhooks) { + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } - if c.AppContext.Session().UserId != oldHook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.AppContext.Session().UserId != oldHook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionManageOthersIncomingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersIncomingWebhooks) return } - if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.LogAudit("fail - bad channel permissions") - c.SetPermissionError(model.PERMISSION_READ_CHANNEL) + c.SetPermissionError(model.PermissionReadChannel) return } @@ -174,25 +174,25 @@ func getIncomingHooks(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageIncomingWebhooks) { + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageOthersIncomingWebhooks) { userId = "" } hooks, err = c.App.GetIncomingWebhooksForTeamPageByUser(teamId, userId, c.Params.Page, c.Params.PerPage) } else { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageIncomingWebhooks) { + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOthersIncomingWebhooks) { userId = "" } @@ -239,16 +239,16 @@ func getIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || - (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageIncomingWebhooks) || + (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { c.LogAudit("fail - bad permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } - if c.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersIncomingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersIncomingWebhooks) return } @@ -290,16 +290,16 @@ func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel_name", channel.Name) auditRec.AddMeta("team_id", hook.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || - (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageIncomingWebhooks) || + (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { c.LogAudit("fail - bad permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageIncomingWebhooks) return } - if c.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersIncomingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersIncomingWebhooks) return } @@ -353,14 +353,14 @@ func updateOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), updatedHook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), updatedHook.TeamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } - if c.AppContext.Session().UserId != oldHook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), updatedHook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.AppContext.Session().UserId != oldHook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), updatedHook.TeamId, model.PermissionManageOthersOutgoingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersOutgoingWebhooks) return } @@ -390,17 +390,17 @@ func createOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("hook_id", hook.Id) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } if hook.CreatorId == "" { hook.CreatorId = c.AppContext.Session().UserId } else { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersOutgoingWebhooks) { c.LogAudit("fail - innapropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersOutgoingWebhooks) return } @@ -437,37 +437,37 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionManageOthersOutgoingWebhooks) { userId = "" } hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage) } else if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PermissionManageOthersOutgoingWebhooks) { userId = "" } hooks, err = c.App.GetOutgoingWebhooksForTeamPageByUser(teamId, userId, c.Params.Page, c.Params.PerPage) } else { - if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageOthersOutgoingWebhooks) { userId = "" } @@ -502,14 +502,14 @@ func getOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } - if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersOutgoingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersOutgoingWebhooks) return } @@ -539,14 +539,14 @@ func regenOutgoingHookToken(c *Context, w http.ResponseWriter, r *http.Request) auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } - if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersOutgoingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersOutgoingWebhooks) return } @@ -582,14 +582,14 @@ func deleteOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { - c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOutgoingWebhooks) { + c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } - if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageOthersOutgoingWebhooks) { c.LogAudit("fail - inappropriate permissions") - c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) + c.SetPermissionError(model.PermissionManageOthersOutgoingWebhooks) return } diff --git a/api4/webhook_test.go b/api4/webhook_test.go index f06c256b30..0468b2a2b0 100644 --- a/api4/webhook_test.go +++ b/api4/webhook_test.go @@ -27,8 +27,8 @@ func TestCreateIncomingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -52,7 +52,7 @@ func TestCreateIncomingWebhook(t *testing.T) { _, resp = Client.CreateIncomingWebhook(hook) CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) _, resp = Client.CreateIncomingWebhook(hook) CheckNoError(t, resp) @@ -110,9 +110,9 @@ func TestCreateIncomingWebhook_BypassTeamPermissions(t *testing.T) { defaultRolePermissions := th.SaveDefaultRolePermissions() defer th.RestoreDefaultRolePermissions(defaultRolePermissions) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -127,7 +127,7 @@ func TestCreateIncomingWebhook_BypassTeamPermissions(t *testing.T) { team.AllowOpenInvite = false th.Client.UpdateTeam(team) th.SystemAdminClient.RemoveTeamMember(team.Id, th.BasicUser.Id) - channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.CHANNEL_OPEN, team.Id) + channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.ChannelTypeOpen, team.Id) hook = &model.IncomingWebhook{ChannelId: channel.Id} rhook, resp = th.Client.CreateIncomingWebhook(hook) @@ -145,8 +145,8 @@ func TestGetIncomingWebhooks(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} rhook, resp := th.SystemAdminClient.CreateIncomingWebhook(hook) @@ -191,7 +191,7 @@ func TestGetIncomingWebhooks(t *testing.T) { _, resp = Client.GetIncomingWebhooks(0, 1000, "") CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) _, resp = Client.GetIncomingWebhooksForTeam(th.BasicTeam.Id, 0, 1000, "") CheckNoError(t, resp) @@ -219,8 +219,8 @@ func TestGetIncomingWebhooksListByUser(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.SystemUserRoleId) // Basic user webhook bHook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, UserId: th.BasicUser.Id} @@ -261,8 +261,8 @@ func TestGetIncomingWebhooksByTeam(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) // Basic user webhook bHook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicTeam.Id, UserId: th.BasicUser.Id} @@ -385,8 +385,8 @@ func TestCreateOutgoingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, Username: "some-user-name", IconURL: "http://some-icon-url/"} @@ -410,7 +410,7 @@ func TestCreateOutgoingWebhook(t *testing.T) { _, resp = Client.CreateOutgoingWebhook(hook) CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) _, resp = Client.CreateOutgoingWebhook(hook) CheckNoError(t, resp) @@ -461,8 +461,8 @@ func TestGetOutgoingWebhooks(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} rhook, resp := th.SystemAdminClient.CreateOutgoingWebhook(hook) @@ -522,7 +522,7 @@ func TestGetOutgoingWebhooks(t *testing.T) { _, resp = th.Client.GetOutgoingWebhooks(0, 1000, "") CheckForbiddenStatus(t, resp) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) _, resp = th.Client.GetOutgoingWebhooksForTeam(th.BasicTeam.Id, 0, 1000, "") CheckNoError(t, resp) @@ -554,8 +554,8 @@ func TestGetOutgoingWebhooksByTeam(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) // Basic user webhook bHook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -595,8 +595,8 @@ func TestGetOutgoingWebhooksByChannel(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) // Basic user webhook bHook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -637,8 +637,8 @@ func TestGetOutgoingWebhooksListByUser(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.SystemUserRoleId) // Basic user webhook bHook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -710,8 +710,8 @@ func TestUpdateIncomingHook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) hook1 := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -814,11 +814,11 @@ func TestUpdateIncomingHook(t *testing.T) { CheckForbiddenStatus(t, resp) }) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) t.Run("OnlyAdminIntegrationsDisabled", func(t *testing.T) { - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) t.Run("UpdateHookOfSameUser", func(t *testing.T) { sameUserHook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -837,8 +837,8 @@ func TestUpdateIncomingHook(t *testing.T) { }) }) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) th.Client.Logout() th.UpdateUserToTeamAdmin(th.BasicUser2, th.BasicTeam) @@ -895,9 +895,9 @@ func TestUpdateIncomingWebhook_BypassTeamPermissions(t *testing.T) { defaultRolePermissions := th.SaveDefaultRolePermissions() defer th.RestoreDefaultRolePermissions(defaultRolePermissions) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -912,7 +912,7 @@ func TestUpdateIncomingWebhook_BypassTeamPermissions(t *testing.T) { team.AllowOpenInvite = false th.Client.UpdateTeam(team) th.SystemAdminClient.RemoveTeamMember(team.Id, th.BasicUser.Id) - channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.CHANNEL_OPEN, team.Id) + channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.ChannelTypeOpen, team.Id) hook2 := &model.IncomingWebhook{Id: rhook.Id, ChannelId: channel.Id} rhook, resp = th.Client.UpdateIncomingWebhook(hook2) @@ -958,8 +958,8 @@ func TestUpdateOutgoingHook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) createdHook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, TriggerWords: []string{"cats"}} @@ -1050,7 +1050,7 @@ func TestUpdateOutgoingHook(t *testing.T) { CheckForbiddenStatus(t, rresp) }) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) hook2 := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, TriggerWords: []string{"rats2"}} @@ -1060,8 +1060,8 @@ func TestUpdateOutgoingHook(t *testing.T) { _, resp = th.Client.UpdateOutgoingWebhook(createdHook2) CheckForbiddenStatus(t, resp) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) th.Client.Logout() th.UpdateUserToTeamAdmin(th.BasicUser2, th.BasicTeam) @@ -1151,9 +1151,9 @@ func TestUpdateOutgoingWebhook_BypassTeamPermissions(t *testing.T) { defaultRolePermissions := th.SaveDefaultRolePermissions() defer th.RestoreDefaultRolePermissions(defaultRolePermissions) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.SYSTEM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.SystemUserRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, TriggerWords: []string{"rats2"}} @@ -1168,7 +1168,7 @@ func TestUpdateOutgoingWebhook_BypassTeamPermissions(t *testing.T) { team.AllowOpenInvite = false th.Client.UpdateTeam(team) th.SystemAdminClient.RemoveTeamMember(team.Id, th.BasicUser.Id) - channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.CHANNEL_OPEN, team.Id) + channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.ChannelTypeOpen, team.Id) hook2 := &model.OutgoingWebhook{Id: rhook.Id, ChannelId: channel.Id} rhook, resp = th.Client.UpdateOutgoingWebhook(hook2) diff --git a/api4/websocket.go b/api4/websocket.go index d0f3ff52ed..62d3e45802 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -25,8 +25,8 @@ func (api *API) InitWebSocket() { func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { upgrader := websocket.Upgrader{ - ReadBufferSize: model.SOCKET_MAX_MESSAGE_SIZE_KB, - WriteBufferSize: model.SOCKET_MAX_MESSAGE_SIZE_KB, + ReadBufferSize: model.SocketMaxMessageSizeKb, + WriteBufferSize: model.SocketMaxMessageSizeKb, CheckOrigin: c.App.OriginChecker(), } diff --git a/api4/websocket_norace_test.go b/api4/websocket_norace_test.go index 3dfeeec63d..a2b28b35a9 100644 --- a/api4/websocket_norace_test.go +++ b/api4/websocket_norace_test.go @@ -34,7 +34,7 @@ func TestWebSocket(t *testing.T) { WebSocketClient.Listen() resp := <-WebSocketClient.ResponseChannel - require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge") + require.Equal(t, resp.Status, model.StatusOk, "should have responded OK to authentication challenge") WebSocketClient.SendMessage("ping", nil) resp = <-WebSocketClient.ResponseChannel diff --git a/api4/websocket_test.go b/api4/websocket_test.go index d2bdc3048b..9249f587ea 100644 --- a/api4/websocket_test.go +++ b/api4/websocket_test.go @@ -21,7 +21,7 @@ func TestWebSocketTrailingSlash(t *testing.T) { defer th.TearDown() url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) - _, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket/", nil) + _, _, err := websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket/", nil) require.NoError(t, err) } @@ -36,11 +36,11 @@ func TestWebSocketEvent(t *testing.T) { WebSocketClient.Listen() resp := <-WebSocketClient.ResponseChannel - require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge") + require.Equal(t, resp.Status, model.StatusOk, "should have responded OK to authentication challenge") omitUser := make(map[string]bool, 1) omitUser["somerandomid"] = true - evt1 := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_TYPING, "", th.BasicChannel.Id, "", omitUser) + evt1 := model.NewWebSocketEvent(model.WebsocketEventTyping, "", th.BasicChannel.Id, "", omitUser) evt1.Add("user_id", "somerandomid") th.App.Publish(evt1) @@ -53,7 +53,7 @@ func TestWebSocketEvent(t *testing.T) { for { select { case resp := <-WebSocketClient.EventChannel: - if resp.EventType() == model.WEBSOCKET_EVENT_TYPING && resp.GetData()["user_id"].(string) == "somerandomid" { + if resp.EventType() == model.WebsocketEventTyping && resp.GetData()["user_id"].(string) == "somerandomid" { eventHit = true } case <-stop: @@ -68,7 +68,7 @@ func TestWebSocketEvent(t *testing.T) { require.True(t, eventHit, "did not receive typing event") - evt2 := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_TYPING, "", "somerandomid", "", nil) + evt2 := model.NewWebSocketEvent(model.WebsocketEventTyping, "", "somerandomid", "", nil) th.App.Publish(evt2) time.Sleep(300 * time.Millisecond) @@ -78,7 +78,7 @@ func TestWebSocketEvent(t *testing.T) { for { select { case resp := <-WebSocketClient.EventChannel: - if resp.EventType() == model.WEBSOCKET_EVENT_TYPING { + if resp.EventType() == model.WebsocketEventTyping { eventHit = true } case <-stop: @@ -114,10 +114,10 @@ func TestCreateDirectChannelWithSocket(t *testing.T) { WebSocketClient.Listen() resp := <-WebSocketClient.ResponseChannel - require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge") + require.Equal(t, resp.Status, model.StatusOk, "should have responded OK to authentication challenge") wsr := <-WebSocketClient.EventChannel - require.Equal(t, wsr.EventType(), model.WEBSOCKET_EVENT_HELLO, "missing hello") + require.Equal(t, wsr.EventType(), model.WebsocketEventHello, "missing hello") stop := make(chan bool) count := 0 @@ -126,7 +126,7 @@ func TestCreateDirectChannelWithSocket(t *testing.T) { for { select { case wsr := <-WebSocketClient.EventChannel: - if wsr != nil && wsr.EventType() == model.WEBSOCKET_EVENT_DIRECT_ADDED { + if wsr != nil && wsr.EventType() == model.WebsocketEventDirectAdded { count = count + 1 } @@ -156,42 +156,42 @@ func TestWebsocketOriginSecurity(t *testing.T) { url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) // Should fail because origin doesn't match - _, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err := websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.Error(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!") // We are not a browser so we can spoof this just fine - _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{fmt.Sprintf("http://localhost:%v", th.App.Srv().ListenAddr.Port)}, }) require.NoError(t, err, err) // Should succeed now because open CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "*" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.NoError(t, err, err) // Should succeed now because matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.evil.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.NoError(t, err, err) // Should fail because non-matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) require.Error(t, err, "Should have errored because Origin contain AllowCorsFrom") // Should fail because non-matching CORS th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) - _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ + _, _, err = websocket.DefaultDialer.Dial(url+model.ApiUrlSuffix+"/websocket", http.Header{ "Origin": []string{"http://www.good.co"}, }) require.Error(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!") @@ -210,9 +210,9 @@ func TestWebSocketStatuses(t *testing.T) { WebSocketClient.Listen() resp := <-WebSocketClient.ResponseChannel - require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge") + require.Equal(t, resp.Status, model.StatusOk, "should have responded OK to authentication challenge") - team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN} + team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "test@nowhere.com", Type: model.TeamOpen} rteam, _ := Client.CreateTeam(&team) user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"} @@ -242,7 +242,7 @@ func TestWebSocketStatuses(t *testing.T) { require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number") - allowedValues := [4]string{model.STATUS_OFFLINE, model.STATUS_AWAY, model.STATUS_ONLINE, model.STATUS_DND} + allowedValues := [4]string{model.StatusOffline, model.StatusAway, model.StatusOnline, model.StatusDnd} for _, status := range resp.Data { require.Containsf(t, allowedValues, status, "one of the statuses had an invalid value status=%v", status) } @@ -250,7 +250,7 @@ func TestWebSocketStatuses(t *testing.T) { status, ok := resp.Data[th.BasicUser2.Id] require.True(t, ok, "should have had user status") - require.Equal(t, status, model.STATUS_ONLINE, "status should have been online status=%v", status) + require.Equal(t, status, model.StatusOnline, "status should have been online status=%v", status) WebSocketClient.GetStatusesByIds([]string{th.BasicUser2.Id}) resp = <-WebSocketClient.ResponseChannel @@ -258,7 +258,7 @@ func TestWebSocketStatuses(t *testing.T) { require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number") - allowedValues = [4]string{model.STATUS_OFFLINE, model.STATUS_AWAY, model.STATUS_ONLINE} + allowedValues = [4]string{model.StatusOffline, model.StatusAway, model.StatusOnline} for _, status := range resp.Data { require.Containsf(t, allowedValues, status, "one of the statuses had an invalid value status") } @@ -266,7 +266,7 @@ func TestWebSocketStatuses(t *testing.T) { status, ok = resp.Data[th.BasicUser2.Id] require.True(t, ok, "should have had user status") - require.Equal(t, status, model.STATUS_ONLINE, "status should have been online status=%v", status) + require.Equal(t, status, model.StatusOnline, "status should have been online status=%v", status) require.Equal(t, len(resp.Data), 1, "only 1 status should be returned") WebSocketClient.GetStatusesByIds([]string{ruser2.Id, "junk"}) @@ -314,11 +314,11 @@ func TestWebSocketStatuses(t *testing.T) { for { select { case resp := <-WebSocketClient.EventChannel: - if resp.EventType() == model.WEBSOCKET_EVENT_STATUS_CHANGE && resp.GetData()["user_id"].(string) == th.BasicUser.Id { + if resp.EventType() == model.WebsocketEventStatusChange && resp.GetData()["user_id"].(string) == th.BasicUser.Id { status := resp.GetData()["status"].(string) - if status == model.STATUS_ONLINE { + if status == model.StatusOnline { onlineHit = true - } else if status == model.STATUS_AWAY { + } else if status == model.StatusAway { awayHit = true } } diff --git a/app/admin.go b/app/admin.go index 224447bd9d..56fc9dcbcf 100644 --- a/app/admin.go +++ b/app/admin.go @@ -155,8 +155,8 @@ func (s *Server) InvalidateAllCaches() *model.AppError { if s.Cluster != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventInvalidateAllCaches, + SendType: model.ClusterSendReliable, WaitForAllToSend: true, } @@ -211,7 +211,7 @@ func (a *App) TestEmail(userID string, cfg *model.Config) *model.AppError { // if the user hasn't changed their email settings, fill in the actual SMTP password so that // the user can verify an existing SMTP connection - if *cfg.EmailSettings.SMTPPassword == model.FAKE_SETTING { + if *cfg.EmailSettings.SMTPPassword == model.FakeSetting { if *cfg.EmailSettings.SMTPServer == *a.Config().EmailSettings.SMTPServer && *cfg.EmailSettings.SMTPPort == *a.Config().EmailSettings.SMTPPort && *cfg.EmailSettings.SMTPUsername == *a.Config().EmailSettings.SMTPUsername { diff --git a/app/analytics.go b/app/analytics.go index 572af594a3..26bfefba10 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -48,7 +48,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var openChannelsCount int64 g.Go(func() error { var err error - if openChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.CHANNEL_OPEN); err != nil { + if openChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypeOpen); err != nil { return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil @@ -57,7 +57,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var privateChannelsCount int64 g.Go(func() error { var err error - if privateChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.CHANNEL_PRIVATE); err != nil { + if privateChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypePrivate); err != nil { return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil diff --git a/app/app.go b/app/app.go index 6a2c9455b6..b4ece04d8a 100644 --- a/app/app.go +++ b/app/app.go @@ -64,7 +64,7 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) { } func (s *Server) getSystemInstallDate() (int64, *model.AppError) { - systemData, err := s.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) + systemData, err := s.Store.System().GetByName(model.SystemInstallationDateKey) if err != nil { return 0, model.NewAppError("getSystemInstallDate", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -76,7 +76,7 @@ func (s *Server) getSystemInstallDate() (int64, *model.AppError) { } func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) { - systemData, err := s.Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY) + systemData, err := s.Store.System().GetByName(model.SystemFirstServerRunTimestampKey) if err != nil { return 0, model.NewAppError("getFirstServerRunTimestamp", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -89,7 +89,7 @@ func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) { //nolint:golint,unused,deadcode func (s *Server) getLastWarnMetricTimestamp() (int64, *model.AppError) { - systemData, err := s.Store.System().GetByName(model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY) + systemData, err := s.Store.System().GetByName(model.SystemWarnMetricLastRunTimestampKey) if err != nil { return 0, model.NewAppError("getLastWarnMetricTimestamp", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -110,9 +110,9 @@ func (a *App) GetWarnMetricsStatus() (map[string]*model.WarnMetricStatus, *model result := map[string]*model.WarnMetricStatus{} for key, value := range systemDataList { - if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) { + if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) { if warnMetric, ok := model.WarnMetricsTable[key]; ok { - if !warnMetric.IsBotOnly && (value == model.WARN_METRIC_STATUS_RUNONCE || value == model.WARN_METRIC_STATUS_LIMIT_REACHED) { + if !warnMetric.IsBotOnly && (value == model.WarnMetricStatusRunonce || value == model.WarnMetricStatusLimitReached) { result[key], _ = a.getWarnMetricStatusAndDisplayTextsForId(key, nil, isE0Edition) } } @@ -141,7 +141,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.BotSuccessMessage = T("api.server.warn_metric.bot_response.notification_success.message") switch warnMetricId { - case model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5: + case model.SystemWarnMetricNumberOfTeams5: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_teams_5.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_teams_5.start_trial.notification_body") @@ -150,7 +150,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_teams_5.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_teams_5.notification_body") } - case model.SYSTEM_WARN_METRIC_MFA: + case model.SystemWarnMetricMfa: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.mfa.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.mfa.start_trial.notification_body") @@ -159,7 +159,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.mfa.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.mfa.notification_body") } - case model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN: + case model.SystemWarnMetricEmailDomain: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.email_domain.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.email_domain.start_trial.notification_body") @@ -168,7 +168,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.email_domain.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.email_domain.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50: + case model.SystemWarnMetricNumberOfChannels50: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_channels_50.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_channels_50.start_trial.notification_body") @@ -177,7 +177,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_channels_50.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_channels_50.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100: + case model.SystemWarnMetricNumberOfActiveUsers100: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_100.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_100.start_trial.notification_body") @@ -186,7 +186,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_100.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_100.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200: + case model.SystemWarnMetricNumberOfActiveUsers200: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_200.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_200.start_trial.notification_body") @@ -195,7 +195,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_200.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_200.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300: + case model.SystemWarnMetricNumberOfActiveUsers300: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_300.start_trial.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_300.start_trial.notification_body") @@ -204,7 +204,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_300.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_300.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500: + case model.SystemWarnMetricNumberOfActiveUsers500: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_500.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_500.start_trial.notification_body") @@ -213,7 +213,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_500.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_500.notification_body") } - case model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M: + case model.SystemWarnMetricNumberOfPosts2m: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_posts_2M.notification_title") if isE0Edition { warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_posts_2M.start_trial.notification_body") @@ -222,7 +222,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_posts_2M.contact_us.email_body") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_posts_2M.notification_body") } - case model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED: + case model.SystemMetricSupportEmailNotConfigured: warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.support_email_not_configured.notification_title") warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.support_email_not_configured.start_trial.notification_body") default: @@ -252,7 +252,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st userOptions := &model.UserGetOptions{ Page: 0, PerPage: perPage, - Role: model.SYSTEM_ADMIN_ROLE_ID, + Role: model.SystemAdminRoleId, Inactive: false, } @@ -293,7 +293,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st botPost := &model.Post{ UserId: warnMetricsBot.UserId, ChannelId: channel.Id, - Type: model.POST_SYSTEM_WARN_METRIC_STATUS, + Type: model.PostTypeSystemWarnMetricStatus, Message: "", } @@ -314,7 +314,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st &model.PostAction{ Id: actionId, Name: actionName, - Type: model.POST_ACTION_TYPE_BUTTON, + Type: model.PostActionTypeButton, Options: []*model.PostActionOptions{ { Text: "TrackEventId", @@ -359,7 +359,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, forceAck bool, isBot bool) *model.AppError { if warnMetric, ok := model.WarnMetricsTable[warnMetricId]; ok { data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id) - if nErr == nil && data != nil && data.Value == model.WARN_METRIC_STATUS_ACK { + if nErr == nil && data != nil && data.Value == model.WarnMetricStatusAck { mlog.Debug("This metric warning has already been acknowledged", mlog.String("id", warnMetric.Id)) return nil } @@ -404,7 +404,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) } - if err := mail.SendMailUsingConfig(model.MM_SUPPORT_ADVISOR_ADDRESS, subject, body, mailConfig, false, sender.Email); err != nil { + if err := mail.SendMailUsingConfig(model.MmSupportAdvisorAddress, subject, body, mailConfig, false, sender.Email); err != nil { return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) } } @@ -418,12 +418,12 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, func (a *App) setWarnMetricsStatusAndNotify(warnMetricId string) *model.AppError { // Ack all metric warnings on the server - if err := a.setWarnMetricsStatus(model.WARN_METRIC_STATUS_ACK); err != nil { + if err := a.setWarnMetricsStatus(model.WarnMetricStatusAck); err != nil { return err } // Inform client that this metric warning has been acked - message := model.NewWebSocketEvent(model.WEBSOCKET_WARN_METRIC_STATUS_REMOVED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketWarnMetricStatusRemoved, "", "", "", nil) message.Add("warnMetricId", warnMetricId) a.Publish(message) @@ -468,7 +468,7 @@ func (a *App) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId st trialLicenseRequest := &model.TrialLicenseRequest{ ServerID: a.TelemetryId(), - Name: currentUser.GetDisplayName(model.SHOW_FULLNAME), + Name: currentUser.GetDisplayName(model.ShowFullName), Email: currentUser.Email, SiteName: *a.Config().TeamSettings.SiteName, SiteURL: *a.Config().ServiceSettings.SiteURL, diff --git a/app/app_iface.go b/app/app_iface.go index cdc0728a87..a0d34b4cd4 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -1058,8 +1058,8 @@ type AppIface interface { UpdateLastActivityAtIfNeeded(session model.Session) UpdateMfa(activate bool, userID, token string) *model.AppError UpdateMobileAppBadge(userID string) - UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string, tokenUser *model.User) *model.AppError - UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) + UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) + UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) UpdatePassword(user *model.User, newPassword string) *model.AppError UpdatePasswordAsUser(userID, currentPassword, newPassword string) *model.AppError diff --git a/app/app_test.go b/app/app_test.go index 98cf40ca34..81793cc512 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -98,87 +98,87 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) { expected1 := map[string][]string{ "channel_user": { - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_ADD_REACTION.Id, - model.PERMISSION_REMOVE_REACTION.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - model.PERMISSION_UPLOAD_FILE.Id, - model.PERMISSION_GET_PUBLIC_LINK.Id, - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, - model.PERMISSION_USE_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_EDIT_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionAddReaction.Id, + model.PermissionRemoveReaction.Id, + model.PermissionManagePublicChannelMembers.Id, + model.PermissionUploadFile.Id, + model.PermissionGetPublicLink.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, + model.PermissionUseSlashCommands.Id, + model.PermissionManagePublicChannelProperties.Id, + model.PermissionDeletePublicChannel.Id, + model.PermissionManagePrivateChannelProperties.Id, + model.PermissionDeletePrivateChannel.Id, + model.PermissionManagePrivateChannelMembers.Id, + model.PermissionDeletePost.Id, + model.PermissionEditPost.Id, }, "channel_admin": { - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_USE_GROUP_MENTIONS.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionUseGroupMentions.Id, }, "team_user": { - model.PERMISSION_LIST_TEAM_CHANNELS.Id, - model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, - model.PERMISSION_READ_PUBLIC_CHANNEL.Id, - model.PERMISSION_VIEW_TEAM.Id, - model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, - model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, - model.PERMISSION_INVITE_USER.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + model.PermissionListTeamChannels.Id, + model.PermissionJoinPublicChannels.Id, + model.PermissionReadPublicChannel.Id, + model.PermissionViewTeam.Id, + model.PermissionCreatePublicChannel.Id, + model.PermissionCreatePrivateChannel.Id, + model.PermissionInviteUser.Id, + model.PermissionAddUserToTeam.Id, }, "team_post_all": { - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, }, "team_post_all_public": { - model.PERMISSION_CREATE_POST_PUBLIC.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePostPublic.Id, + model.PermissionUseChannelMentions.Id, }, "team_admin": { - model.PERMISSION_REMOVE_USER_FROM_TEAM.Id, - model.PERMISSION_MANAGE_TEAM.Id, - model.PERMISSION_IMPORT_TEAM.Id, - model.PERMISSION_MANAGE_TEAM_ROLES.Id, - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, - model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + model.PermissionRemoveUserFromTeam.Id, + model.PermissionManageTeam.Id, + model.PermissionImportTeam.Id, + model.PermissionManageTeamRoles.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionManageOthersIncomingWebhooks.Id, + model.PermissionManageOthersOutgoingWebhooks.Id, + model.PermissionManageSlashCommands.Id, + model.PermissionManageOthersSlashCommands.Id, + model.PermissionManageIncomingWebhooks.Id, + model.PermissionManageOutgoingWebhooks.Id, + model.PermissionConvertPublicChannelToPrivate.Id, + model.PermissionConvertPrivateChannelToPublic.Id, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, }, "system_user": { - model.PERMISSION_LIST_PUBLIC_TEAMS.Id, - model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, - model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, - model.PERMISSION_CREATE_GROUP_CHANNEL.Id, - model.PERMISSION_VIEW_MEMBERS.Id, - model.PERMISSION_CREATE_TEAM.Id, + model.PermissionListPublicTeams.Id, + model.PermissionJoinPublicTeams.Id, + model.PermissionCreateDirectChannel.Id, + model.PermissionCreateGroupChannel.Id, + model.PermissionViewMembers.Id, + model.PermissionCreateTeam.Id, }, "system_post_all": { - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, }, "system_post_all_public": { - model.PERMISSION_CREATE_POST_PUBLIC.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePostPublic.Id, + model.PermissionUseChannelMentions.Id, }, "system_user_access_token": { - model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, - model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, - model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, + model.PermissionCreateUserAccessToken.Id, + model.PermissionReadUserAccessToken.Id, + model.PermissionRevokeUserAccessToken.Id, }, "system_admin": allPermissionIDs, } - assert.Contains(t, allPermissionIDs, model.PERMISSION_MANAGE_SHARED_CHANNELS.Id, "manage_shared_channels permission not found") - assert.Contains(t, allPermissionIDs, model.PERMISSION_MANAGE_SECURE_CONNECTIONS.Id, "manage_secure_connections permission not found") + assert.Contains(t, allPermissionIDs, model.PermissionManageSharedChannels.Id, "manage_shared_channels permission not found") + assert.Contains(t, allPermissionIDs, model.PermissionManageSecureConnections.Id, "manage_secure_connections permission not found") // Check the migration matches what's expected. for name, permissions := range expected1 { @@ -200,10 +200,10 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN + *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = model.PermissionsTeamAdmin }) th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PermissionsTeamAdmin }) th.App.Srv().SetLicense(model.NewTestLicense()) @@ -229,82 +229,82 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) { // Check the role permissions. expected2 := map[string][]string{ "channel_user": { - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_ADD_REACTION.Id, - model.PERMISSION_REMOVE_REACTION.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - model.PERMISSION_UPLOAD_FILE.Id, - model.PERMISSION_GET_PUBLIC_LINK.Id, - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, - model.PERMISSION_USE_SLASH_COMMANDS.Id, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_EDIT_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionAddReaction.Id, + model.PermissionRemoveReaction.Id, + model.PermissionManagePublicChannelMembers.Id, + model.PermissionUploadFile.Id, + model.PermissionGetPublicLink.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, + model.PermissionUseSlashCommands.Id, + model.PermissionDeletePublicChannel.Id, + model.PermissionDeletePrivateChannel.Id, + model.PermissionManagePrivateChannelMembers.Id, + model.PermissionDeletePost.Id, + model.PermissionEditPost.Id, }, "channel_admin": { - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_USE_GROUP_MENTIONS.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionUseGroupMentions.Id, }, "team_user": { - model.PERMISSION_LIST_TEAM_CHANNELS.Id, - model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id, - model.PERMISSION_READ_PUBLIC_CHANNEL.Id, - model.PERMISSION_VIEW_TEAM.Id, - model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, - model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, - model.PERMISSION_INVITE_USER.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + model.PermissionListTeamChannels.Id, + model.PermissionJoinPublicChannels.Id, + model.PermissionReadPublicChannel.Id, + model.PermissionViewTeam.Id, + model.PermissionCreatePublicChannel.Id, + model.PermissionCreatePrivateChannel.Id, + model.PermissionInviteUser.Id, + model.PermissionAddUserToTeam.Id, }, "team_post_all": { - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, }, "team_post_all_public": { - model.PERMISSION_CREATE_POST_PUBLIC.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePostPublic.Id, + model.PermissionUseChannelMentions.Id, }, "team_admin": { - model.PERMISSION_REMOVE_USER_FROM_TEAM.Id, - model.PERMISSION_MANAGE_TEAM.Id, - model.PERMISSION_IMPORT_TEAM.Id, - model.PERMISSION_MANAGE_TEAM_ROLES.Id, - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, - model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + model.PermissionRemoveUserFromTeam.Id, + model.PermissionManageTeam.Id, + model.PermissionImportTeam.Id, + model.PermissionManageTeamRoles.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionManageOthersIncomingWebhooks.Id, + model.PermissionManageOthersOutgoingWebhooks.Id, + model.PermissionManageSlashCommands.Id, + model.PermissionManageOthersSlashCommands.Id, + model.PermissionManageIncomingWebhooks.Id, + model.PermissionManageOutgoingWebhooks.Id, + model.PermissionConvertPublicChannelToPrivate.Id, + model.PermissionConvertPrivateChannelToPublic.Id, + model.PermissionManagePublicChannelProperties.Id, + model.PermissionManagePrivateChannelProperties.Id, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, }, "system_user": { - model.PERMISSION_LIST_PUBLIC_TEAMS.Id, - model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, - model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, - model.PERMISSION_CREATE_GROUP_CHANNEL.Id, - model.PERMISSION_VIEW_MEMBERS.Id, - model.PERMISSION_CREATE_TEAM.Id, + model.PermissionListPublicTeams.Id, + model.PermissionJoinPublicTeams.Id, + model.PermissionCreateDirectChannel.Id, + model.PermissionCreateGroupChannel.Id, + model.PermissionViewMembers.Id, + model.PermissionCreateTeam.Id, }, "system_post_all": { - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePost.Id, + model.PermissionUseChannelMentions.Id, }, "system_post_all_public": { - model.PERMISSION_CREATE_POST_PUBLIC.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, + model.PermissionCreatePostPublic.Id, + model.PermissionUseChannelMentions.Id, }, "system_user_access_token": { - model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, - model.PERMISSION_READ_USER_ACCESS_TOKEN.Id, - model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, + model.PermissionCreateUserAccessToken.Id, + model.PermissionReadUserAccessToken.Id, + model.PermissionRevokeUserAccessToken.Id, }, "system_admin": allPermissionIDs, } @@ -384,7 +384,7 @@ func TestDoEmojisPermissionsMigration(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_SYSTEM_ADMIN + *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationSystemAdmin }) th.ResetEmojisMigration() @@ -393,84 +393,84 @@ func TestDoEmojisPermissionsMigration(t *testing.T) { expectedSystemAdmin := allPermissionIDs sort.Strings(expectedSystemAdmin) - role1, err1 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + role1, err1 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId) assert.Nil(t, err1) sort.Strings(role1.Permissions) - assert.Equal(t, expectedSystemAdmin, role1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID)) + assert.Equal(t, expectedSystemAdmin, role1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId)) th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ADMIN + *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationAdmin }) th.ResetEmojisMigration() th.App.DoEmojisPermissionsMigration() - role2, err2 := th.App.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID) + role2, err2 := th.App.GetRoleByName(context.Background(), model.TeamAdminRoleId) assert.Nil(t, err2) expected2 := []string{ - model.PERMISSION_REMOVE_USER_FROM_TEAM.Id, - model.PERMISSION_MANAGE_TEAM.Id, - model.PERMISSION_IMPORT_TEAM.Id, - model.PERMISSION_MANAGE_TEAM_ROLES.Id, - model.PERMISSION_READ_PUBLIC_CHANNEL_GROUPS.Id, - model.PERMISSION_READ_PRIVATE_CHANNEL_GROUPS.Id, - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id, - model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, - model.PERMISSION_CREATE_EMOJIS.Id, - model.PERMISSION_DELETE_EMOJIS.Id, - model.PERMISSION_ADD_REACTION.Id, - model.PERMISSION_CREATE_POST.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, - model.PERMISSION_REMOVE_REACTION.Id, - model.PERMISSION_USE_CHANNEL_MENTIONS.Id, - model.PERMISSION_USE_GROUP_MENTIONS.Id, - model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, - model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, + model.PermissionRemoveUserFromTeam.Id, + model.PermissionManageTeam.Id, + model.PermissionImportTeam.Id, + model.PermissionManageTeamRoles.Id, + model.PermissionReadPublicChannelGroups.Id, + model.PermissionReadPrivateChannelGroups.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionManageOthersIncomingWebhooks.Id, + model.PermissionManageOthersOutgoingWebhooks.Id, + model.PermissionManageSlashCommands.Id, + model.PermissionManageOthersSlashCommands.Id, + model.PermissionManageIncomingWebhooks.Id, + model.PermissionManageOutgoingWebhooks.Id, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, + model.PermissionCreateEmojis.Id, + model.PermissionDeleteEmojis.Id, + model.PermissionAddReaction.Id, + model.PermissionCreatePost.Id, + model.PermissionManagePublicChannelMembers.Id, + model.PermissionManagePrivateChannelMembers.Id, + model.PermissionRemoveReaction.Id, + model.PermissionUseChannelMentions.Id, + model.PermissionUseGroupMentions.Id, + model.PermissionConvertPublicChannelToPrivate.Id, + model.PermissionConvertPrivateChannelToPublic.Id, } sort.Strings(expected2) sort.Strings(role2.Permissions) - assert.Equal(t, expected2, role2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.TEAM_ADMIN_ROLE_ID)) + assert.Equal(t, expected2, role2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.TeamAdminRoleId)) - systemAdmin1, systemAdminErr1 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + systemAdmin1, systemAdminErr1 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId) assert.Nil(t, systemAdminErr1) sort.Strings(systemAdmin1.Permissions) - assert.Equal(t, expectedSystemAdmin, systemAdmin1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID)) + assert.Equal(t, expectedSystemAdmin, systemAdmin1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId)) th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ALL + *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationAll }) th.ResetEmojisMigration() th.App.DoEmojisPermissionsMigration() - role3, err3 := th.App.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + role3, err3 := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId) assert.Nil(t, err3) expected3 := []string{ - model.PERMISSION_LIST_PUBLIC_TEAMS.Id, - model.PERMISSION_JOIN_PUBLIC_TEAMS.Id, - model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, - model.PERMISSION_CREATE_GROUP_CHANNEL.Id, - model.PERMISSION_CREATE_TEAM.Id, - model.PERMISSION_CREATE_EMOJIS.Id, - model.PERMISSION_DELETE_EMOJIS.Id, - model.PERMISSION_VIEW_MEMBERS.Id, + model.PermissionListPublicTeams.Id, + model.PermissionJoinPublicTeams.Id, + model.PermissionCreateDirectChannel.Id, + model.PermissionCreateGroupChannel.Id, + model.PermissionCreateTeam.Id, + model.PermissionCreateEmojis.Id, + model.PermissionDeleteEmojis.Id, + model.PermissionViewMembers.Id, } sort.Strings(expected3) sort.Strings(role3.Permissions) - assert.Equal(t, expected3, role3.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_USER_ROLE_ID)) + assert.Equal(t, expected3, role3.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemUserRoleId)) - systemAdmin2, systemAdminErr2 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + systemAdmin2, systemAdminErr2 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId) assert.Nil(t, systemAdminErr2) sort.Strings(systemAdmin2.Permissions) - assert.Equal(t, expectedSystemAdmin, systemAdmin2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID)) + assert.Equal(t, expectedSystemAdmin, systemAdmin2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId)) } func TestDBHealthCheckWriteAndDelete(t *testing.T) { diff --git a/app/authentication.go b/app/authentication.go index b52e47084d..0012c5d2e4 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -249,7 +249,7 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m license := a.Srv().License() ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP - if user.AuthService == model.USER_AUTH_SERVICE_LDAP { + if user.AuthService == model.UserAuthServiceLdap { if !ldapAvailable { err := model.NewAppError("login", "api.user.login_ldap.not_available.app_error", nil, "", http.StatusNotImplemented) return user, err @@ -267,7 +267,7 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m if user.AuthService != "" { authService := user.AuthService - if authService == model.USER_AUTH_SERVICE_SAML { + if authService == model.UserAuthServiceSaml { authService = strings.ToUpper(authService) } err := model.NewAppError("login", "api.user.login.use_auth_service.app_error", map[string]interface{}{"AuthService": authService}, "", http.StatusBadRequest) @@ -283,20 +283,20 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m } func ParseAuthTokenFromRequest(r *http.Request) (string, TokenLocation) { - authHeader := r.Header.Get(model.HEADER_AUTH) + authHeader := r.Header.Get(model.HeaderAuth) // Attempt to parse the token from the cookie - if cookie, err := r.Cookie(model.SESSION_COOKIE_TOKEN); err == nil { + if cookie, err := r.Cookie(model.SessionCookieToken); err == nil { return cookie.Value, TokenLocationCookie } // Parse the token from the header - if len(authHeader) > 6 && strings.ToUpper(authHeader[0:6]) == model.HEADER_BEARER { + if len(authHeader) > 6 && strings.ToUpper(authHeader[0:6]) == model.HeaderBearer { // Default session token return authHeader[7:], TokenLocationHeader } - if len(authHeader) > 5 && strings.ToLower(authHeader[0:5]) == model.HEADER_TOKEN { + if len(authHeader) > 5 && strings.ToLower(authHeader[0:5]) == model.HeaderToken { // OAuth token return authHeader[6:], TokenLocationHeader } @@ -306,11 +306,11 @@ func ParseAuthTokenFromRequest(r *http.Request) (string, TokenLocation) { return token, TokenLocationQueryString } - if token := r.Header.Get(model.HEADER_CLOUD_TOKEN); token != "" { + if token := r.Header.Get(model.HeaderCloudToken); token != "" { return token, TokenLocationCloudHeader } - if token := r.Header.Get(model.HEADER_REMOTECLUSTER_TOKEN); token != "" { + if token := r.Header.Get(model.HeaderRemoteclusterToken); token != "" { return token, TokenLocationRemoteClusterHeader } diff --git a/app/authentication_test.go b/app/authentication_test.go index ad9bd34c00..cb323923d2 100644 --- a/app/authentication_test.go +++ b/app/authentication_test.go @@ -38,12 +38,12 @@ func TestParseAuthTokenFromRequest(t *testing.T) { req := httptest.NewRequest("GET", pathname, nil) switch tc.expectedLocation { case TokenLocationHeader: - req.Header.Add(model.HEADER_AUTH, tc.header) + req.Header.Add(model.HeaderAuth, tc.header) case TokenLocationCloudHeader: - req.Header.Add(model.HEADER_CLOUD_TOKEN, tc.header) + req.Header.Add(model.HeaderCloudToken, tc.header) case TokenLocationCookie: req.AddCookie(&http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: tc.cookie, }) } diff --git a/app/authorization.go b/app/authorization.go index eb3d44e953..43ef0cb373 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -106,7 +106,7 @@ func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postID } func (a *App) SessionHasPermissionToCategory(session model.Session, userID, teamID, categoryId string) bool { - if a.SessionHasPermissionTo(session, model.PERMISSION_EDIT_OTHER_USERS) { + if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) { return true } category, err := a.GetSidebarCategory(categoryId) @@ -125,7 +125,7 @@ func (a *App) SessionHasPermissionToUser(session model.Session, userID string) b return true } - if a.SessionHasPermissionTo(session, model.PERMISSION_EDIT_OTHER_USERS) { + if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) { return true } @@ -212,7 +212,7 @@ func (a *App) HasPermissionToUser(askingUserId string, userID string) bool { return true } - if a.HasPermissionTo(askingUserId, model.PERMISSION_EDIT_OTHER_USERS) { + if a.HasPermissionTo(askingUserId, model.PermissionEditOtherUsers) { return true } @@ -257,22 +257,22 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s } if existingBot.OwnerId == session.UserId { - if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_BOTS) { - if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_BOTS) { + if !a.SessionHasPermissionTo(session, model.PermissionManageBots) { + if !a.SessionHasPermissionTo(session, model.PermissionReadBots) { // If the user doesn't have permission to read bots, pretend as if // the bot doesn't exist at all. return model.MakeBotNotFoundError(botUserId) } - return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_BOTS}) + return a.MakePermissionError(&session, []*model.Permission{model.PermissionManageBots}) } } else { - if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_OTHERS_BOTS) { - if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_OTHERS_BOTS) { + if !a.SessionHasPermissionTo(session, model.PermissionManageOthersBots) { + if !a.SessionHasPermissionTo(session, model.PermissionReadOthersBots) { // If the user doesn't have permission to read others' bots, // pretend as if the bot doesn't exist at all. return model.MakeBotNotFoundError(botUserId) } - return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS}) + return a.MakePermissionError(&session, []*model.Permission{model.PermissionManageOthersBots}) } } diff --git a/app/authorization_test.go b/app/authorization_test.go index 0b433d8c62..a488900a4c 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -24,14 +24,14 @@ func TestCheckIfRolesGrantPermission(t *testing.T) { permissionId string shouldGrant bool }{ - {[]string{model.SYSTEM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true}, - {[]string{model.SYSTEM_ADMIN_ROLE_ID}, "non-existent-permission", false}, - {[]string{model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_READ_CHANNEL.Id, true}, - {[]string{model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, false}, - {[]string{model.SYSTEM_ADMIN_ROLE_ID, model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true}, - {[]string{model.CHANNEL_USER_ROLE_ID, model.SYSTEM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true}, - {[]string{model.TEAM_USER_ROLE_ID, model.TEAM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, true}, - {[]string{model.TEAM_ADMIN_ROLE_ID, model.TEAM_USER_ROLE_ID}, model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, true}, + {[]string{model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true}, + {[]string{model.SystemAdminRoleId}, "non-existent-permission", false}, + {[]string{model.ChannelUserRoleId}, model.PermissionReadChannel.Id, true}, + {[]string{model.ChannelUserRoleId}, model.PermissionManageSystem.Id, false}, + {[]string{model.SystemAdminRoleId, model.ChannelUserRoleId}, model.PermissionManageSystem.Id, true}, + {[]string{model.ChannelUserRoleId, model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true}, + {[]string{model.TeamUserRoleId, model.TeamAdminRoleId}, model.PermissionManageSlashCommands.Id, true}, + {[]string{model.TeamAdminRoleId, model.TeamUserRoleId}, model.PermissionManageSlashCommands.Id, true}, } for _, testcase := range cases { @@ -50,17 +50,17 @@ func TestHasPermissionToTeam(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - assert.True(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) + assert.True(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) th.RemoveUserFromTeam(th.BasicUser, th.BasicTeam) - assert.False(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) + assert.False(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) - assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) + assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam) - assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) - th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID) - assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) + assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) + th.RemovePermissionFromRole(model.PermissionListTeamChannels.Id, model.TeamUserRoleId) + assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) th.RemoveUserFromTeam(th.SystemAdminUser, th.BasicTeam) - assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS)) + assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels)) } func TestSessionHasPermissionToChannel(t *testing.T) { @@ -72,7 +72,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) { } t.Run("basic user can access basic channel", func(t *testing.T) { - assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PERMISSION_ADD_REACTION)) + assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PermissionAddReaction)) }) t.Run("does not panic if fetching channel causes an error", func(t *testing.T) { @@ -97,7 +97,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) { // If there's an error returned from the GetChannel call the code should continue to cascade and since there // are no session level permissions in this test case, the permission should be denied. - assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PERMISSION_ADD_REACTION)) + assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PermissionAddReaction)) }) } diff --git a/app/auto_responder.go b/app/auto_responder.go index 5254436b29..4583d26485 100644 --- a/app/auto_responder.go +++ b/app/auto_responder.go @@ -22,7 +22,7 @@ func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) ( } func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { - if channel.Type != model.CHANNEL_DIRECT { + if channel.Type != model.ChannelTypeDirect { return false, nil } @@ -57,8 +57,8 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei return false, nil } - active := receiver.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true" - message := receiver.NotifyProps[model.AUTO_RESPONDER_MESSAGE_NOTIFY_PROP] + active := receiver.NotifyProps[model.AutoResponderActiveNotifyProp] == "true" + message := receiver.NotifyProps[model.AutoResponderMessageNotifyProp] if !active || message == "" { return false, nil @@ -73,7 +73,7 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei ChannelId: channel.Id, Message: message, RootId: rootID, - Type: model.POST_AUTO_RESPONDER, + Type: model.PostTypeAutoResponder, UserId: receiver.Id, } @@ -85,8 +85,8 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei } func (a *App) SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) { - active := user.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true" - oldActive := oldNotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true" + active := user.NotifyProps[model.AutoResponderActiveNotifyProp] == "true" + oldActive := oldNotifyProps[model.AutoResponderActiveNotifyProp] == "true" autoResponderEnabled := !oldActive && active autoResponderDisabled := oldActive && !active @@ -104,12 +104,12 @@ func (a *App) DisableAutoResponder(userID string, asAdmin bool) *model.AppError return err } - active := user.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true" + active := user.NotifyProps[model.AutoResponderActiveNotifyProp] == "true" if active { patch := &model.UserPatch{} patch.NotifyProps = user.NotifyProps - patch.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] = "false" + patch.NotifyProps[model.AutoResponderActiveNotifyProp] = "false" _, err := a.PatchUser(userID, patch, asAdmin) if err != nil { diff --git a/app/auto_responder_test.go b/app/auto_responder_test.go index 3e9909a7bb..41b7e298c0 100644 --- a/app/auto_responder_test.go +++ b/app/auto_responder_test.go @@ -33,7 +33,7 @@ func TestSetAutoResponderStatus(t *testing.T) { status, err := th.App.GetStatus(userUpdated1.Id) require.Nil(t, err) - assert.Equal(t, model.STATUS_OUT_OF_OFFICE, status.Status) + assert.Equal(t, model.StatusOutOfOffice, status.Status) patch2 := &model.UserPatch{} patch2.NotifyProps = make(map[string]string) @@ -47,7 +47,7 @@ func TestSetAutoResponderStatus(t *testing.T) { status, err = th.App.GetStatus(userUpdated2.Id) require.Nil(t, err) - assert.Equal(t, model.STATUS_ONLINE, status.Status) + assert.Equal(t, model.StatusOnline, status.Status) } @@ -268,7 +268,7 @@ func TestSendAutoResponseSuccess(t *testing.T) { autoResponderPostFound := false for _, post := range list.Posts { - if post.Type == model.POST_AUTO_RESPONDER { + if post.Type == model.PostTypeAutoResponder { autoResponderPostFound = true assert.Equal(t, savedPost.Id, post.RootId) assert.Equal(t, savedPost.Id, post.ParentId) @@ -318,7 +318,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) { autoResponderPostFound := false for _, post := range list.Posts { - if post.Type == model.POST_AUTO_RESPONDER { + if post.Type == model.PostTypeAutoResponder { autoResponderPostFound = true assert.Equal(t, savedPost.RootId, post.RootId) assert.Equal(t, savedPost.ParentId, post.ParentId) @@ -359,7 +359,7 @@ func TestSendAutoResponseFailure(t *testing.T) { } else { autoResponderPostFound := false for _, post := range list.Posts { - if post.Type == model.POST_AUTO_RESPONDER { + if post.Type == model.PostTypeAutoResponder { autoResponderPostFound = true } } diff --git a/app/bot.go b/app/bot.go index b36c34d86a..c74dcaa970 100644 --- a/app/bot.go +++ b/app/bot.go @@ -76,7 +76,7 @@ func (a *App) CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model. T := i18n.GetUserTranslations(ownerUser.Locale) botAddPost := &model.Post{ - Type: model.POST_ADD_BOT_TEAMS_CHANNELS, + Type: model.PostTypeAddBotTeamsChannels, UserId: savedBot.UserId, ChannelId: channel.Id, Message: T("api.bot.teams_channels.add_message_mobile"), @@ -96,7 +96,7 @@ func (a *App) GetWarnMetricsBot() (*model.Bot, *model.AppError) { userOptions := &model.UserGetOptions{ Page: 0, PerPage: perPage, - Role: model.SYSTEM_ADMIN_ROLE_ID, + Role: model.SystemAdminRoleId, Inactive: false, } @@ -111,7 +111,7 @@ func (a *App) GetWarnMetricsBot() (*model.Bot, *model.AppError) { T := i18n.GetUserTranslations(sysAdminList[0].Locale) warnMetricsBot := &model.Bot{ - Username: model.BOT_WARN_METRIC_BOT_USERNAME, + Username: model.BotWarnMetricBotUsername, DisplayName: T("app.system.warn_metric.bot_displayname"), Description: "", OwnerId: sysAdminList[0].Id, @@ -125,7 +125,7 @@ func (a *App) GetSystemBot() (*model.Bot, *model.AppError) { userOptions := &model.UserGetOptions{ Page: 0, PerPage: perPage, - Role: model.SYSTEM_ADMIN_ROLE_ID, + Role: model.SystemAdminRoleId, Inactive: false, } @@ -140,7 +140,7 @@ func (a *App) GetSystemBot() (*model.Bot, *model.AppError) { T := i18n.GetUserTranslations(sysAdminList[0].Locale) systemBot := &model.Bot{ - Username: model.BOT_SYSTEM_BOT_USERNAME, + Username: model.BotSystemBotUsername, DisplayName: T("app.system.system_bot.bot_displayname"), Description: "", OwnerId: sysAdminList[0].Id, @@ -478,7 +478,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID stri userOptions := &model.UserGetOptions{ Page: 0, PerPage: perPage, - Role: model.SYSTEM_ADMIN_ROLE_ID, + Role: model.SystemAdminRoleId, Inactive: false, } // get sysadmins @@ -515,7 +515,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID stri UserId: sysAdmin.Id, ChannelId: channel.Id, Message: a.getDisableBotSysadminMessage(user, userBots), - Type: model.POST_SYSTEM_GENERIC, + Type: model.PostTypeSystemGeneric, } _, appErr = a.CreatePost(c, post, channel, false, true) diff --git a/app/bot_test.go b/app/bot_test.go index cd4d09a1c2..c400ff669b 100644 --- a/app/bot_test.go +++ b/app/bot_test.go @@ -87,7 +87,7 @@ func TestCreateBot(t *testing.T) { postArray := posts.ToSlice() assert.Len(t, postArray, 1) - assert.Equal(t, postArray[0].Type, model.POST_ADD_BOT_TEAMS_CHANNELS) + assert.Equal(t, postArray[0].Type, model.PostTypeAddBotTeamsChannels) }) t.Run("create bot, username already used by a non-bot user", func(t *testing.T) { @@ -595,20 +595,20 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { Nickname: "nn_sysadmin1", Password: "hello1", Username: "un_sysadmin1", - Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} _, err := th.App.CreateUser(th.Context, &sysadmin1) require.Nil(t, err, "failed to create user") - th.App.UpdateUserRoles(sysadmin1.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(sysadmin1.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) sysadmin2 := model.User{ Email: "sys2@example.com", Nickname: "nn_sysadmin2", Password: "hello1", Username: "un_sysadmin2", - Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} + Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId} _, err = th.App.CreateUser(th.Context, &sysadmin2) require.Nil(t, err, "failed to create user") - th.App.UpdateUserRoles(sysadmin2.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(sysadmin2.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) // create user to be disabled user1, err := th.App.CreateUser(th.Context, &model.User{ @@ -932,23 +932,23 @@ func TestGetSystemBot(t *testing.T) { t.Run("The bot should be created the first time it's retrieved", func(t *testing.T) { // assert no bot with username exists - _, err := th.App.GetUserByUsername(model.BOT_SYSTEM_BOT_USERNAME) + _, err := th.App.GetUserByUsername(model.BotSystemBotUsername) require.NotNil(t, err) bot, err := th.App.GetSystemBot() require.Nil(t, err) - require.Equal(t, bot.Username, model.BOT_SYSTEM_BOT_USERNAME) + require.Equal(t, bot.Username, model.BotSystemBotUsername) }) t.Run("The bot should be correctly retrieved if it exists already", func(t *testing.T) { // assert that the bot is now present - botUser, err := th.App.GetUserByUsername(model.BOT_SYSTEM_BOT_USERNAME) + botUser, err := th.App.GetUserByUsername(model.BotSystemBotUsername) require.Nil(t, err) require.True(t, botUser.IsBot) bot, err := th.App.GetSystemBot() require.Nil(t, err) - require.Equal(t, bot.Username, model.BOT_SYSTEM_BOT_USERNAME) + require.Equal(t, bot.Username, model.BotSystemBotUsername) require.Equal(t, bot.UserId, botUser.Id) }) } diff --git a/app/busy.go b/app/busy.go index 63582c8f80..79a9747475 100644 --- a/app/busy.go +++ b/app/busy.go @@ -55,7 +55,7 @@ func (b *Busy) Set(dur time.Duration) { b.setWithoutNotify(dur) if b.cluster != nil { - sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), Expires_ts: b.expires.UTC().Format(TimestampFormat)} + sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), ExpiresTS: b.expires.UTC().Format(TimestampFormat)} b.notifyServerBusyChange(sbs) } } @@ -80,7 +80,7 @@ func (b *Busy) Clear() { b.clearWithoutNotify() if b.cluster != nil { - sbs := &model.ServerBusyState{Busy: false, Expires: time.Time{}.Unix(), Expires_ts: ""} + sbs := &model.ServerBusyState{Busy: false, Expires: time.Time{}.Unix(), ExpiresTS: ""} b.notifyServerBusyChange(sbs) } } @@ -110,8 +110,8 @@ func (b *Busy) notifyServerBusyChange(sbs *model.ServerBusyState) { return } msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_BUSY_STATE_CHANGED, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventBusyStateChanged, + SendType: model.ClusterSendReliable, WaitForAllToSend: true, Data: sbs.ToJson(), } @@ -139,9 +139,9 @@ func (b *Busy) ToJson() string { defer b.mux.RUnlock() sbs := &model.ServerBusyState{ - Busy: atomic.LoadInt32(&b.busy) != 0, - Expires: b.expires.Unix(), - Expires_ts: b.expires.UTC().Format(TimestampFormat), + Busy: atomic.LoadInt32(&b.busy) != 0, + Expires: b.expires.Unix(), + ExpiresTS: b.expires.UTC().Format(TimestampFormat), } return sbs.ToJson() } diff --git a/app/channel.go b/app/channel.go index 3eaf2f5ef6..1b7e87d69f 100644 --- a/app/channel.go +++ b/app/channel.go @@ -31,7 +31,7 @@ func (a *App) CreateDefaultChannels(c *request.Context, teamID string) ([]*model defaultChannelNames := a.DefaultChannelNames() for _, name := range defaultChannelNames { displayName := i18n.TDefault(displayNames[name], name) - channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.CHANNEL_OPEN, TeamId: teamID} + channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.ChannelTypeOpen, TeamId: teamID} if _, err := a.CreateChannel(c, channel, false); err != nil { return nil, err } @@ -96,7 +96,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model continue } - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { continue } @@ -122,7 +122,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model a.invalidateCacheForChannelMembers(channel.Id) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ADDED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserAdded, "", channel.Id, "", nil) message.Add("user_id", user.Id) message.Add("team_id", channel.TeamId) a.Publish(message) @@ -147,7 +147,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model } func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError { - if channel.Name == model.DEFAULT_CHANNEL { + if channel.Name == model.DefaultChannelName { if requestor == nil { if err := a.postJoinTeamMessage(c, user, channel); err != nil { return err @@ -205,7 +205,7 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, a.postJoinChannelMessage(c, user, channel) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CREATED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelCreated, "", "", userID, nil) message.Add("channel_id", channel.Id) message.Add("team_id", channel.TeamId) a.Publish(message) @@ -215,11 +215,11 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, // RenameChannel is used to rename the channel Name and the DisplayName fields func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) { - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { return nil, model.NewAppError("RenameChannel", "api.channel.rename_channel.cant_rename_direct_messages.app_error", nil, "", http.StatusBadRequest) } - if channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeGroup { return nil, model.NewAppError("RenameChannel", "api.channel.rename_channel.cant_rename_group_messages.app_error", nil, "", http.StatusBadRequest) } @@ -332,8 +332,8 @@ func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID s return channel, nil } - if *a.Config().TeamSettings.RestrictDirectMessage == model.DIRECT_MESSAGE_TEAM && - !a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if *a.Config().TeamSettings.RestrictDirectMessage == model.DirectMessageTeam && + !a.SessionHasPermissionTo(*c.Session(), model.PermissionManageSystem) { commonTeamIDs, err := a.GetCommonTeamIDsForTwoUsers(userID, otherUserID) if err != nil { return nil, err @@ -391,7 +391,7 @@ func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string }) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_DIRECT_ADDED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventDirectAdded, "", channel.Id, "", nil) message.Add("creator_id", userID) message.Add("teammate_id", otherUserID) a.Publish(message) @@ -509,7 +509,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha a.InvalidateCacheForUser(userID) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_GROUP_ADDED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventGroupAdded, "", channel.Id, "", nil) message.Add("teammate_ids", model.ArrayToJson(userIDs)) a.Publish(message) @@ -517,7 +517,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha } func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { - if len(userIDs) > model.CHANNEL_GROUP_MAX_USERS || len(userIDs) < model.CHANNEL_GROUP_MIN_USERS { + if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers { return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } @@ -533,7 +533,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr group := &model.Channel{ Name: model.GetGroupNameFromUserIds(userIDs), DisplayName: model.GetGroupDisplayNameFromUsers(users, true), - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } channel, nErr := a.Srv().Store.Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam) @@ -596,7 +596,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr } func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { - if len(userIDs) > model.CHANNEL_GROUP_MAX_USERS || len(userIDs) < model.CHANNEL_GROUP_MIN_USERS { + if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers { return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } @@ -635,7 +635,7 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE a.invalidateCacheForChannel(channel) - messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_UPDATED, "", channel.Id, "", nil) + messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelUpdated, "", channel.Id, "", nil) messageWs.Add("channel", channel.ToJson()) a.Publish(messageWs) @@ -647,7 +647,7 @@ func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model scheme, err := a.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }) if err != nil { return nil, err @@ -690,10 +690,10 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel } if err := a.postChannelPrivacyMessage(c, user, channel); err != nil { - if channel.Type == model.CHANNEL_OPEN { - channel.Type = model.CHANNEL_PRIVATE + if channel.Type == model.ChannelTypeOpen { + channel.Type = model.ChannelTypePrivate } else { - channel.Type = model.CHANNEL_OPEN + channel.Type = model.ChannelTypeOpen } // revert to previous channel privacy a.UpdateChannel(channel) @@ -702,7 +702,7 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel a.invalidateCacheForChannel(channel) - messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CONVERTED, channel.TeamId, "", "", nil) + messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelConverted, channel.TeamId, "", "", nil) messageWs.Add("channel_id", channel.Id) a.Publish(messageWs) @@ -726,13 +726,13 @@ func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, ch } message := (map[string]string{ - model.CHANNEL_OPEN: i18n.T("api.channel.change_channel_privacy.private_to_public"), - model.CHANNEL_PRIVATE: i18n.T("api.channel.change_channel_privacy.public_to_private"), + model.ChannelTypeOpen: i18n.T("api.channel.change_channel_privacy.private_to_public"), + model.ChannelTypePrivate: i18n.T("api.channel.change_channel_privacy.public_to_private"), })[channel.Type] post := &model.Post{ ChannelId: channel.Id, Message: message, - Type: model.POST_CHANGE_CHANNEL_PRIVACY, + Type: model.PostTypeChangeChannelPrivacy, UserId: authorId, Props: model.StringInterface{ "username": authorUsername, @@ -757,7 +757,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID channel.DeleteAt = 0 a.invalidateCacheForChannel(channel) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_RESTORED, channel.TeamId, "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelRestored, channel.TeamId, "", "", nil) message.Add("channel_id", channel.Id) a.Publish(message) @@ -782,7 +782,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID post := &model.Post{ ChannelId: channel.Id, Message: T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": user.Username}), - Type: model.POST_CHANNEL_RESTORED, + Type: model.PostTypeChannelRestored, UserId: userID, Props: model.StringInterface{ "username": user.Username, @@ -803,7 +803,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID post := &model.Post{ ChannelId: channel.Id, Message: i18n.T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": systemBot.Username}), - Type: model.POST_CHANNEL_RESTORED, + Type: model.PostTypeChannelRestored, UserId: systemBot.UserId, Props: model.StringInterface{ "username": systemBot.Username, @@ -893,9 +893,9 @@ func (a *App) GetTeamSchemeChannelRoles(teamID string) (guestRoleName, userRoleN userRoleName = scheme.DefaultChannelUserRole adminRoleName = scheme.DefaultChannelAdminRole } else { - guestRoleName = model.CHANNEL_GUEST_ROLE_ID - userRoleName = model.CHANNEL_USER_ROLE_ID - adminRoleName = model.CHANNEL_ADMIN_ROLE_ID + guestRoleName = model.ChannelGuestRoleId + userRoleName = model.ChannelUserRoleId + adminRoleName = model.ChannelAdminRoleId } return @@ -994,7 +994,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM } a.sendUpdatedRoleEvent(adminRole) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_SCHEME_UPDATED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelSchemeUpdated, "", channel.Id, "", nil) a.Publish(message) mlog.Info("Permission scheme created.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } else { @@ -1052,7 +1052,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM return nil, err } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_SCHEME_UPDATED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelSchemeUpdated, "", channel.Id, "", nil) a.Publish(message) memberRole = higherScopedMemberRole @@ -1199,7 +1199,7 @@ func (a *App) UpdateChannelMemberSchemeRoles(channelID string, userID string, is // If the migration is not completed, we also need to check the default channel_admin/channel_user roles are not present in the roles field. if err = a.IsPhase2MigrationCompleted(); err != nil { - member.ExplicitRoles = RemoveRoles([]string{model.CHANNEL_GUEST_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID}, member.ExplicitRoles) + member.ExplicitRoles = RemoveRoles([]string{model.ChannelGuestRoleId, model.ChannelUserRoleId, model.ChannelAdminRoleId}, member.ExplicitRoles) } return a.updateChannelMember(member) @@ -1213,24 +1213,24 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID s } // update whichever notify properties have been provided, but don't change the others - if markUnread, exists := data[model.MARK_UNREAD_NOTIFY_PROP]; exists { - member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = markUnread + if markUnread, exists := data[model.MarkUnreadNotifyProp]; exists { + member.NotifyProps[model.MarkUnreadNotifyProp] = markUnread } - if desktop, exists := data[model.DESKTOP_NOTIFY_PROP]; exists { - member.NotifyProps[model.DESKTOP_NOTIFY_PROP] = desktop + if desktop, exists := data[model.DesktopNotifyProp]; exists { + member.NotifyProps[model.DesktopNotifyProp] = desktop } - if email, exists := data[model.EMAIL_NOTIFY_PROP]; exists { - member.NotifyProps[model.EMAIL_NOTIFY_PROP] = email + if email, exists := data[model.EmailNotifyProp]; exists { + member.NotifyProps[model.EmailNotifyProp] = email } - if push, exists := data[model.PUSH_NOTIFY_PROP]; exists { - member.NotifyProps[model.PUSH_NOTIFY_PROP] = push + if push, exists := data[model.PushNotifyProp]; exists { + member.NotifyProps[model.PushNotifyProp] = push } - if ignoreChannelMentions, exists := data[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP]; exists { - member.NotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] = ignoreChannelMentions + if ignoreChannelMentions, exists := data[model.IgnoreChannelMentionsNotifyProp]; exists { + member.NotifyProps[model.IgnoreChannelMentionsNotifyProp] = ignoreChannelMentions } member, err = a.updateChannelMember(member) @@ -1261,7 +1261,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe a.InvalidateCacheForUser(member.UserId) // Notify the clients that the member notify props changed - evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", member.UserId, nil) + evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil) evt.Add("channelMember", member.ToJson()) a.Publish(evt) @@ -1317,8 +1317,8 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s return err } - if channel.Name == model.DEFAULT_CHANNEL { - err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) + if channel.Name == model.DefaultChannelName { + err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) return err } @@ -1328,7 +1328,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(T("api.channel.delete_channel.archived"), user.Username), - Type: model.POST_CHANNEL_DELETED, + Type: model.PostTypeChannelDeleted, UserId: userID, Props: model.StringInterface{ "username": user.Username, @@ -1349,7 +1349,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.channel.delete_channel.archived"), systemBot.Username), - Type: model.POST_CHANNEL_DELETED, + Type: model.PostTypeChannelDeleted, UserId: systemBot.UserId, Props: model.StringInterface{ "username": systemBot.Username, @@ -1383,7 +1383,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s } a.invalidateCacheForChannel(channel) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_DELETED, channel.TeamId, "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil) message.Add("channel_id", channel.Id) message.Add("delete_at", deleteAt) a.Publish(message) @@ -1392,7 +1392,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s } func (a *App) addUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { - if channel.Type != model.CHANNEL_OPEN && channel.Type != model.CHANNEL_PRIVATE { + if channel.Type != model.ChannelTypeOpen && channel.Type != model.ChannelTypePrivate { return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) } @@ -1472,7 +1472,7 @@ func (a *App) AddUserToChannel(user *model.User, channel *model.Channel, skipTea return nil, err } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ADDED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserAdded, "", channel.Id, "", nil) message.Add("user_id", user.Id) message.Add("team_id", channel.TeamId) a.Publish(message) @@ -1560,7 +1560,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError preference := model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: profile.Id, Value: "true", } @@ -1597,7 +1597,7 @@ func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string, post := &model.Post{ ChannelId: channel.Id, Message: message, - Type: model.POST_HEADER_CHANGE, + Type: model.PostTypeHeaderChange, UserId: userID, Props: model.StringInterface{ "username": user.Username, @@ -1631,7 +1631,7 @@ func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string, post := &model.Post{ ChannelId: channel.Id, Message: message, - Type: model.POST_PURPOSE_CHANGE, + Type: model.PostTypePurposeChange, UserId: userID, Props: model.StringInterface{ "username": user.Username, @@ -1657,7 +1657,7 @@ func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID str post := &model.Post{ ChannelId: channel.Id, Message: message, - Type: model.POST_DISPLAYNAME_CHANGE, + Type: model.PostTypeDisplaynameChange, UserId: userID, Props: model.StringInterface{ "username": user.Username, @@ -1984,7 +1984,7 @@ func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread, } } - if channelUnread.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_MARK_UNREAD_MENTION { + if channelUnread.NotifyProps[model.MarkUnreadNotifyProp] == model.ChannelMarkUnreadMention { channelUnread.MsgCount = 0 channelUnread.MsgCountRoot = 0 } @@ -2024,7 +2024,7 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str user := uresult.Data.(*model.User) - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { return model.NewAppError("JoinChannel", "api.channel.join_channel.permissions.app_error", nil, "", http.StatusBadRequest) } @@ -2052,11 +2052,11 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.join_channel.post_and_forget"), user.Username) - postType := model.POST_JOIN_CHANNEL + postType := model.PostTypeJoinChannel if user.IsGuest() { message = fmt.Sprintf(i18n.T("api.channel.guest_join_channel.post_and_forget"), user.Username) - postType = model.POST_GUEST_JOIN_CHANNEL + postType = model.PostTypeGuestJoinChannel } post := &model.Post{ @@ -2080,7 +2080,7 @@ func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.join_team.post_and_forget"), user.Username), - Type: model.POST_JOIN_TEAM, + Type: model.PostTypeJoinTeam, UserId: user.Id, Props: model.StringInterface{ "username": user.Username, @@ -2150,7 +2150,7 @@ func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) return err } - if channel.Type == model.CHANNEL_PRIVATE && membersCount == 1 { + if channel.Type == model.ChannelTypePrivate && membersCount == 1 { err := model.NewAppError("LeaveChannel", "api.channel.leave.last_member.app_error", nil, "userId="+user.Id, http.StatusBadRequest) return err } @@ -2159,7 +2159,7 @@ func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) return err } - if channel.Name == model.DEFAULT_CHANNEL && !*a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { + if channel.Name == model.DefaultChannelName && !*a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { return nil } @@ -2177,7 +2177,7 @@ func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, chan // treat this as a username mention even though the user has now left the channel. // The client renders its own system message, ignoring this value altogether. Message: fmt.Sprintf(i18n.T("api.channel.leave.left"), fmt.Sprintf("@%s", user.Username)), - Type: model.POST_LEAVE_CHANNEL, + Type: model.PostTypeLeaveChannel, UserId: user.Id, Props: model.StringInterface{ "username": user.Username, @@ -2193,11 +2193,11 @@ func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, chan func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.add_member.added"), addedUser.Username, user.Username) - postType := model.POST_ADD_TO_CHANNEL + postType := model.PostTypeAddToChannel if addedUser.IsGuest() { message = fmt.Sprintf(i18n.T("api.channel.add_guest.added"), addedUser.Username, user.Username) - postType = model.POST_ADD_GUEST_TO_CHANNEL + postType = model.PostTypeAddGuestToChannel } post := &model.Post{ @@ -2207,10 +2207,10 @@ func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, adde UserId: user.Id, RootId: postRootId, Props: model.StringInterface{ - "userId": user.Id, - "username": user.Username, - model.POST_PROPS_ADDED_USER_ID: addedUser.Id, - "addedUsername": addedUser.Username, + "userId": user.Id, + "username": user.Username, + model.PostPropsAddedUserId: addedUser.Id, + "addedUsername": addedUser.Username, }, } @@ -2225,14 +2225,14 @@ func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUs post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.add_user_to_team.added"), addedUser.Username, user.Username), - Type: model.POST_ADD_TO_TEAM, + Type: model.PostTypeAddToTeam, UserId: user.Id, RootId: postRootId, Props: model.StringInterface{ - "userId": user.Id, - "username": user.Username, - model.POST_PROPS_ADDED_USER_ID: addedUser.Id, - "addedUsername": addedUser.Username, + "userId": user.Id, + "username": user.Username, + model.PostPropsAddedUserId: addedUser.Id, + "addedUsername": addedUser.Username, }, } @@ -2260,7 +2260,7 @@ func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId str // treat this as a username mention even though the user has now left the channel. // The client renders its own system message, ignoring this value altogether. Message: fmt.Sprintf(i18n.T("api.channel.remove_member.removed"), fmt.Sprintf("@%s", removedUser.Username)), - Type: model.POST_REMOVE_FROM_CHANNEL, + Type: model.PostTypeRemoveFromChannel, UserId: messageUserId, Props: model.StringInterface{ "removedUserId": removedUser.Id, @@ -2288,9 +2288,9 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r } isGuest := user.IsGuest() - if channel.Name == model.DEFAULT_CHANNEL { + if channel.Name == model.DefaultChannelName { if !isGuest { - return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) + return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest) } } @@ -2351,13 +2351,13 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r }) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_REMOVED, "", channel.Id, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserRemoved, "", channel.Id, "", nil) message.Add("user_id", userIDToRemove) message.Add("remover_id", removerUserId) a.Publish(message) // because the removed user no longer belongs to the channel we need to send a separate websocket event - userMsg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_REMOVED, "", "", userIDToRemove, nil) + userMsg := model.NewWebSocketEvent(model.WebsocketEventUserRemoved, "", "", userIDToRemove, nil) userMsg.Add("channel_id", channel.Id) userMsg.Add("remover_id", removerUserId) a.Publish(userMsg) @@ -2410,15 +2410,15 @@ func (a *App) GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) { func (a *App) SetActiveChannel(userID string, channelID string) *model.AppError { status, err := a.GetStatus(userID) - oldStatus := model.STATUS_OFFLINE + oldStatus := model.StatusOffline if err != nil { - status = &model.Status{UserId: userID, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: channelID} + status = &model.Status{UserId: userID, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: channelID} } else { oldStatus = status.Status status.ActiveChannel = channelID if !status.Manual && channelID != "" { - status.Status = model.STATUS_ONLINE + status.Status = model.StatusOnline } status.LastActivityAt = model.GetMillis() } @@ -2445,7 +2445,7 @@ func (a *App) UpdateChannelLastViewedAt(channelIDs []string, userID string) *mod if *a.Config().ServiceSettings.EnableChannelViewedMessages { for _, channelID := range channelIDs { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelViewed, "", "", userID, nil) message.Add("channel_id", channelID) a.Publish(message) } @@ -2455,12 +2455,12 @@ func (a *App) UpdateChannelLastViewedAt(channelIDs []string, userID string) *mod } func (a *App) isCRTEnabledForUser(userID string) bool { - if *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DISABLED { + if *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDisabled { return false } - threadsEnabled := *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DEFAULT_ON + threadsEnabled := *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDefaultOn // check if a participant has overridden collapsed threads settings - if preference, err := a.Srv().Store.Preference().Get(userID, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED); err == nil { + if preference, err := a.Srv().Store.Preference().Get(userID, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil { threadsEnabled = preference.Value == "on" } return threadsEnabled @@ -2537,7 +2537,7 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapse thread.Post.SanitizeProps() payload := thread.ToJson() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, channel.TeamId, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil) message.Add("thread", payload) a.Publish(message) } @@ -2653,7 +2653,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st payload := thread.ToJson() if a.isCRTEnabledForUser(userID) { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, channel.TeamId, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil) message.Add("thread", payload) a.Publish(message) } @@ -2665,7 +2665,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st } func (a *App) sendWebSocketPostUnreadEvent(channelUnread *model.ChannelUnreadAt, postID string, withMsgCountRoot bool) { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_UNREAD, channelUnread.TeamId, channelUnread.ChannelId, channelUnread.UserId, nil) + message := model.NewWebSocketEvent(model.WebsocketEventPostUnread, channelUnread.TeamId, channelUnread.ChannelId, channelUnread.UserId, nil) message.Add("msg_count", channelUnread.MsgCount) if withMsgCountRoot { message.Add("msg_count_root", channelUnread.MsgCountRoot) @@ -2810,22 +2810,22 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe continue } - notify := member.NotifyProps[model.PUSH_NOTIFY_PROP] - if notify == model.CHANNEL_NOTIFY_DEFAULT { + notify := member.NotifyProps[model.PushNotifyProp] + if notify == model.ChannelNotifyDefault { user, err := a.GetUser(userID) if err != nil { mlog.Warn("Failed to get user", mlog.String("user_id", userID), mlog.Err(err)) continue } - notify = user.NotifyProps[model.PUSH_NOTIFY_PROP] + notify = user.NotifyProps[model.PushNotifyProp] } - if notify == model.USER_NOTIFY_ALL { + if notify == model.UserNotifyAll { if count, err := a.Srv().Store.User().GetAnyUnreadPostCountForChannel(userID, channelID); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID) } } - } else if notify == model.USER_NOTIFY_MENTION || channel.Type == model.CHANNEL_DIRECT { + } else if notify == model.UserNotifyMention || channel.Type == model.ChannelTypeDirect { if count, err := a.Srv().Store.User().GetUnreadCountForChannel(userID, channelID); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID) @@ -2847,7 +2847,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe if *a.Config().ServiceSettings.EnableChannelViewedMessages { for _, channelID := range channelIDs { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelViewed, "", "", userID, nil) message.Add("channel_id", channelID) a.Publish(message) } @@ -2864,7 +2864,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe if a.isCRTEnabledForUser(userID) { timestamp := model.GetMillis() for _, channelID := range channelIDs { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_READ_CHANGED, "", channelID, userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadReadChanged, "", channelID, userID, nil) message.Add("timestamp", timestamp) a.Publish(message) } @@ -2920,7 +2920,7 @@ func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { } a.invalidateCacheForChannel(channel) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_DELETED, channel.TeamId, "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil) message.Add("channel_id", channel.Id) message.Add("delete_at", deleteAt) a.Publish(message) @@ -3045,7 +3045,7 @@ func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, chann post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.move_channel.success"), previousTeam.Name), - Type: model.POST_MOVE_CHANNEL, + Type: model.PostTypeMoveChannel, UserId: user.Id, Props: model.StringInterface{ "username": user.Username, @@ -3179,7 +3179,7 @@ func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) ( for _, member := range updated { a.invalidateCacheForChannelMembersNotifyProps(member.ChannelId) - evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", member.UserId, nil) + evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil) evt.Add("channelMember", member.ToJson()) a.Publish(evt) } @@ -3231,7 +3231,7 @@ func (a *App) FillInChannelsProps(channelList *model.ChannelList) *model.AppErro channelMentionsProp := make(map[string]interface{}, len(channelMentions[channel])) for _, channelMention := range channelMentions[channel] { if mentioned, ok := mentionedChannelsByName[channelMention]; ok { - if mentioned.Type == model.CHANNEL_OPEN { + if mentioned.Type == model.ChannelTypeOpen { channelMentionsProp[mentioned.Name] = map[string]interface{}{ "display_name": mentioned.DisplayName, } @@ -3281,7 +3281,7 @@ func (a *App) forEachChannelMember(channelID string, f func(model.ChannelMember) func (a *App) ClearChannelMembersCache(channelID string) { clearSessionCache := func(channelMember model.ChannelMember) error { a.ClearSessionCacheForUser(channelMember.UserId) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", channelMember.UserId, nil) + message := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", channelMember.UserId, nil) message.Add("channelMember", channelMember.ToJson()) a.Publish(message) return nil diff --git a/app/channel_category.go b/app/channel_category.go index 48bc3901cb..a8047bbffc 100644 --- a/app/channel_category.go +++ b/app/channel_category.go @@ -86,7 +86,7 @@ func (a *App) CreateSidebarCategory(userID, teamID string, newCategory *model.Si return nil, model.NewAppError("CreateSidebarCategory", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError) } } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_CREATED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryCreated, teamID, "", userID, nil) message.Add("category_id", category.Id) a.Publish(message) return category, nil @@ -106,7 +106,7 @@ func (a *App) UpdateSidebarCategoryOrder(userID, teamID string, categoryOrder [] return model.NewAppError("UpdateSidebarCategoryOrder", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError) } } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_ORDER_UPDATED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryOrderUpdated, teamID, "", userID, nil) message.Add("order", categoryOrder) a.Publish(message) return nil @@ -118,7 +118,7 @@ func (a *App) UpdateSidebarCategories(userID, teamID string, categories []*model return nil, model.NewAppError("UpdateSidebarCategories", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, teamID, "", userID, nil) a.Publish(message) a.muteChannelsForUpdatedCategories(userID, updatedCategories, originalCategories) @@ -243,7 +243,7 @@ func (a *App) DeleteSidebarCategory(userID, teamID, categoryId string) *model.Ap } } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_DELETED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryDeleted, teamID, "", userID, nil) message.Add("category_id", categoryId) a.Publish(message) diff --git a/app/channel_test.go b/app/channel_test.go index 62a0188221..efcd9cac93 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -31,7 +31,7 @@ func TestPermanentDeleteChannel(t *testing.T) { *cfg.ServiceSettings.EnableOutgoingWebhooks = true }) - channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.NotNil(t, channel, "Channel shouldn't be nil") require.Nil(t, err) defer func() { @@ -169,7 +169,7 @@ func TestMoveChannel(t *testing.T) { channel3 := &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: sourceTeam.Id, CreatorId: th.BasicUser.Id, } @@ -352,7 +352,7 @@ func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) { defer th.TearDown() // creates a public channel and adds basic user to it - publicChannel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) + publicChannel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) // there should be a ChannelMemberHistory record for the user histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) @@ -367,7 +367,7 @@ func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) { defer th.TearDown() // creates a private channel and adds basic user to it - privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) + privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) // there should be a ChannelMemberHistory record for the user histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) @@ -380,7 +380,7 @@ func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) defer th.App.PermanentDeleteChannel(channel) require.Nil(t, err) require.Equal(t, channel.DisplayName, "Public 1") @@ -390,13 +390,13 @@ func TestUpdateChannelPrivacy(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) - privateChannel.Type = model.CHANNEL_OPEN + privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) + privateChannel.Type = model.ChannelTypeOpen publicChannel, err := th.App.UpdateChannelPrivacy(th.Context, privateChannel, th.BasicUser) require.Nil(t, err, "Failed to update channel privacy.") assert.Equal(t, publicChannel.Id, privateChannel.Id) - assert.Equal(t, publicChannel.Type, model.CHANNEL_OPEN) + assert.Equal(t, publicChannel.Type, model.ChannelTypeOpen) } func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) { @@ -496,7 +496,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { groupUserIds = append(groupUserIds, th.BasicUser.Id) groupUserIds = append(groupUserIds, user.Id) - channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) + channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) _, err = th.App.AddUserToChannel(user, channel, false) require.Nil(t, err, "Failed to add user to channel.") @@ -583,7 +583,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { groupUserIds = append(groupUserIds, th.BasicUser.Id) groupUserIds = append(groupUserIds, user.Id) - channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) + channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) _, err = th.App.AddChannelMember(th.Context, user.Id, channel, ChannelMemberOpts{}) require.Nil(t, err, "Failed to add user to channel.") @@ -605,7 +605,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { if assert.Len(t, postList.Order, 1) { post := postList.Posts[postList.Order[0]] - assert.Equal(t, model.POST_JOIN_CHANNEL, post.Type) + assert.Equal(t, model.PostTypeJoinChannel, post.Type) assert.Equal(t, user.Id, post.UserId) assert.Equal(t, user.Username, post.GetProp("username")) } @@ -682,15 +682,15 @@ func TestFillInChannelProps(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPublic1) - channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPublic2) - channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false) + channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPrivate) @@ -699,13 +699,13 @@ func TestFillInChannelProps(t *testing.T) { DisplayName: "dn_" + otherTeamId, Name: "name" + otherTeamId, Email: "success+" + otherTeamId + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } otherTeam, err = th.App.CreateTeam(th.Context, otherTeam) require.Nil(t, err) defer th.App.PermanentDeleteTeam(otherTeam) - channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false) + channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.ChannelTypeOpen, TeamId: otherTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelOtherTeam) @@ -897,7 +897,7 @@ func TestRenameChannel(t *testing.T) { }{ { "Rename open channel", - th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), + th.createChannel(th.BasicTeam, model.ChannelTypeOpen), false, "newchannelname", "newchannelname", @@ -905,7 +905,7 @@ func TestRenameChannel(t *testing.T) { }, { "Fail on rename open channel with bad name", - th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), + th.createChannel(th.BasicTeam, model.ChannelTypeOpen), true, "6zii9a9g6pruzj451x3esok54h__wr4j4g8zqtnhmkw771pfpynqwo", "", @@ -913,7 +913,7 @@ func TestRenameChannel(t *testing.T) { }, { "Success on rename open channel with consecutive underscores in name", - th.createChannel(th.BasicTeam, model.CHANNEL_OPEN), + th.createChannel(th.BasicTeam, model.ChannelTypeOpen), false, "foo__bar", "foo__bar", @@ -988,7 +988,7 @@ func TestGetChannelsForUser(t *testing.T) { channel := &model.Channel{ DisplayName: "Public", Name: "public", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, } @@ -1034,7 +1034,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) { channel := model.Channel{ DisplayName: fmt.Sprintf("Public %v", i), Name: fmt.Sprintf("public_%v", i), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } var rchannel *model.Channel @@ -1067,7 +1067,7 @@ func TestGetPrivateChannelsForTeam(t *testing.T) { channel := model.Channel{ DisplayName: fmt.Sprintf("Private %v", i), Name: fmt.Sprintf("private_%v", i), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: team.Id, } var rchannel *model.Channel @@ -1189,13 +1189,13 @@ func TestSearchChannelsForUser(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer func() { @@ -1539,7 +1539,7 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { manageMembers := model.ChannelModeratedPermissions[2] channelMentions := model.ChannelModeratedPermissions[3] - nonChannelModeratedPermission := model.PERMISSION_CREATE_BOT.Id + nonChannelModeratedPermission := model.PermissionCreateBot.Id testCases := []struct { Name string @@ -1942,11 +1942,11 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { _, err := th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) require.Nil(t, err) - require.True(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PERMISSION_CREATE_POST)) + require.True(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost)) _, err = th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) require.Nil(t, err) - require.False(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PERMISSION_CREATE_POST)) + require.False(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost)) }) } @@ -1963,7 +1963,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) { mockChannelStore.On("Get", "channelID", true).Return(&model.Channel{}, nil) mockChannelStore.On("GetMember", context.Background(), "channelID", "userID").Return(&model.ChannelMember{ NotifyProps: model.StringMap{ - model.PUSH_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, + model.PushNotifyProp: model.ChannelNotifyDefault, }}, nil) times := map[string]int64{ "userID": 1, @@ -2049,14 +2049,14 @@ func TestViewChannelCollapsedThreadsTurnedOff(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) // Turn off CRT for user preference := model.Preference{ UserId: u1.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameCollapsedThreadsEnabled, Value: "off", } var preferences model.Preferences @@ -2123,7 +2123,7 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) th.AddUserToChannel(th.BasicUser2, th.BasicChannel) @@ -2131,8 +2131,8 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) { // Turn off CRT for user preference := model.Preference{ UserId: th.BasicUser.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameCollapsedThreadsEnabled, Value: "off", } var preferences model.Preferences @@ -2210,7 +2210,7 @@ func TestMarkUnreadWithThreads(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) t.Run("Follow threads only if specified", func(t *testing.T) { diff --git a/app/cloud.go b/app/cloud.go index db433cd0c2..2f78167398 100644 --- a/app/cloud.go +++ b/app/cloud.go @@ -17,7 +17,7 @@ func (a *App) getSysAdminsEmailRecipients() ([]*model.User, *model.AppError) { userOptions := &model.UserGetOptions{ Page: 0, PerPage: 100, - Role: model.SYSTEM_ADMIN_ROLE_ID, + Role: model.SystemAdminRoleId, Inactive: false, } return a.GetUsers(userOptions) diff --git a/app/cluster_discovery_test.go b/app/cluster_discovery_test.go index e9ba0e72c6..05041e4b5f 100644 --- a/app/cluster_discovery_test.go +++ b/app/cluster_discovery_test.go @@ -15,7 +15,7 @@ func TestClusterDiscoveryService(t *testing.T) { defer th.TearDown() ds := th.App.NewClusterDiscoveryService() - ds.Type = model.CDS_TYPE_APP + ds.Type = model.CDSTypeApp ds.ClusterName = "ClusterA" ds.AutoFillHostname() diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index 12e17eb248..f8138d5979 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -53,19 +53,19 @@ func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) { // The cluster event handlers are spread across this function and NewLocalCacheLayer. // Be careful to not have duplicated handlers here and there. func (s *Server) registerClusterHandlers() { - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, s.clusterPublishHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, s.clusterUpdateStatusHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, s.clusterInvalidateAllCachesHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, s.clusterInvalidateCacheForChannelMembersNotifyPropHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, s.clusterInvalidateCacheForChannelByNameHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, s.clusterInvalidateCacheForUserHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, s.clusterInvalidateCacheForUserTeamsHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, s.clusterBusyStateChgHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, s.clusterClearSessionCacheForUserHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, s.clusterClearSessionCacheForAllUsersHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, s.clusterInstallPluginHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, s.clusterRemovePluginHandler) - s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PLUGIN_EVENT, s.clusterPluginEventHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPublish, s.clusterPublishHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventUpdateStatus, s.clusterUpdateStatusHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateAllCaches, s.clusterInvalidateAllCachesHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, s.clusterInvalidateCacheForChannelMembersNotifyPropHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelByName, s.clusterInvalidateCacheForChannelByNameHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUser, s.clusterInvalidateCacheForUserHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUserTeams, s.clusterInvalidateCacheForUserTeamsHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventBusyStateChanged, s.clusterBusyStateChgHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForUser, s.clusterClearSessionCacheForUserHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForAllUsers, s.clusterClearSessionCacheForAllUsersHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInstallPlugin, s.clusterInstallPluginHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventRemovePlugin, s.clusterRemovePluginHandler) + s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPluginEvent, s.clusterPluginEventHandler) } func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) { diff --git a/app/command.go b/app/command.go index 2ead77253b..6b208bb818 100644 --- a/app/command.go +++ b/app/command.go @@ -56,7 +56,7 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str post.CreateAt = model.GetMillis() - if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) { + if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { err := model.NewAppError("CreateCommandPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -65,11 +65,11 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str model.ParseSlackAttachment(post, response.Attachments) } - if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL { + if response.ResponseType == model.CommandResponseTypeInChannel { return a.CreatePostMissingChannel(c, post, true) } - if (response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL) && (response.Text != "" || response.Attachments != nil) { + if (response.ResponseType == "" || response.ResponseType == model.CommandResponseTypeEphemeral) && (response.Text != "" || response.Attachments != nil) { post.ParentId = "" a.SendEphemeralPost(post.UserId, post) } @@ -477,7 +477,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command // Prepare the request var req *http.Request var err error - if cmd.Method == model.COMMAND_METHOD_GET { + if cmd.Method == model.CommandMethodGet { req, err = http.NewRequest(http.MethodGet, cmd.URL, nil) } else { req, err = http.NewRequest(http.MethodPost, cmd.URL, strings.NewReader(p.Encode())) @@ -487,7 +487,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) } - if cmd.Method == model.COMMAND_METHOD_GET { + if cmd.Method == model.CommandMethodGet { if req.URL.RawQuery != "" { req.URL.RawQuery += "&" } @@ -496,7 +496,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Token "+cmd.Token) - if cmd.Method == model.COMMAND_METHOD_POST { + if cmd.Method == model.CommandMethodPost { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } diff --git a/app/command_autocomplete.go b/app/command_autocomplete.go index a5e28e6a4a..1db392e3ae 100644 --- a/app/command_autocomplete.go +++ b/app/command_autocomplete.go @@ -54,7 +54,7 @@ func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs, if index == -1 { // no space in input for _, command := range commands { - if strings.HasPrefix(command.Trigger, strings.ToLower(inputToBeParsed)) && (command.RoleID == roleID || roleID == model.SYSTEM_ADMIN_ROLE_ID || roleID == "") { + if strings.HasPrefix(command.Trigger, strings.ToLower(inputToBeParsed)) && (command.RoleID == roleID || roleID == model.SystemAdminRoleId || roleID == "") { s := model.AutocompleteSuggestion{ Complete: inputParsed + command.Trigger, Suggestion: command.Trigger, @@ -71,7 +71,7 @@ func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs, if command.Trigger != strings.ToLower(inputToBeParsed[:index]) { continue } - if roleID != "" && roleID != model.SYSTEM_ADMIN_ROLE_ID && roleID != command.RoleID { + if roleID != "" && roleID != model.SystemAdminRoleId && roleID != command.RoleID { continue } toBeParsed := inputToBeParsed[index+1:] diff --git a/app/command_autocomplete_test.go b/app/command_autocomplete_test.go index 49b379064e..3f7b1df22f 100644 --- a/app/command_autocomplete_test.go +++ b/app/command_autocomplete_test.go @@ -208,21 +208,21 @@ func TestSuggestions(t *testing.T) { jira := createJiraAutocompleteData() emptyCmdArgs := &model.CommandArgs{} - suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, jira.Trigger, suggestions[0].Complete) assert.Equal(t, jira.Trigger, suggestions[0].Suggestion) assert.Equal(t, "[command]", suggestions[0].Hint) assert.Equal(t, jira.HelpText, suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create", suggestions[0].Complete) assert.Equal(t, "create", suggestions[0].Suggestion) assert.Equal(t, "[issue text]", suggestions[0].Hint) assert.Equal(t, "Create a new Issue", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "jira create", suggestions[1].Complete) assert.Equal(t, "create", suggestions[1].Suggestion) @@ -233,27 +233,27 @@ func TestSuggestions(t *testing.T) { assert.Equal(t, "[url]", suggestions[0].Hint) assert.Equal(t, "Connect your Mattermost account to your Jira account", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create some", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SystemAdminRoleId) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SystemAdminRoleId) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "jira settings notifications On", suggestions[0].Complete) assert.Equal(t, "On", suggestions[0].Suggestion) @@ -264,48 +264,48 @@ func TestSuggestions(t *testing.T) { assert.Equal(t, "Turn notifications off", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SystemAdminRoleId) assert.Len(t, suggestions, 11) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SystemUserRoleId) assert.Len(t, suggestions, 9) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create \"some issue text", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "--zone", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "--zone", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone bla", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SystemAdminRoleId) assert.Len(t, suggestions, 0) commandA := &model.Command{ @@ -320,7 +320,7 @@ func TestSuggestions(t *testing.T) { Trigger: "charles", AutocompleteData: model.NewAutocompleteData("charles", "", ""), } - suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "alice", suggestions[0].Complete) assert.Equal(t, "bob", suggestions[1].Complete) @@ -334,14 +334,14 @@ func TestCommandWithOptionalArgs(t *testing.T) { command := createCommandWithOptionalArgs() emptyCmdArgs := &model.CommandArgs{} - suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, command.Trigger, suggestions[0].Complete) assert.Equal(t, command.Trigger, suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, command.HelpText, suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SystemAdminRoleId) assert.Len(t, suggestions, 4) assert.Equal(t, "command subcommand1", suggestions[0].Complete) assert.Equal(t, "subcommand1", suggestions[0].Suggestion) @@ -356,7 +356,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "", suggestions[2].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -367,21 +367,21 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand1 item1 --name2 ", suggestions[0].Complete) assert.Equal(t, "--name2", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand1 item1 --name2 bla", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -392,7 +392,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "arg2", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -403,7 +403,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "arg2", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -418,7 +418,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -433,24 +433,24 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand2 --name1 item1 ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand2 --name1 item1 bla ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg3", suggestions[0].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SystemAdminRoleId) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -465,7 +465,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -480,7 +480,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand3 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -491,7 +491,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand4 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -502,7 +502,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "message", suggestions[1].Hint) assert.Equal(t, "help4", suggestions[1].Description) - suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SystemAdminRoleId) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand4 item1 ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) @@ -591,7 +591,7 @@ func createJiraAutocompleteData() *model.AutocompleteData { jira.AddCommand(timezone) install := model.NewAutocompleteData("install", "", "Connect Mattermost to a Jira instance") - install.RoleID = model.SYSTEM_ADMIN_ROLE_ID + install.RoleID = model.SystemAdminRoleId cloud := model.NewAutocompleteData("cloud", "", "Connect to a Jira Cloud instance") urlPattern := "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)" cloud.AddTextArgument("input URL of the Jira Cloud instance", "[URL]", urlPattern) @@ -602,7 +602,7 @@ func createJiraAutocompleteData() *model.AutocompleteData { jira.AddCommand(install) uninstall := model.NewAutocompleteData("uninstall", "", "Disconnect Mattermost from a Jira instance") - uninstall.RoleID = model.SYSTEM_ADMIN_ROLE_ID + uninstall.RoleID = model.SystemAdminRoleId cloud = model.NewAutocompleteData("cloud", "", "Disconnect from a Jira Cloud instance") cloud.AddTextArgument("input URL of the Jira Cloud instance", "[URL]", urlPattern) uninstall.AddCommand(cloud) @@ -625,7 +625,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) { emptyCmdArgs := &model.CommandArgs{} t.Run("GetAutoCompleteListItems", func(t *testing.T) { - suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SystemAdminRoleId) assert.Len(t, suggestions, 3) assert.Equal(t, "this is hint 1", suggestions[0].Hint) assert.Equal(t, "this is hint 2", suggestions[1].Hint) @@ -633,7 +633,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) { }) t.Run("GetAutoCompleteListItems bad arg", func(t *testing.T) { - suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SystemAdminRoleId) assert.Empty(t, suggestions) }) } @@ -662,7 +662,7 @@ func (p *testCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model.Co func (p *testCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return &model.CommandResponse{ Text: "I do nothing!", - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/compliance.go b/app/compliance.go index b95923ab2b..0b4efaeaab 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -30,7 +30,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - job.Type = model.COMPLIANCE_TYPE_ADHOC + job.Type = model.ComplianceTypeAdhoc job, err := a.Srv().Store.Compliance().Save(job) if err != nil { diff --git a/app/config.go b/app/config.go index 4418ae5f62..4277758bb9 100644 --- a/app/config.go +++ b/app/config.go @@ -116,7 +116,7 @@ func (s *Server) ensurePostActionCookieSecret() error { var secret *model.SystemPostActionCookieSecret - value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := s.Store.System().GetByName(model.SystemPostActionCookieSecretKey) if err == nil { if err := json.Unmarshal([]byte(value.Value), &secret); err != nil { return err @@ -134,7 +134,7 @@ func (s *Server) ensurePostActionCookieSecret() error { } system := &model.System{ - Name: model.SYSTEM_POST_ACTION_COOKIE_SECRET, + Name: model.SystemPostActionCookieSecretKey, } v, err := json.Marshal(newSecret) if err != nil { @@ -152,7 +152,7 @@ func (s *Server) ensurePostActionCookieSecret() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if secret == nil { - value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := s.Store.System().GetByName(model.SystemPostActionCookieSecretKey) if err != nil { return err } @@ -175,7 +175,7 @@ func (s *Server) ensureAsymmetricSigningKey() error { var key *model.SystemAsymmetricSigningKey - value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := s.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) if err == nil { if err := json.Unmarshal([]byte(value.Value), &key); err != nil { return err @@ -197,7 +197,7 @@ func (s *Server) ensureAsymmetricSigningKey() error { }, } system := &model.System{ - Name: model.SYSTEM_ASYMMETRIC_SIGNING_KEY, + Name: model.SystemAsymmetricSigningKeyKey, } v, err := json.Marshal(newKey) if err != nil { @@ -215,7 +215,7 @@ func (s *Server) ensureAsymmetricSigningKey() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if key == nil { - value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := s.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) if err != nil { return err } @@ -259,7 +259,7 @@ func (s *Server) ensureInstallationDate() error { } if err := s.Store.System().SaveOrUpdate(&model.System{ - Name: model.SYSTEM_INSTALLATION_DATE_KEY, + Name: model.SystemInstallationDateKey, Value: strconv.FormatInt(installationDate, 10), }); err != nil { return err @@ -274,7 +274,7 @@ func (s *Server) ensureFirstServerRunTimestamp() error { } if err := s.Store.System().SaveOrUpdate(&model.System{ - Name: model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY, + Name: model.SystemFirstServerRunTimestampKey, Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10), }); err != nil { return err diff --git a/app/config_test.go b/app/config_test.go index 48d4bc3e78..9296f0f913 100644 --- a/app/config_test.go +++ b/app/config_test.go @@ -135,10 +135,10 @@ func TestEnsureInstallationDate(t *testing.T) { } if tc.PrevInstallationDate == nil { - th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_INSTALLATION_DATE_KEY) + th.App.Srv().Store.System().PermanentDeleteByName(model.SystemInstallationDateKey) } else { th.App.Srv().Store.System().SaveOrUpdate(&model.System{ - Name: model.SYSTEM_INSTALLATION_DATE_KEY, + Name: model.SystemInstallationDateKey, Value: strconv.FormatInt(*tc.PrevInstallationDate, 10), }) } @@ -150,7 +150,7 @@ func TestEnsureInstallationDate(t *testing.T) { } else { assert.NoError(t, err) - data, err := th.App.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) + data, err := th.App.Srv().Store.System().GetByName(model.SystemInstallationDateKey) assert.NoError(t, err) value, _ := strconv.ParseInt(data.Value, 10, 64) assert.True(t, *tc.ExpectedInstallationDate <= value && *tc.ExpectedInstallationDate+1000 >= value) diff --git a/app/email/email_batching.go b/app/email/email_batching.go index 30637baa06..506df32dbb 100644 --- a/app/email/email_batching.go +++ b/app/email/email_batching.go @@ -181,14 +181,14 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu // get how long we need to wait to send notifications to the user var interval int64 - preference, err := job.service.store.Preference().Get(userID, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL) + preference, err := job.service.store.Preference().Get(userID, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval) if err != nil { // use the default batching interval if an error ocurrs while fetching user preferences - interval, _ = strconv.ParseInt(model.PREFERENCE_EMAIL_INTERVAL_BATCHING_SECONDS, 10, 64) + interval, _ = strconv.ParseInt(model.PreferenceEmailIntervalBatchingSeconds, 10, 64) } else { if value, err := strconv.ParseInt(preference.Value, 10, 64); err != nil { // // use the default batching interval if an error ocurrs while deserializing user preferences - interval, _ = strconv.ParseInt(model.PREFERENCE_EMAIL_INTERVAL_BATCHING_SECONDS, 10, 64) + interval, _ = strconv.ParseInt(model.PreferenceEmailIntervalBatchingSeconds, 10, 64) } else { interval = value } @@ -220,12 +220,12 @@ func (es *Service) sendBatchedEmailNotification(userID string, notifications []* postsData := make([]*postData, 0 /* len */, len(notifications) /* cap */) embeddedFiles := make(map[string]io.Reader) - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull if license := es.license(); license != nil && *license.Features.EmailNotificationContents { emailNotificationContentsType = *es.config().EmailSettings.EmailNotificationContentsType } - if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { + if emailNotificationContentsType == model.EmailNotificationContentsFull { for i, notification := range notifications { sender, errSender := es.userService.GetUser(notification.post.UserId) if errSender != nil { diff --git a/app/email/email_batching_test.go b/app/email/email_batching_test.go index 922ee1fb64..5de399dde7 100644 --- a/app/email/email_batching_test.go +++ b/app/email/email_batching_test.go @@ -98,8 +98,8 @@ func TestCheckPendingNotifications(t *testing.T) { nErr := th.store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, - Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, - Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, + Category: model.PreferenceCategoryNotifications, + Name: model.PreferenceNameEmailInterval, Value: "60", }}) require.NoError(t, nErr) @@ -120,8 +120,8 @@ func TestCheckPendingNotifications(t *testing.T) { // We reset the interval to something shorter nErr = th.store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, - Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, - Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, + Category: model.PreferenceCategoryNotifications, + Name: model.PreferenceNameEmailInterval, Value: "10", }}) require.NoError(t, nErr) @@ -256,8 +256,8 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { // preference value is not an integer, so we'll fall back to the default 15min value nErr := th.store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, - Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, - Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, + Category: model.PreferenceCategoryNotifications, + Name: model.PreferenceNameEmailInterval, Value: "notAnIntegerValue", }}) require.NoError(t, nErr) diff --git a/app/email/helper_test.go b/app/email/helper_test.go index 975a559ece..217001f443 100644 --- a/app/email/helper_test.go +++ b/app/email/helper_test.go @@ -54,7 +54,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(mockStore, tb) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -155,7 +155,7 @@ func (th *TestHelper) InitBasic() *TestHelper { th.BasicUser2, _ = th.service.userService.GetUser(th.BasicUser2.Id) th.addUserToTeam(th.BasicTeam, th.BasicUser2) - th.BasicChannel = th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) + th.BasicChannel = th.createChannel(th.BasicTeam, model.ChannelTypeOpen) th.addUserToChannel(th.BasicChannel, th.SystemAdminUser) th.addUserToChannel(th.BasicChannel, th.BasicUser) th.addUserToChannel(th.BasicChannel, th.BasicUser2) @@ -169,7 +169,7 @@ func (th *TestHelper) CreateTeam() *model.Team { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } utils.DisableDebugLogForTest() diff --git a/app/emoji.go b/app/emoji.go index 95c84ae3e6..c7cffe54bc 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -77,7 +77,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, model.NewAppError("CreateEmoji", "app.emoji.create.internal_error", nil, err.Error(), http.StatusInternalServerError) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventEmojiAdded, "", "", "", nil) message.Add("emoji", emoji.ToJson()) a.Publish(message) return emoji, nil diff --git a/app/expirynotify.go b/app/expirynotify.go index 97e79419c6..af0a452caf 100644 --- a/app/expirynotify.go +++ b/app/expirynotify.go @@ -32,8 +32,8 @@ func (a *App) NotifySessionsExpired() *model.AppError { } msg := &model.PushNotification{ - Version: model.PUSH_MESSAGE_V2, - Type: model.PUSH_TYPE_SESSION, + Version: model.PushMessageV2, + Type: model.PushTypeSession, } for _, session := range sessions { @@ -59,7 +59,7 @@ func (a *App) NotifySessionsExpired() *model.AppError { mlog.String("type", tmpMessage.Type), mlog.String("userId", session.UserId), mlog.String("deviceId", tmpMessage.DeviceId), - mlog.String("status", model.PUSH_SEND_SUCCESS), + mlog.String("status", model.PushSendSuccess), ) if a.Metrics() != nil { @@ -75,7 +75,7 @@ func (a *App) NotifySessionsExpired() *model.AppError { } func (a *App) getSessionExpiredPushMessage(session *model.Session) string { - locale := model.DEFAULT_LOCALE + locale := model.DefaultLocale user, err := a.GetUser(session.UserId) if err == nil { locale = user.Locale diff --git a/app/expirynotify_test.go b/app/expirynotify_test.go index 81c5a5fa5b..f49688b4c2 100644 --- a/app/expirynotify_test.go +++ b/app/expirynotify_test.go @@ -70,11 +70,11 @@ func TestNotifySessionsExpired(t *testing.T) { require.Equal(t, 2, handler.numReqs()) expected := []string{"22222", "33333"} - require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[0].Type) + require.Equal(t, model.PushTypeSession, handler.notifications()[0].Type) require.Contains(t, expected, handler.notifications()[0].DeviceId) require.Contains(t, handler.notifications()[0].Message, "Session Expired") - require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[1].Type) + require.Equal(t, model.PushTypeSession, handler.notifications()[1].Type) require.Contains(t, expected, handler.notifications()[1].DeviceId) require.Contains(t, handler.notifications()[1].Message, "Session Expired") }) diff --git a/app/export.go b/app/export.go index 05e4d38910..905c2738bb 100644 --- a/app/export.go +++ b/app/export.go @@ -32,35 +32,35 @@ const ExportDataDir = "data" // We use this map to identify the exportable preferences. // Here we link the preference category and name, to the name of the relevant field in the import struct. var exportablePreferences = map[ComparablePreference]string{{ - Category: model.PREFERENCE_CATEGORY_THEME, + Category: model.PreferenceCategoryTheme, Name: "", }: "Theme", { - Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, + Category: model.PreferenceCategoryAdvancedSettings, Name: "feature_enabled_markdown_preview", }: "UseMarkdownPreview", { - Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, + Category: model.PreferenceCategoryAdvancedSettings, Name: "formatting", }: "UseFormatting", { - Category: model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS, + Category: model.PreferenceCategorySidebarSettings, Name: "show_unread_section", }: "ShowUnreadSection", { - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_USE_MILITARY_TIME, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameUseMilitaryTime, }: "UseMilitaryTime", { - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_COLLAPSE_SETTING, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameCollapseSetting, }: "CollapsePreviews", { - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_MESSAGE_DISPLAY, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameMessageDisplay, }: "MessageDisplay", { - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, + Category: model.PreferenceCategoryDisplaySettings, Name: "channel_display_mode", }: "ChannelDisplayMode", { - Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, + Category: model.PreferenceCategoryTutorialSteps, Name: "", }: "TutorialStep", { - Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, - Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, + Category: model.PreferenceCategoryNotifications, + Name: model.PreferenceNameEmailInterval, }: "EmailInterval", } @@ -251,17 +251,17 @@ func (a *App) exportAllUsers(writer io.Writer) *model.AppError { for _, pref := range allPrefs { // We need to manage the special cases // Here we manage Tutorial steps - if pref.Category == model.PREFERENCE_CATEGORY_TUTORIAL_STEPS { + if pref.Category == model.PreferenceCategoryTutorialSteps { pref.Name = "" // Then the email interval - } else if pref.Category == model.PREFERENCE_CATEGORY_NOTIFICATIONS && pref.Name == model.PREFERENCE_NAME_EMAIL_INTERVAL { + } else if pref.Category == model.PreferenceCategoryNotifications && pref.Name == model.PreferenceNameEmailInterval { switch pref.Value { - case model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS: - pref.Value = model.PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY - case model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN_AS_SECONDS: - pref.Value = model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN - case model.PREFERENCE_EMAIL_INTERVAL_HOUR_AS_SECONDS: - pref.Value = model.PREFERENCE_EMAIL_INTERVAL_HOUR + case model.PreferenceEmailIntervalNoBatchingSeconds: + pref.Value = model.PreferenceEmailIntervalImmediately + case model.PreferenceEmailIntervalFifteenAsSeconds: + pref.Value = model.PreferenceEmailIntervalFifteen + case model.PreferenceEmailIntervalHourAsSeconds: + pref.Value = model.PreferenceEmailIntervalHour case "0": pref.Value = "" } @@ -325,7 +325,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userID string) (*[]UserTeamImpo } // Get the user theme - themePreference, nErr := a.Srv().Store.Preference().Get(member.UserId, model.PREFERENCE_CATEGORY_THEME, member.TeamId) + themePreference, nErr := a.Srv().Store.Preference().Get(member.UserId, model.PreferenceCategoryTheme, member.TeamId) if nErr == nil { memberData.Theme = &themePreference.Value } @@ -346,7 +346,7 @@ func (a *App) buildUserChannelMemberships(userID string, teamID string) (*[]User return nil, model.NewAppError("buildUserChannelMemberships", "app.channel.get_members.app_error", nil, nErr.Error(), http.StatusInternalServerError) } - category := model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL + category := model.PreferenceCategoryFavoriteChannel preferences, err := a.GetPreferenceByCategoryForUser(userID, category) if err != nil && err.StatusCode != http.StatusNotFound { return nil, err @@ -368,14 +368,14 @@ func (a *App) buildUserNotifyProps(notifyProps model.StringMap) *UserNotifyProps } return &UserNotifyPropsImportData{ - Desktop: getProp(model.DESKTOP_NOTIFY_PROP), - DesktopSound: getProp(model.DESKTOP_SOUND_NOTIFY_PROP), - Email: getProp(model.EMAIL_NOTIFY_PROP), - Mobile: getProp(model.PUSH_NOTIFY_PROP), - MobilePushStatus: getProp(model.PUSH_STATUS_NOTIFY_PROP), - ChannelTrigger: getProp(model.CHANNEL_MENTIONS_NOTIFY_PROP), - CommentsTrigger: getProp(model.COMMENTS_NOTIFY_PROP), - MentionKeys: getProp(model.MENTION_KEYS_NOTIFY_PROP), + Desktop: getProp(model.DesktopNotifyProp), + DesktopSound: getProp(model.DesktopSoundNotifyProp), + Email: getProp(model.EmailNotifyProp), + Mobile: getProp(model.PushNotifyProp), + MobilePushStatus: getProp(model.PushStatusNotifyProp), + ChannelTrigger: getProp(model.ChannelMentionsNotifyProp), + CommentsTrigger: getProp(model.CommentsNotifyProp), + MentionKeys: getProp(model.MentionKeysNotifyProp), } } @@ -518,7 +518,7 @@ func (a *App) exportCustomEmoji(writer io.Writer, outPath, exportDir string, exp var emojiPaths []string pageNumber := 0 for { - customEmojiList, err := a.GetEmojiList(pageNumber, 100, model.EMOJI_SORT_BY_NAME) + customEmojiList, err := a.GetEmojiList(pageNumber, 100, model.EmojiSortByName) if err != nil { return nil, err diff --git a/app/export_converters.go b/app/export_converters.go index 3c6eae442e..c4deac8b41 100644 --- a/app/export_converters.go +++ b/app/export_converters.go @@ -90,13 +90,13 @@ func ImportLineFromUser(user *model.User, exportedPrefs map[string]*string) *Lin func ImportUserTeamDataFromTeamMember(member *model.TeamMemberForExport) *UserTeamImportData { rolesList := strings.Fields(member.Roles) if member.SchemeAdmin { - rolesList = append(rolesList, model.TEAM_ADMIN_ROLE_ID) + rolesList = append(rolesList, model.TeamAdminRoleId) } if member.SchemeUser { - rolesList = append(rolesList, model.TEAM_USER_ROLE_ID) + rolesList = append(rolesList, model.TeamUserRoleId) } if member.SchemeGuest { - rolesList = append(rolesList, model.TEAM_GUEST_ROLE_ID) + rolesList = append(rolesList, model.TeamGuestRoleId) } roles := strings.Join(rolesList, " ") return &UserTeamImportData{ @@ -108,26 +108,26 @@ func ImportUserTeamDataFromTeamMember(member *model.TeamMemberForExport) *UserTe func ImportUserChannelDataFromChannelMemberAndPreferences(member *model.ChannelMemberForExport, preferences *model.Preferences) *UserChannelImportData { rolesList := strings.Fields(member.Roles) if member.SchemeAdmin { - rolesList = append(rolesList, model.CHANNEL_ADMIN_ROLE_ID) + rolesList = append(rolesList, model.ChannelAdminRoleId) } if member.SchemeUser { - rolesList = append(rolesList, model.CHANNEL_USER_ROLE_ID) + rolesList = append(rolesList, model.ChannelUserRoleId) } if member.SchemeGuest { - rolesList = append(rolesList, model.CHANNEL_GUEST_ROLE_ID) + rolesList = append(rolesList, model.ChannelGuestRoleId) } props := member.NotifyProps notifyProps := UserChannelNotifyPropsImportData{} - desktop, exist := props[model.DESKTOP_NOTIFY_PROP] + desktop, exist := props[model.DesktopNotifyProp] if exist { notifyProps.Desktop = &desktop } - mobile, exist := props[model.PUSH_NOTIFY_PROP] + mobile, exist := props[model.PushNotifyProp] if exist { notifyProps.Mobile = &mobile } - markUnread, exist := props[model.MARK_UNREAD_NOTIFY_PROP] + markUnread, exist := props[model.MarkUnreadNotifyProp] if exist { notifyProps.MarkUnread = &markUnread } diff --git a/app/export_test.go b/app/export_test.go index 2b5e971292..03f2988b60 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -52,26 +52,26 @@ func TestExportUserNotifyProps(t *testing.T) { defer th.TearDown() userNotifyProps := model.StringMap{ - model.DESKTOP_NOTIFY_PROP: model.USER_NOTIFY_ALL, - model.DESKTOP_SOUND_NOTIFY_PROP: "true", - model.EMAIL_NOTIFY_PROP: "true", - model.PUSH_NOTIFY_PROP: model.USER_NOTIFY_ALL, - model.PUSH_STATUS_NOTIFY_PROP: model.STATUS_ONLINE, - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", - model.COMMENTS_NOTIFY_PROP: model.COMMENTS_NOTIFY_ROOT, - model.MENTION_KEYS_NOTIFY_PROP: "valid,misc", + model.DesktopNotifyProp: model.UserNotifyAll, + model.DesktopSoundNotifyProp: "true", + model.EmailNotifyProp: "true", + model.PushNotifyProp: model.UserNotifyAll, + model.PushStatusNotifyProp: model.StatusOnline, + model.ChannelMentionsNotifyProp: "true", + model.CommentsNotifyProp: model.CommentsNotifyRoot, + model.MentionKeysNotifyProp: "valid,misc", } exportNotifyProps := th.App.buildUserNotifyProps(userNotifyProps) - require.Equal(t, userNotifyProps[model.DESKTOP_NOTIFY_PROP], *exportNotifyProps.Desktop) - require.Equal(t, userNotifyProps[model.DESKTOP_SOUND_NOTIFY_PROP], *exportNotifyProps.DesktopSound) - require.Equal(t, userNotifyProps[model.EMAIL_NOTIFY_PROP], *exportNotifyProps.Email) - require.Equal(t, userNotifyProps[model.PUSH_NOTIFY_PROP], *exportNotifyProps.Mobile) - require.Equal(t, userNotifyProps[model.PUSH_STATUS_NOTIFY_PROP], *exportNotifyProps.MobilePushStatus) - require.Equal(t, userNotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP], *exportNotifyProps.ChannelTrigger) - require.Equal(t, userNotifyProps[model.COMMENTS_NOTIFY_PROP], *exportNotifyProps.CommentsTrigger) - require.Equal(t, userNotifyProps[model.MENTION_KEYS_NOTIFY_PROP], *exportNotifyProps.MentionKeys) + require.Equal(t, userNotifyProps[model.DesktopNotifyProp], *exportNotifyProps.Desktop) + require.Equal(t, userNotifyProps[model.DesktopSoundNotifyProp], *exportNotifyProps.DesktopSound) + require.Equal(t, userNotifyProps[model.EmailNotifyProp], *exportNotifyProps.Email) + require.Equal(t, userNotifyProps[model.PushNotifyProp], *exportNotifyProps.Mobile) + require.Equal(t, userNotifyProps[model.PushStatusNotifyProp], *exportNotifyProps.MobilePushStatus) + require.Equal(t, userNotifyProps[model.ChannelMentionsNotifyProp], *exportNotifyProps.ChannelTrigger) + require.Equal(t, userNotifyProps[model.CommentsNotifyProp], *exportNotifyProps.CommentsTrigger) + require.Equal(t, userNotifyProps[model.MentionKeysNotifyProp], *exportNotifyProps.MentionKeys) } func TestExportUserChannels(t *testing.T) { @@ -82,12 +82,12 @@ func TestExportUserChannels(t *testing.T) { team := th.BasicTeam channelName := channel.Name notifyProps := model.StringMap{ - model.DESKTOP_NOTIFY_PROP: model.USER_NOTIFY_ALL, - model.PUSH_NOTIFY_PROP: model.USER_NOTIFY_NONE, + model.DesktopNotifyProp: model.UserNotifyAll, + model.PushNotifyProp: model.UserNotifyNone, } preference := model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", } diff --git a/app/file_test.go b/app/file_test.go index 1e50644c56..7810a528c9 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -234,7 +234,7 @@ func TestFindTeamIdForFilename(t *testing.T) { teamID := th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png") assert.Equal(t, th.BasicTeam.Id, teamID) - _, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id) + _, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TeamOpen}, th.BasicUser.Id) require.Nil(t, err) teamID = th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png") diff --git a/app/group.go b/app/group.go index f7393500b9..002286d239 100644 --- a/app/group.go +++ b/app/group.go @@ -96,7 +96,7 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) { updatedGroup, err := a.Srv().Store.Group().Update(group) if err == nil { - messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP, "", "", "", nil) + messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil) messageWs.Add("group", updatedGroup.ToJson()) a.Publish(messageWs) } @@ -121,7 +121,7 @@ func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) { deletedGroup, err := a.Srv().Store.Group().Delete(groupID) if err == nil { - messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP, "", "", "", nil) + messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil) messageWs.Add("group", deletedGroup.ToJson()) a.Publish(messageWs) } @@ -287,9 +287,9 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr var messageWs *model.WebSocketEvent if gs.Type == model.GroupSyncableTypeTeam { - messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_TEAM, gs.SyncableId, "", "", nil) + messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupAssociatedToTeam, gs.SyncableId, "", "", nil) } else { - messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_CHANNEL, "", gs.SyncableId, "", nil) + messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupAssociatedToChannel, "", gs.SyncableId, "", nil) } messageWs.Add("group_id", gs.GroupId) a.Publish(messageWs) @@ -388,9 +388,9 @@ func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableTyp var messageWs *model.WebSocketEvent if gs.Type == model.GroupSyncableTypeTeam { - messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_TEAM, gs.SyncableId, "", "", nil) + messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupNotAssociatedToTeam, gs.SyncableId, "", "", nil) } else { - messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_CHANNEL, "", gs.SyncableId, "", nil) + messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupNotAssociatedToChannel, "", gs.SyncableId, "", nil) } messageWs.Add("group_id", gs.GroupId) diff --git a/app/helper_test.go b/app/helper_test.go index a2e189e36e..64374a40ea 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -164,7 +164,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(mockStore, false, false, tb) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -179,7 +179,7 @@ func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(mockStore, true, false, tb) statusMock := mocks.StatusStore{} statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) - statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) emptyMockStore := mocks.Store{} @@ -200,7 +200,7 @@ func (th *TestHelper) InitBasic() *TestHelper { // create users once and cache them because password hashing is slow initBasicOnce.Do(func() { th.SystemAdminUser = th.CreateUser() - th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id) userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy() @@ -237,7 +237,7 @@ func (th *TestHelper) CreateTeam() *model.Team { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } utils.DisableDebugLogForTest() @@ -309,11 +309,11 @@ func WithShared(v bool) ChannelOption { } func (th *TestHelper) CreateChannel(team *model.Team, options ...ChannelOption) *model.Channel { - return th.createChannel(team, model.CHANNEL_OPEN, options...) + return th.createChannel(team, model.ChannelTypeOpen, options...) } func (th *TestHelper) CreatePrivateChannel(team *model.Team) *model.Channel { - return th.createChannel(team, model.CHANNEL_PRIVATE) + return th.createChannel(team, model.ChannelTypePrivate) } func (th *TestHelper) createChannel(team *model.Team, channelType string, options ...ChannelOption) *model.Channel { @@ -462,7 +462,7 @@ func (th *TestHelper) CreateScheme() (*model.Scheme, []*model.Role) { DisplayName: "Test Scheme Display Name", Name: model.NewId(), Description: "Test scheme description", - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }) if err != nil { panic(err) @@ -597,7 +597,7 @@ func (*TestHelper) ResetRoleMigration() { mainHelper.GetClusterInterface().SendClearRoleCacheMessage() - if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.ADVANCED_PERMISSIONS_MIGRATION_KEY}); err != nil { + if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.AdvancedPermissionsMigrationKey}); err != nil { panic(err) } } @@ -630,7 +630,7 @@ func (th *TestHelper) CheckTeamCount(t *testing.T, expected int64) { } func (th *TestHelper) CheckChannelsCount(t *testing.T, expected int64) { - count, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) + count, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) require.NoError(t, err, "Failed to get channel count.") require.Equalf(t, count, expected, "Unexpected number of channels. Expected: %v, found: %v", expected, count) } @@ -639,7 +639,7 @@ func (th *TestHelper) SetupTeamScheme() *model.Scheme { scheme, err := th.App.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }) if err != nil { panic(err) @@ -651,7 +651,7 @@ func (th *TestHelper) SetupChannelScheme() *model.Scheme { scheme, err := th.App.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }) if err != nil { panic(err) diff --git a/app/import_functions.go b/app/import_functions.go index 7d19c58b3b..bf6c19fa77 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -65,7 +65,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError return err } - if scheme.Scope == model.SCHEME_SCOPE_TEAM { + if scheme.Scope == model.SchemeScopeTeam { data.DefaultTeamAdminRole.Name = &scheme.DefaultTeamAdminRole if err := a.importRole(data.DefaultTeamAdminRole, dryRun, true); err != nil { return err @@ -87,7 +87,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError } } - if scheme.Scope == model.SCHEME_SCOPE_TEAM || scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope == model.SchemeScopeTeam || scheme.Scope == model.SchemeScopeChannel { data.DefaultChannelAdminRole.Name = &scheme.DefaultChannelAdminRole if err := a.importRole(data.DefaultChannelAdminRole, dryRun, true); err != nil { return err @@ -197,7 +197,7 @@ func (a *App) importTeam(c *request.Context, data *TeamImportData, dryRun bool) return model.NewAppError("BulkImport", "app.import.import_team.scheme_deleted.error", nil, "", http.StatusBadRequest) } - if scheme.Scope != model.SCHEME_SCOPE_TEAM { + if scheme.Scope != model.SchemeScopeTeam { return model.NewAppError("BulkImport", "app.import.import_team.scheme_wrong_scope.error", nil, "", http.StatusBadRequest) } @@ -262,7 +262,7 @@ func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun return model.NewAppError("BulkImport", "app.import.import_channel.scheme_deleted.error", nil, "", http.StatusBadRequest) } - if scheme.Scope != model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope != model.SchemeScopeChannel { return model.NewAppError("BulkImport", "app.import.import_channel.scheme_wrong_scope.error", nil, "", http.StatusBadRequest) } @@ -415,8 +415,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { } } else if user.Roles == "" { // Set SYSTEM_USER roles on newly created users by default. - if user.Roles != model.SYSTEM_USER_ROLE_ID { - roles = model.SYSTEM_USER_ROLE_ID + if user.Roles != model.SystemUserRoleId { + roles = model.SystemUserRoleId hasUserRolesChanged = true } } @@ -424,57 +424,57 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.NotifyProps != nil { if data.NotifyProps.Desktop != nil { - if value, ok := user.NotifyProps[model.DESKTOP_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Desktop { - user.AddNotifyProp(model.DESKTOP_NOTIFY_PROP, *data.NotifyProps.Desktop) + if value, ok := user.NotifyProps[model.DesktopNotifyProp]; !ok || value != *data.NotifyProps.Desktop { + user.AddNotifyProp(model.DesktopNotifyProp, *data.NotifyProps.Desktop) hasNotifyPropsChanged = true } } if data.NotifyProps.DesktopSound != nil { - if value, ok := user.NotifyProps[model.DESKTOP_SOUND_NOTIFY_PROP]; !ok || value != *data.NotifyProps.DesktopSound { - user.AddNotifyProp(model.DESKTOP_SOUND_NOTIFY_PROP, *data.NotifyProps.DesktopSound) + if value, ok := user.NotifyProps[model.DesktopSoundNotifyProp]; !ok || value != *data.NotifyProps.DesktopSound { + user.AddNotifyProp(model.DesktopSoundNotifyProp, *data.NotifyProps.DesktopSound) hasNotifyPropsChanged = true } } if data.NotifyProps.Email != nil { - if value, ok := user.NotifyProps[model.EMAIL_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Email { - user.AddNotifyProp(model.EMAIL_NOTIFY_PROP, *data.NotifyProps.Email) + if value, ok := user.NotifyProps[model.EmailNotifyProp]; !ok || value != *data.NotifyProps.Email { + user.AddNotifyProp(model.EmailNotifyProp, *data.NotifyProps.Email) hasNotifyPropsChanged = true } } if data.NotifyProps.Mobile != nil { - if value, ok := user.NotifyProps[model.PUSH_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Mobile { - user.AddNotifyProp(model.PUSH_NOTIFY_PROP, *data.NotifyProps.Mobile) + if value, ok := user.NotifyProps[model.PushNotifyProp]; !ok || value != *data.NotifyProps.Mobile { + user.AddNotifyProp(model.PushNotifyProp, *data.NotifyProps.Mobile) hasNotifyPropsChanged = true } } if data.NotifyProps.MobilePushStatus != nil { - if value, ok := user.NotifyProps[model.PUSH_STATUS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.MobilePushStatus { - user.AddNotifyProp(model.PUSH_STATUS_NOTIFY_PROP, *data.NotifyProps.MobilePushStatus) + if value, ok := user.NotifyProps[model.PushStatusNotifyProp]; !ok || value != *data.NotifyProps.MobilePushStatus { + user.AddNotifyProp(model.PushStatusNotifyProp, *data.NotifyProps.MobilePushStatus) hasNotifyPropsChanged = true } } if data.NotifyProps.ChannelTrigger != nil { - if value, ok := user.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.ChannelTrigger { - user.AddNotifyProp(model.CHANNEL_MENTIONS_NOTIFY_PROP, *data.NotifyProps.ChannelTrigger) + if value, ok := user.NotifyProps[model.ChannelMentionsNotifyProp]; !ok || value != *data.NotifyProps.ChannelTrigger { + user.AddNotifyProp(model.ChannelMentionsNotifyProp, *data.NotifyProps.ChannelTrigger) hasNotifyPropsChanged = true } } if data.NotifyProps.CommentsTrigger != nil { - if value, ok := user.NotifyProps[model.COMMENTS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.CommentsTrigger { - user.AddNotifyProp(model.COMMENTS_NOTIFY_PROP, *data.NotifyProps.CommentsTrigger) + if value, ok := user.NotifyProps[model.CommentsNotifyProp]; !ok || value != *data.NotifyProps.CommentsTrigger { + user.AddNotifyProp(model.CommentsNotifyProp, *data.NotifyProps.CommentsTrigger) hasNotifyPropsChanged = true } } if data.NotifyProps.MentionKeys != nil { - if value, ok := user.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.MentionKeys { - user.AddNotifyProp(model.MENTION_KEYS_NOTIFY_PROP, *data.NotifyProps.MentionKeys) + if value, ok := user.NotifyProps[model.MentionKeysNotifyProp]; !ok || value != *data.NotifyProps.MentionKeys { + user.AddNotifyProp(model.MentionKeysNotifyProp, *data.NotifyProps.MentionKeys) hasNotifyPropsChanged = true } } else { @@ -509,7 +509,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { } } - pref := model.Preference{UserId: savedUser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: savedUser.Id, Value: "0"} + pref := model.Preference{UserId: savedUser.Id, Category: model.PreferenceCategoryTutorialSteps, Name: savedUser.Id, Value: "0"} if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil { mlog.Warn("Encountered error saving tutorial preference", mlog.Err(err)) } @@ -580,7 +580,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.Theme != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_THEME, + Category: model.PreferenceCategoryTheme, Name: "", Value: *data.Theme, }) @@ -589,8 +589,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.UseMilitaryTime != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_USE_MILITARY_TIME, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameUseMilitaryTime, Value: *data.UseMilitaryTime, }) } @@ -598,8 +598,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.CollapsePreviews != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_COLLAPSE_SETTING, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameCollapseSetting, Value: *data.CollapsePreviews, }) } @@ -607,8 +607,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.MessageDisplay != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_MESSAGE_DISPLAY, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameMessageDisplay, Value: *data.MessageDisplay, }) } @@ -616,7 +616,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.ChannelDisplayMode != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, + Category: model.PreferenceCategoryDisplaySettings, Name: "channel_display_mode", Value: *data.ChannelDisplayMode, }) @@ -625,7 +625,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.TutorialStep != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, + Category: model.PreferenceCategoryTutorialSteps, Name: savedUser.Id, Value: *data.TutorialStep, }) @@ -634,7 +634,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.UseMarkdownPreview != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, + Category: model.PreferenceCategoryAdvancedSettings, Name: "feature_enabled_markdown_preview", Value: *data.UseMarkdownPreview, }) @@ -643,7 +643,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.UseFormatting != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, + Category: model.PreferenceCategoryAdvancedSettings, Name: "formatting", Value: *data.UseFormatting, }) @@ -652,31 +652,31 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { if data.ShowUnreadSection != nil { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS, + Category: model.PreferenceCategorySidebarSettings, Name: "show_unread_section", Value: *data.ShowUnreadSection, }) } - if data.EmailInterval != nil || savedUser.NotifyProps[model.EMAIL_NOTIFY_PROP] == "false" { + if data.EmailInterval != nil || savedUser.NotifyProps[model.EmailNotifyProp] == "false" { var intervalSeconds string - if value := savedUser.NotifyProps[model.EMAIL_NOTIFY_PROP]; value == "false" { + if value := savedUser.NotifyProps[model.EmailNotifyProp]; value == "false" { intervalSeconds = "0" } else { switch *data.EmailInterval { - case model.PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY: - intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS - case model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN: - intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN_AS_SECONDS - case model.PREFERENCE_EMAIL_INTERVAL_HOUR: - intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_HOUR_AS_SECONDS + case model.PreferenceEmailIntervalImmediately: + intervalSeconds = model.PreferenceEmailIntervalNoBatchingSeconds + case model.PreferenceEmailIntervalFifteen: + intervalSeconds = model.PreferenceEmailIntervalFifteenAsSeconds + case model.PreferenceEmailIntervalHour: + intervalSeconds = model.PreferenceEmailIntervalHourAsSeconds } } if intervalSeconds != "" { preferences = append(preferences, model.Preference{ UserId: savedUser.Id, - Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, - Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, + Category: model.PreferenceCategoryNotifications, + Name: model.PreferenceNameEmailInterval, Value: intervalSeconds, }) } @@ -730,7 +730,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod if tdata.Theme != nil { teamThemePreferencesByID[team.Id] = append(teamThemePreferencesByID[team.Id], model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_THEME, + Category: model.PreferenceCategoryTheme, Name: team.Id, Value: *tdata.Theme, }) @@ -746,12 +746,12 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod rawRoles := *tdata.Roles explicitRoles := []string{} for _, role := range strings.Fields(rawRoles) { - if role == model.TEAM_GUEST_ROLE_ID { + if role == model.TeamGuestRoleId { isGuestByTeamId[team.Id] = true isUserByTeamId[team.Id] = false - } else if role == model.TEAM_USER_ROLE_ID { + } else if role == model.TeamUserRoleId { isUserByTeamId[team.Id] = true - } else if role == model.TEAM_ADMIN_ROLE_ID { + } else if role == model.TeamAdminRoleId { isAdminByTeamId[team.Id] = true } else { explicitRoles = append(explicitRoles, role) @@ -780,7 +780,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod channels[team.Id] = append(channels[team.Id], *tdata.Channels...) } if !user.IsGuest() { - channels[team.Id] = append(channels[team.Id], UserChannelImportData{Name: model.NewString(model.DEFAULT_CHANNEL)}) + channels[team.Id] = append(channels[team.Id], UserChannelImportData{Name: model.NewString(model.DefaultChannelName)}) } teamsByID[team.Id] = team @@ -886,7 +886,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use if !ok { return model.NewAppError("BulkImport", "app.import.import_user_channels.channel_not_found.error", nil, "", http.StatusInternalServerError) } - if _, ok = channelsByID[channel.Id]; ok && *cdata.Name == model.DEFAULT_CHANNEL { + if _, ok = channelsByID[channel.Id]; ok && *cdata.Name == model.DefaultChannelName { // town-square membership was in the import and added by the importer (skip the added by the importer) continue } @@ -901,12 +901,12 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use rawRoles := *cdata.Roles explicitRoles := []string{} for _, role := range strings.Fields(rawRoles) { - if role == model.CHANNEL_GUEST_ROLE_ID { + if role == model.ChannelGuestRoleId { isGuestByChannelId[channel.Id] = true isUserByChannelId[channel.Id] = false - } else if role == model.CHANNEL_USER_ROLE_ID { + } else if role == model.ChannelUserRoleId { isUserByChannelId[channel.Id] = true - } else if role == model.CHANNEL_ADMIN_ROLE_ID { + } else if role == model.ChannelAdminRoleId { isAdminByChannelId[channel.Id] = true } else { explicitRoles = append(explicitRoles, role) @@ -918,7 +918,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use if cdata.Favorite != nil && *cdata.Favorite { channelPreferencesByID[channel.Id] = append(channelPreferencesByID[channel.Id], model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }) @@ -943,15 +943,15 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use if cdata.NotifyProps != nil { if cdata.NotifyProps.Desktop != nil { - member.NotifyProps[model.DESKTOP_NOTIFY_PROP] = *cdata.NotifyProps.Desktop + member.NotifyProps[model.DesktopNotifyProp] = *cdata.NotifyProps.Desktop } if cdata.NotifyProps.Mobile != nil { - member.NotifyProps[model.PUSH_NOTIFY_PROP] = *cdata.NotifyProps.Mobile + member.NotifyProps[model.PushNotifyProp] = *cdata.NotifyProps.Mobile } if cdata.NotifyProps.MarkUnread != nil { - member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = *cdata.NotifyProps.MarkUnread + member.NotifyProps[model.MarkUnreadNotifyProp] = *cdata.NotifyProps.MarkUnread } } @@ -1446,7 +1446,7 @@ func (a *App) importMultiplePostLines(c *request.Context, lines []LineImportWork preferences = append(preferences, model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: postWithData.post.Id, Value: "true", }) @@ -1544,7 +1544,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m for _, userID := range userIDs { preferences = append(preferences, model.Preference{ UserId: userID, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: channel.Id, Value: "true", }) @@ -1554,7 +1554,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m for _, favoriter := range *data.FavoritedBy { preferences = append(preferences, model.Preference{ UserId: userMap[favoriter].Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel.Id, Value: "true", }) @@ -1740,7 +1740,7 @@ func (a *App) importMultipleDirectPostLines(c *request.Context, lines []LineImpo preferences = append(preferences, model.Preference{ UserId: user.Id, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: postWithData.post.Id, Value: "true", }) diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 83cb9fdb02..67a86808ba 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -25,10 +25,10 @@ func TestImportImportScheme(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() // Try importing an invalid scheme in dryRun mode. @@ -220,10 +220,10 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() // Try importing an invalid scheme in dryRun mode. @@ -496,10 +496,10 @@ func TestImportImportTeam(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() scheme1 := th.SetupTeamScheme() @@ -586,10 +586,10 @@ func TestImportImportChannel(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() scheme1 := th.SetupChannelScheme() @@ -606,7 +606,7 @@ func TestImportImportChannel(t *testing.T) { require.Nil(t, err, "Failed to get team from database.") // Check how many channels are in the database. - channelCount, nErr := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) + channelCount, nErr := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) require.NoError(t, nErr, "Failed to get team count.") // Do an invalid channel in dry-run mode. @@ -679,7 +679,7 @@ func TestImportImportChannel(t *testing.T) { // Alter all the fields of that channel. data.DisplayName = ptrStr("Chaned Disp Name") - data.Type = ptrStr(model.CHANNEL_PRIVATE) + data.Type = ptrStr(model.ChannelTypePrivate) data.Header = ptrStr("New Header") data.Purpose = ptrStr("New Purpose") data.Scheme = &scheme2.Name @@ -1088,9 +1088,9 @@ func TestImportImportUser(t *testing.T) { channelMember, appErr := th.App.GetChannelMember(context.Background(), channel.Id, user.Id) require.Nil(t, appErr, "Failed to get channel member from database.") assert.Equal(t, "channel_user", channelMember.Roles) - assert.Equal(t, "default", channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP]) - assert.Equal(t, "default", channelMember.NotifyProps[model.PUSH_NOTIFY_PROP]) - assert.Equal(t, "all", channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, "default", channelMember.NotifyProps[model.DesktopNotifyProp]) + assert.Equal(t, "default", channelMember.NotifyProps[model.PushNotifyProp]) + assert.Equal(t, "all", channelMember.NotifyProps[model.MarkUnreadNotifyProp]) // Test with the properties of the team and channel membership changed. data.Teams = &[]UserTeamImportData{ @@ -1103,9 +1103,9 @@ func TestImportImportUser(t *testing.T) { Name: &channelName, Roles: ptrStr("channel_user channel_admin"), NotifyProps: &UserChannelNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_MENTION), - Mobile: ptrStr(model.USER_NOTIFY_MENTION), - MarkUnread: ptrStr(model.USER_NOTIFY_MENTION), + Desktop: ptrStr(model.UserNotifyMention), + Mobile: ptrStr(model.UserNotifyMention), + MarkUnread: ptrStr(model.UserNotifyMention), }, Favorite: ptrBool(true), }, @@ -1123,12 +1123,12 @@ func TestImportImportUser(t *testing.T) { channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) require.Nil(t, appErr, "Failed to get channel member Desktop from database.") assert.Equal(t, "channel_user channel_admin", channelMember.Roles) - assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP]) - assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.PUSH_NOTIFY_PROP]) - assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.DesktopNotifyProp]) + assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.PushNotifyProp]) + assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.MarkUnreadNotifyProp]) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, team.Id, *(*data.Teams)[0].Theme) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true") + checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, team.Id, *(*data.Teams)[0].Theme) // No more new member objects. tmc, appErr = th.App.GetTeamMembers(team.Id, 0, 1000, nil) @@ -1162,16 +1162,16 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "feature_enabled_markdown_preview", *data.UseMarkdownPreview) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "formatting", *data.UseFormatting) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS, "show_unread_section", *data.ShowUnreadSection) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL, "30") + checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, "", *data.Theme) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime, *data.UseMilitaryTime) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapseSetting, *data.CollapsePreviews) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameMessageDisplay, *data.MessageDisplay) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameChannelDisplayMode, *data.ChannelDisplayMode) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryTutorialSteps, user.Id, *data.TutorialStep) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryAdvancedSettings, "feature_enabled_markdown_preview", *data.UseMarkdownPreview) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryAdvancedSettings, "formatting", *data.UseFormatting) + checkPreference(t, th.App, user.Id, model.PreferenceCategorySidebarSettings, "show_unread_section", *data.ShowUnreadSection) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval, "30") // Change those preferences. data = UserImportData{ @@ -1189,23 +1189,23 @@ func TestImportImportUser(t *testing.T) { assert.Nil(t, appErr) // Check their values again. - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL, "3600") + checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, "", *data.Theme) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime, *data.UseMilitaryTime) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapseSetting, *data.CollapsePreviews) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameMessageDisplay, *data.MessageDisplay) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameChannelDisplayMode, *data.ChannelDisplayMode) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryTutorialSteps, user.Id, *data.TutorialStep) + checkPreference(t, th.App, user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval, "3600") // Set Notify Without mention keys data.NotifyProps = &UserNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_ALL), + Desktop: ptrStr(model.UserNotifyAll), DesktopSound: ptrStr("true"), Email: ptrStr("true"), - Mobile: ptrStr(model.USER_NOTIFY_ALL), - MobilePushStatus: ptrStr(model.STATUS_ONLINE), + Mobile: ptrStr(model.UserNotifyAll), + MobilePushStatus: ptrStr(model.StatusOnline), ChannelTrigger: ptrStr("true"), - CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT), + CommentsTrigger: ptrStr(model.CommentsNotifyRoot), } appErr = th.App.importUser(&data, false) assert.Nil(t, appErr) @@ -1213,24 +1213,24 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_ALL) - checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_ALL) - checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_ONLINE) - checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ROOT) - checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "") + checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyAll) + checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "true") + checkNotifyProp(t, user, model.EmailNotifyProp, "true") + checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyAll) + checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusOnline) + checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "true") + checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyRoot) + checkNotifyProp(t, user, model.MentionKeysNotifyProp, "") // Set Notify Props with Mention keys data.NotifyProps = &UserNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_ALL), + Desktop: ptrStr(model.UserNotifyAll), DesktopSound: ptrStr("true"), Email: ptrStr("true"), - Mobile: ptrStr(model.USER_NOTIFY_ALL), - MobilePushStatus: ptrStr(model.STATUS_ONLINE), + Mobile: ptrStr(model.UserNotifyAll), + MobilePushStatus: ptrStr(model.StatusOnline), ChannelTrigger: ptrStr("true"), - CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT), + CommentsTrigger: ptrStr(model.CommentsNotifyRoot), MentionKeys: ptrStr("valid,misc"), } appErr = th.App.importUser(&data, false) @@ -1239,24 +1239,24 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_ALL) - checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_ALL) - checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_ONLINE) - checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "true") - checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ROOT) - checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "valid,misc") + checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyAll) + checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "true") + checkNotifyProp(t, user, model.EmailNotifyProp, "true") + checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyAll) + checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusOnline) + checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "true") + checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyRoot) + checkNotifyProp(t, user, model.MentionKeysNotifyProp, "valid,misc") // Change Notify Props with mention keys data.NotifyProps = &UserNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_MENTION), + Desktop: ptrStr(model.UserNotifyMention), DesktopSound: ptrStr("false"), Email: ptrStr("false"), - Mobile: ptrStr(model.USER_NOTIFY_NONE), - MobilePushStatus: ptrStr(model.STATUS_AWAY), + Mobile: ptrStr(model.UserNotifyNone), + MobilePushStatus: ptrStr(model.StatusAway), ChannelTrigger: ptrStr("false"), - CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY), + CommentsTrigger: ptrStr(model.CommentsNotifyAny), MentionKeys: ptrStr("misc"), } appErr = th.App.importUser(&data, false) @@ -1265,24 +1265,24 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION) - checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE) - checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY) - checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY) - checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc") + checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention) + checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false") + checkNotifyProp(t, user, model.EmailNotifyProp, "false") + checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone) + checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway) + checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false") + checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny) + checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc") // Change Notify Props without mention keys data.NotifyProps = &UserNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_MENTION), + Desktop: ptrStr(model.UserNotifyMention), DesktopSound: ptrStr("false"), Email: ptrStr("false"), - Mobile: ptrStr(model.USER_NOTIFY_NONE), - MobilePushStatus: ptrStr(model.STATUS_AWAY), + Mobile: ptrStr(model.UserNotifyNone), + MobilePushStatus: ptrStr(model.StatusAway), ChannelTrigger: ptrStr("false"), - CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY), + CommentsTrigger: ptrStr(model.CommentsNotifyAny), } appErr = th.App.importUser(&data, false) assert.Nil(t, appErr) @@ -1290,14 +1290,14 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION) - checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE) - checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY) - checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY) - checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc") + checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention) + checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false") + checkNotifyProp(t, user, model.EmailNotifyProp, "false") + checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone) + checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway) + checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false") + checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny) + checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc") // Check Notify Props get set on *create* user. username = model.NewId() @@ -1306,13 +1306,13 @@ func TestImportImportUser(t *testing.T) { Email: ptrStr(model.NewId() + "@example.com"), } data.NotifyProps = &UserNotifyPropsImportData{ - Desktop: ptrStr(model.USER_NOTIFY_MENTION), + Desktop: ptrStr(model.UserNotifyMention), DesktopSound: ptrStr("false"), Email: ptrStr("false"), - Mobile: ptrStr(model.USER_NOTIFY_NONE), - MobilePushStatus: ptrStr(model.STATUS_AWAY), + Mobile: ptrStr(model.UserNotifyNone), + MobilePushStatus: ptrStr(model.StatusAway), ChannelTrigger: ptrStr("false"), - CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY), + CommentsTrigger: ptrStr(model.CommentsNotifyAny), MentionKeys: ptrStr("misc"), } @@ -1322,24 +1322,24 @@ func TestImportImportUser(t *testing.T) { user, appErr = th.App.GetUserByUsername(username) require.Nil(t, appErr, "Failed to get user from database.") - checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION) - checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE) - checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY) - checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false") - checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY) - checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc") + checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention) + checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false") + checkNotifyProp(t, user, model.EmailNotifyProp, "false") + checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone) + checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway) + checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false") + checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny) + checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc") // Test importing a user with roles set to a team and a channel which are affected by an override scheme. // The import subsystem should translate `channel_admin/channel_user/team_admin/team_user` // to the appropriate scheme-managed-role booleans. // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() teamSchemeData := &SchemeImportData{ @@ -1596,7 +1596,7 @@ func TestImportUserTeams(t *testing.T) { data: &[]UserTeamImportData{ { Name: &th.BasicTeam.Name, - Roles: model.NewString(model.TEAM_ADMIN_ROLE_ID), + Roles: model.NewString(model.TeamAdminRoleId), }, }, expectedError: false, @@ -1640,7 +1640,7 @@ func TestImportUserTeams(t *testing.T) { Name: &th.BasicTeam.Name, Channels: &[]UserChannelImportData{ { - Name: ptrStr(model.DEFAULT_CHANNEL), + Name: ptrStr(model.DefaultChannelName), }, }, }, @@ -1720,7 +1720,7 @@ func TestImportUserTeams(t *testing.T) { require.Equal(t, tc.expectedExplicitRoles, teamMembers[0].ExplicitRoles, "Not matching expected explicit roles") require.Equal(t, tc.expectedRoles, teamMembers[0].Roles, "not matching expected roles") if tc.expectedTheme != "" { - pref, prefErr := th.App.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_THEME, teamMembers[0].TeamId) + pref, prefErr := th.App.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryTheme, teamMembers[0].TeamId) require.NoError(t, prefErr) require.Equal(t, tc.expectedTheme, pref.Value) } @@ -1816,7 +1816,7 @@ func TestImportUserChannels(t *testing.T) { data: &[]UserChannelImportData{ { Name: &th.BasicChannel.Name, - Roles: model.NewString(model.CHANNEL_ADMIN_ROLE_ID), + Roles: model.NewString(model.ChannelAdminRoleId), }, }, expectedError: false, @@ -1874,9 +1874,9 @@ func TestImportUserChannels(t *testing.T) { require.Equal(t, tc.expectedExplicitRoles, channelMember.ExplicitRoles, "Not matching expected explicit roles") require.Equal(t, tc.expectedRoles, channelMember.Roles, "not matching expected roles") if tc.expectedNotifyProps != nil { - require.Equal(t, *tc.expectedNotifyProps.Desktop, channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP]) - require.Equal(t, *tc.expectedNotifyProps.Mobile, channelMember.NotifyProps[model.PUSH_NOTIFY_PROP]) - require.Equal(t, *tc.expectedNotifyProps.MarkUnread, channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + require.Equal(t, *tc.expectedNotifyProps.Desktop, channelMember.NotifyProps[model.DesktopNotifyProp]) + require.Equal(t, *tc.expectedNotifyProps.Mobile, channelMember.NotifyProps[model.PushNotifyProp]) + require.Equal(t, *tc.expectedNotifyProps.MarkUnread, channelMember.NotifyProps[model.MarkUnreadNotifyProp]) } } } @@ -1904,7 +1904,7 @@ func TestImportUserDefaultNotifyProps(t *testing.T) { require.Nil(t, err) // Check the value of the notify prop we specified explicitly in the import data. - val, ok := user.NotifyProps[model.EMAIL_NOTIFY_PROP] + val, ok := user.NotifyProps[model.EmailNotifyProp] assert.True(t, ok) assert.Equal(t, "false", val) @@ -1913,7 +1913,7 @@ func TestImportUserDefaultNotifyProps(t *testing.T) { comparisonUser.SetDefaultNotifications() for key, expectedValue := range comparisonUser.NotifyProps { - if key == model.EMAIL_NOTIFY_PROP { + if key == model.EmailNotifyProp { continue } @@ -2239,8 +2239,8 @@ func TestImportimportMultiplePostLines(t *testing.T) { postBool = post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id require.False(t, postBool, "Post properties not as expected") - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, user.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") + checkPreference(t, th.App, user2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") // Post with reaction. reactionPostTime := hashtagTime + 2 @@ -2785,8 +2785,8 @@ func TestImportImportPost(t *testing.T) { postBool := post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id require.False(t, postBool, "Post properties not as expected") - checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, user.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") + checkPreference(t, th.App, user2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") }) t.Run("Post with reaction", func(t *testing.T) { @@ -2959,10 +2959,10 @@ func TestImportImportDirectChannel(t *testing.T) { defer th.TearDown() // Check how many channels are in the database. - directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT) + directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeDirect) require.NoError(t, err, "Failed to get direct channel count.") - groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP) + groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeGroup) require.NoError(t, err, "Failed to get group channel count.") // Do an invalid channel in dry-run mode. @@ -2976,8 +2976,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Error(t, err) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do a valid DIRECT channel with a nonexistent member in dry-run mode. data.Members = &[]string{ @@ -2988,8 +2988,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do a valid GROUP channel with a nonexistent member in dry-run mode. data.Members = &[]string{ @@ -3001,8 +3001,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do an invalid channel in apply mode. data.Members = &[]string{ @@ -3012,8 +3012,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Error(t, err) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do a valid DIRECT channel. data.Members = &[]string{ @@ -3024,16 +3024,16 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that one more DIRECT channel is in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do the same DIRECT channel again. appErr = th.App.importDirectChannel(&data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Update the channel's HEADER data.Header = ptrStr("New Channel Header 2") @@ -3041,8 +3041,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Get the channel to check that the header was updated. channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) @@ -3061,8 +3061,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.NotNil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do a valid GROUP channel. data.Members = &[]string{ @@ -3074,16 +3074,16 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that one more GROUP channel is in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1) // Do the same DIRECT channel again. appErr = th.App.importDirectChannel(&data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1) // Update the channel's HEADER data.Header = ptrStr("New Channel Header 3") @@ -3091,8 +3091,8 @@ func TestImportImportDirectChannel(t *testing.T) { require.Nil(t, appErr) // Check that no more channels are in the DB. - AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1) + AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1) // Get the channel to check that the header was updated. userIDs := []string{ @@ -3118,8 +3118,8 @@ func TestImportImportDirectChannel(t *testing.T) { channel, appErr = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, appErr) - checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") - checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true") } func TestImportImportDirectPost(t *testing.T) { @@ -3376,8 +3376,8 @@ func TestImportImportDirectPost(t *testing.T) { require.Len(t, posts, 1) post := posts[0] - checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") }) // ------------------ Group Channel ------------------------- @@ -3649,8 +3649,8 @@ func TestImportImportDirectPost(t *testing.T) { require.Len(t, posts, 1) post := posts[0] - checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true") }) t.Run("Post with reaction", func(t *testing.T) { diff --git a/app/import_validators.go b/app/import_validators.go index e8309c6ccd..cc42e906bc 100644 --- a/app/import_validators.go +++ b/app/import_validators.go @@ -20,11 +20,11 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError { } switch *data.Scope { - case model.SCHEME_SCOPE_TEAM: + case model.SchemeScopeTeam: if data.DefaultTeamAdminRole == nil || data.DefaultTeamUserRole == nil || data.DefaultChannelAdminRole == nil || data.DefaultChannelUserRole == nil { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.wrong_roles_for_scope.error", nil, "", http.StatusBadRequest) } - case model.SCHEME_SCOPE_CHANNEL: + case model.SchemeScopeChannel: if data.DefaultTeamAdminRole != nil || data.DefaultTeamUserRole != nil || data.DefaultChannelAdminRole == nil || data.DefaultChannelUserRole == nil { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.wrong_roles_for_scope.error", nil, "", http.StatusBadRequest) } @@ -36,11 +36,11 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.name_invalid.error", nil, "", http.StatusBadRequest) } - if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH { + if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SchemeDisplayNameMaxLength { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) } - if data.Description != nil && len(*data.Description) > model.SCHEME_DESCRIPTION_MAX_LENGTH { + if data.Description != nil && len(*data.Description) > model.SchemeDescriptionMaxLength { return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.description_invalid.error", nil, "", http.StatusBadRequest) } @@ -89,11 +89,11 @@ func validateRoleImportData(data *RoleImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_role_import_data.name_invalid.error", nil, "", http.StatusBadRequest) } - if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH { + if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.RoleDisplayNameMaxLength { return model.NewAppError("BulkImport", "app.import.validate_role_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest) } - if data.Description != nil && len(*data.Description) > model.ROLE_DESCRIPTION_MAX_LENGTH { + if data.Description != nil && len(*data.Description) > model.RoleDescriptionMaxLength { return model.NewAppError("BulkImport", "app.import.validate_role_import_data.description_invalid.error", nil, "", http.StatusBadRequest) } @@ -120,7 +120,7 @@ func validateTeamImportData(data *TeamImportData) *model.AppError { if data.Name == nil { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_missing.error", nil, "", http.StatusBadRequest) - } else if len(*data.Name) > model.TEAM_NAME_MAX_LENGTH { + } else if len(*data.Name) > model.TeamNameMaxLength { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_length.error", nil, "", http.StatusBadRequest) } else if model.IsReservedTeamName(*data.Name) { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_reserved.error", nil, "", http.StatusBadRequest) @@ -130,17 +130,17 @@ func validateTeamImportData(data *TeamImportData) *model.AppError { if data.DisplayName == nil { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.display_name_missing.error", nil, "", http.StatusBadRequest) - } else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.TEAM_DISPLAY_NAME_MAX_RUNES { + } else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.TeamDisplayNameMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.display_name_length.error", nil, "", http.StatusBadRequest) } if data.Type == nil { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.type_missing.error", nil, "", http.StatusBadRequest) - } else if *data.Type != model.TEAM_OPEN && *data.Type != model.TEAM_INVITE { + } else if *data.Type != model.TeamOpen && *data.Type != model.TeamInvite { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.type_invalid.error", nil, "", http.StatusBadRequest) } - if data.Description != nil && len(*data.Description) > model.TEAM_DESCRIPTION_MAX_LENGTH { + if data.Description != nil && len(*data.Description) > model.TeamDescriptionMaxLength { return model.NewAppError("BulkImport", "app.import.validate_team_import_data.description_length.error", nil, "", http.StatusBadRequest) } @@ -159,7 +159,7 @@ func validateChannelImportData(data *ChannelImportData) *model.AppError { if data.Name == nil { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_missing.error", nil, "", http.StatusBadRequest) - } else if len(*data.Name) > model.CHANNEL_NAME_MAX_LENGTH { + } else if len(*data.Name) > model.ChannelNameMaxLength { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_length.error", nil, "", http.StatusBadRequest) } else if !model.IsValidChannelIdentifier(*data.Name) { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_characters.error", nil, "", http.StatusBadRequest) @@ -167,21 +167,21 @@ func validateChannelImportData(data *ChannelImportData) *model.AppError { if data.DisplayName == nil { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.display_name_missing.error", nil, "", http.StatusBadRequest) - } else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.CHANNEL_DISPLAY_NAME_MAX_RUNES { + } else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.ChannelDisplayNameMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.display_name_length.error", nil, "", http.StatusBadRequest) } if data.Type == nil { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.type_missing.error", nil, "", http.StatusBadRequest) - } else if *data.Type != model.CHANNEL_OPEN && *data.Type != model.CHANNEL_PRIVATE { + } else if *data.Type != model.ChannelTypeOpen && *data.Type != model.ChannelTypePrivate { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.type_invalid.error", nil, "", http.StatusBadRequest) } - if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.CHANNEL_HEADER_MAX_RUNES { + if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.ChannelHeaderMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.header_length.error", nil, "", http.StatusBadRequest) } - if data.Purpose != nil && utf8.RuneCountInString(*data.Purpose) > model.CHANNEL_PURPOSE_MAX_RUNES { + if data.Purpose != nil && utf8.RuneCountInString(*data.Purpose) > model.ChannelPurposeMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.purpose_length.error", nil, "", http.StatusBadRequest) } @@ -207,7 +207,7 @@ func validateUserImportData(data *UserImportData) *model.AppError { if data.Email == nil { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_missing.error", nil, "", http.StatusBadRequest) - } else if *data.Email == "" || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH { + } else if *data.Email == "" || len(*data.Email) > model.UserEmailMaxLength { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_length.error", nil, "", http.StatusBadRequest) } @@ -215,7 +215,7 @@ func validateUserImportData(data *UserImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_and_password.error", nil, "", http.StatusBadRequest) } - if data.AuthData != nil && len(*data.AuthData) > model.USER_AUTH_DATA_MAX_LENGTH { + if data.AuthData != nil && len(*data.AuthData) > model.UserAuthDataMaxLength { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_length.error", nil, "", http.StatusBadRequest) } @@ -234,23 +234,23 @@ func validateUserImportData(data *UserImportData) *model.AppError { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest) } - if data.Password != nil && len(*data.Password) > model.USER_PASSWORD_MAX_LENGTH { + if data.Password != nil && len(*data.Password) > model.UserPasswordMaxLength { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest) } - if data.Nickname != nil && utf8.RuneCountInString(*data.Nickname) > model.USER_NICKNAME_MAX_RUNES { + if data.Nickname != nil && utf8.RuneCountInString(*data.Nickname) > model.UserNicknameMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.nickname_length.error", nil, "", http.StatusBadRequest) } - if data.FirstName != nil && utf8.RuneCountInString(*data.FirstName) > model.USER_FIRST_NAME_MAX_RUNES { + if data.FirstName != nil && utf8.RuneCountInString(*data.FirstName) > model.UserFirstNameMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.first_name_length.error", nil, "", http.StatusBadRequest) } - if data.LastName != nil && utf8.RuneCountInString(*data.LastName) > model.USER_LAST_NAME_MAX_RUNES { + if data.LastName != nil && utf8.RuneCountInString(*data.LastName) > model.UserLastNameMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.last_name_length.error", nil, "", http.StatusBadRequest) } - if data.Position != nil && utf8.RuneCountInString(*data.Position) > model.USER_POSITION_MAX_RUNES { + if data.Position != nil && utf8.RuneCountInString(*data.Position) > model.UserPositionMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_user_import_data.position_length.error", nil, "", http.StatusBadRequest) } @@ -381,7 +381,7 @@ func validateReactionImportData(data *ReactionImportData, parentCreateAt int64) if data.EmojiName == nil { return model.NewAppError("BulkImport", "app.import.validate_reaction_import_data.emoji_name_missing.error", nil, "", http.StatusBadRequest) - } else if utf8.RuneCountInString(*data.EmojiName) > model.EMOJI_NAME_MAX_LENGTH { + } else if utf8.RuneCountInString(*data.EmojiName) > model.EmojiNameMaxLength { return model.NewAppError("BulkImport", "app.import.validate_reaction_import_data.emoji_name_length.error", nil, "", http.StatusBadRequest) } @@ -457,7 +457,7 @@ func validatePostImportData(data *PostImportData, maxPostSize int) *model.AppErr } } - if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJson(*data.Props)) > model.POST_PROPS_MAX_RUNES { + if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJson(*data.Props)) > model.PostPropsMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_post_import_data.props_too_large.error", nil, "", http.StatusBadRequest) } @@ -470,14 +470,14 @@ func validateDirectChannelImportData(data *DirectChannelImportData) *model.AppEr } if len(*data.Members) != 2 { - if len(*data.Members) < model.CHANNEL_GROUP_MIN_USERS { + if len(*data.Members) < model.ChannelGroupMinUsers { return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.members_too_few.error", nil, "", http.StatusBadRequest) - } else if len(*data.Members) > model.CHANNEL_GROUP_MAX_USERS { + } else if len(*data.Members) > model.ChannelGroupMaxUsers { return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.members_too_many.error", nil, "", http.StatusBadRequest) } } - if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.CHANNEL_HEADER_MAX_RUNES { + if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.ChannelHeaderMaxRunes { return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.header_length.error", nil, "", http.StatusBadRequest) } @@ -505,9 +505,9 @@ func validateDirectPostImportData(data *DirectPostImportData, maxPostSize int) * } if len(*data.ChannelMembers) != 2 { - if len(*data.ChannelMembers) < model.CHANNEL_GROUP_MIN_USERS { + if len(*data.ChannelMembers) < model.ChannelGroupMinUsers { return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.channel_members_too_few.error", nil, "", http.StatusBadRequest) - } else if len(*data.ChannelMembers) > model.CHANNEL_GROUP_MAX_USERS { + } else if len(*data.ChannelMembers) > model.ChannelGroupMaxUsers { return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.channel_members_too_many.error", nil, "", http.StatusBadRequest) } } diff --git a/app/import_validators_test.go b/app/import_validators_test.go index 1c5ed06fef..3e54c73188 100644 --- a/app/import_validators_test.go +++ b/app/import_validators_test.go @@ -586,7 +586,7 @@ func TestImportValidateUserImportData(t *testing.T) { data.NotifyProps.Desktop = ptrStr("invalid") checkError(t, validateUserImportData(&data)) - data.NotifyProps.Desktop = ptrStr(model.USER_NOTIFY_ALL) + data.NotifyProps.Desktop = ptrStr(model.UserNotifyAll) data.NotifyProps.DesktopSound = ptrStr("invalid") checkError(t, validateUserImportData(&data)) @@ -598,11 +598,11 @@ func TestImportValidateUserImportData(t *testing.T) { data.NotifyProps.Mobile = ptrStr("invalid") checkError(t, validateUserImportData(&data)) - data.NotifyProps.Mobile = ptrStr(model.USER_NOTIFY_ALL) + data.NotifyProps.Mobile = ptrStr(model.UserNotifyAll) data.NotifyProps.MobilePushStatus = ptrStr("invalid") checkError(t, validateUserImportData(&data)) - data.NotifyProps.MobilePushStatus = ptrStr(model.STATUS_ONLINE) + data.NotifyProps.MobilePushStatus = ptrStr(model.StatusOnline) data.NotifyProps.ChannelTrigger = ptrStr("invalid") checkError(t, validateUserImportData(&data)) @@ -610,7 +610,7 @@ func TestImportValidateUserImportData(t *testing.T) { data.NotifyProps.CommentsTrigger = ptrStr("invalid") checkError(t, validateUserImportData(&data)) - data.NotifyProps.CommentsTrigger = ptrStr(model.COMMENTS_NOTIFY_ROOT) + data.NotifyProps.CommentsTrigger = ptrStr(model.CommentsNotifyRoot) data.NotifyProps.MentionKeys = ptrStr("valid") checkNoError(t, validateUserImportData(&data)) @@ -1013,7 +1013,7 @@ func TestImportValidatePostImportData(t *testing.T) { t.Run("Test with props too large", func(t *testing.T) { props := model.StringInterface{ - "attachment": strings.Repeat("a", model.POST_PROPS_MAX_RUNES), + "attachment": strings.Repeat("a", model.PostPropsMaxRunes), } data := PostImportData{ diff --git a/app/integration_action.go b/app/integration_action.go index 37e646818f..3137637490 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -219,7 +219,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI upstreamRequest.TeamName = team.Name } - if upstreamRequest.Type == model.POST_ACTION_TYPE_SELECT { + if upstreamRequest.Type == model.PostActionTypeSelect { if selectedOption != "" { if upstreamRequest.Context == nil { upstreamRequest.Context = map[string]interface{}{} @@ -329,7 +329,7 @@ func (a *App) DoActionRequest(c *request.Context, rawURL string, body []byte) (* subpath, _ := utils.GetSubpathFromConfig(a.Config()) siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL) if (inURL.Hostname() == "localhost" || inURL.Hostname() == "127.0.0.1" || inURL.Hostname() == siteURL.Hostname()) && strings.HasPrefix(inURL.Path, path.Join(subpath, "plugins")) { - req.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token) + req.Header.Set(model.HeaderAuth, "Bearer "+c.Session().Token) httpClient = a.HTTPService().MakeClient(true) } else { httpClient = a.HTTPService().MakeClient(false) @@ -414,7 +414,7 @@ func (a *App) doPluginRequest(c *request.Context, method, rawURL string, values return nil, model.NewAppError("doPluginRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) } r.Header.Set("Mattermost-User-Id", c.Session().UserId) - r.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token) + r.Header.Set(model.HeaderAuth, "Bearer "+c.Session().Token) params := make(map[string]string) params["plugin_id"] = pluginID r = mux.SetURLVars(r, params) @@ -485,7 +485,7 @@ func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstr &model.PostAction{ Id: "emailUs", Name: i18n.T("api.server.warn_metric.email_us"), - Type: model.POST_ACTION_TYPE_BUTTON, + Type: model.PostActionTypeButton, Options: []*model.PostActionOptions{ { Text: "WarnMetricMailtoUrl", @@ -501,7 +501,7 @@ func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstr "bot_user_id": botPost.UserId, "force_ack": true, }, - URL: fmt.Sprintf("/warn_metrics/ack/%s", model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500), + URL: fmt.Sprintf("/warn_metrics/ack/%s", model.SystemWarnMetricNumberOfActiveUsers500), }, }, ) @@ -563,7 +563,7 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s mailToLinkContent := &MailToLinkContent{ MetricId: warnMetricId, - MailRecipient: model.MM_SUPPORT_ADVISOR_ADDRESS, + MailRecipient: model.MmSupportAdvisorAddress, MailCC: user.Email, MailSubject: T("api.server.warn_metric.bot_response.mailto_subject"), MailBody: mailBody, @@ -586,7 +586,7 @@ func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppE jsonRequest, _ := json.Marshal(request) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_OPEN_DIALOG, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventOpenDialog, "", "", userID, nil) message.Add("dialog", string(jsonRequest)) a.Publish(message) diff --git a/app/integration_action_test.go b/app/integration_action_test.go index e16169a1a1..1a041f4215 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -162,7 +162,7 @@ func TestPostAction(t *testing.T) { assert.Equal(t, request.UserName, th.BasicUser.Username) assert.Equal(t, request.ChannelId, channel.Id) assert.Equal(t, request.ChannelName, channel.Name) - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { assert.Empty(t, request.TeamId) assert.Empty(t, request.TeamName) } else { @@ -170,7 +170,7 @@ func TestPostAction(t *testing.T) { assert.Equal(t, request.TeamName, th.BasicTeam.Name) } assert.True(t, request.TriggerId != "") - if request.Type == model.POST_ACTION_TYPE_SELECT { + if request.Type == model.PostActionTypeSelect { assert.Equal(t, request.DataSource, "some_source") assert.Equal(t, request.Context["selected_option"], "selected") } else { @@ -238,7 +238,7 @@ func TestPostAction(t *testing.T) { URL: ts.URL, }, Name: "action", - Type: model.POST_ACTION_TYPE_SELECT, + Type: model.PostActionTypeSelect, DataSource: "some_source", }, }, diff --git a/app/job.go b/app/job.go index 0ec7a2f6de..6e0ee03866 100644 --- a/app/job.go +++ b/app/job.go @@ -74,30 +74,30 @@ func (a *App) CancelJob(jobId string) *model.AppError { func (a *App) SessionHasPermissionToCreateJob(session model.Session, job *model.Job) (bool, *model.Permission) { switch job.Type { - case model.JOB_TYPE_BLEVE_POST_INDEXING: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB), model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB - case model.JOB_TYPE_DATA_RETENTION: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_DATA_RETENTION_JOB), model.PERMISSION_CREATE_DATA_RETENTION_JOB - case model.JOB_TYPE_MESSAGE_EXPORT: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB), model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB - case model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB), model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB - case model.JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB), model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB - case model.JOB_TYPE_LDAP_SYNC: - return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_LDAP_SYNC_JOB), model.PERMISSION_CREATE_LDAP_SYNC_JOB + case model.JobTypeBlevePostIndexing: + return a.SessionHasPermissionTo(session, model.PermissionCreatePostBleveIndexesJob), model.PermissionCreatePostBleveIndexesJob + case model.JobTypeDataRetention: + return a.SessionHasPermissionTo(session, model.PermissionCreateDataRetentionJob), model.PermissionCreateDataRetentionJob + case model.JobTypeMessageExport: + return a.SessionHasPermissionTo(session, model.PermissionCreateComplianceExportJob), model.PermissionCreateComplianceExportJob + case model.JobTypeElasticsearchPostIndexing: + return a.SessionHasPermissionTo(session, model.PermissionCreateElasticsearchPostIndexingJob), model.PermissionCreateElasticsearchPostIndexingJob + case model.JobTypeElasticsearchPostAggregation: + return a.SessionHasPermissionTo(session, model.PermissionCreateElasticsearchPostAggregationJob), model.PermissionCreateElasticsearchPostAggregationJob + case model.JobTypeLdapSync: + return a.SessionHasPermissionTo(session, model.PermissionCreateLdapSyncJob), model.PermissionCreateLdapSyncJob case - model.JOB_TYPE_MIGRATIONS, - model.JOB_TYPE_PLUGINS, - model.JOB_TYPE_PRODUCT_NOTICES, - model.JOB_TYPE_EXPIRY_NOTIFY, - model.JOB_TYPE_ACTIVE_USERS, - model.JOB_TYPE_IMPORT_PROCESS, - model.JOB_TYPE_IMPORT_DELETE, - model.JOB_TYPE_EXPORT_PROCESS, - model.JOB_TYPE_EXPORT_DELETE, - model.JOB_TYPE_CLOUD: - return a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_JOBS), model.PERMISSION_MANAGE_JOBS + model.JobTypeMigrations, + model.JobTypePlugins, + model.JobTypeProductNotices, + model.JobTypeExpiryNotify, + model.JobTypeActiveUsers, + model.JobTypeImportProcess, + model.JobTypeImportDelete, + model.JobTypeExportProcess, + model.JobTypeExportDelete, + model.JobTypeCloud: + return a.SessionHasPermissionTo(session, model.PermissionManageJobs), model.PermissionManageJobs } return false, nil @@ -105,29 +105,29 @@ func (a *App) SessionHasPermissionToCreateJob(session model.Session, job *model. func (a *App) SessionHasPermissionToReadJob(session model.Session, jobType string) (bool, *model.Permission) { switch jobType { - case model.JOB_TYPE_DATA_RETENTION: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_DATA_RETENTION_JOB), model.PERMISSION_READ_DATA_RETENTION_JOB - case model.JOB_TYPE_MESSAGE_EXPORT: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB - case model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB), model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB - case model.JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB), model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB - case model.JOB_TYPE_LDAP_SYNC: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_LDAP_SYNC_JOB), model.PERMISSION_READ_LDAP_SYNC_JOB + case model.JobTypeDataRetention: + return a.SessionHasPermissionTo(session, model.PermissionReadDataRetentionJob), model.PermissionReadDataRetentionJob + case model.JobTypeMessageExport: + return a.SessionHasPermissionTo(session, model.PermissionReadComplianceExportJob), model.PermissionReadComplianceExportJob + case model.JobTypeElasticsearchPostIndexing: + return a.SessionHasPermissionTo(session, model.PermissionReadElasticsearchPostIndexingJob), model.PermissionReadElasticsearchPostIndexingJob + case model.JobTypeElasticsearchPostAggregation: + return a.SessionHasPermissionTo(session, model.PermissionReadElasticsearchPostAggregationJob), model.PermissionReadElasticsearchPostAggregationJob + case model.JobTypeLdapSync: + return a.SessionHasPermissionTo(session, model.PermissionReadLdapSyncJob), model.PermissionReadLdapSyncJob case - model.JOB_TYPE_BLEVE_POST_INDEXING, - model.JOB_TYPE_MIGRATIONS, - model.JOB_TYPE_PLUGINS, - model.JOB_TYPE_PRODUCT_NOTICES, - model.JOB_TYPE_EXPIRY_NOTIFY, - model.JOB_TYPE_ACTIVE_USERS, - model.JOB_TYPE_IMPORT_PROCESS, - model.JOB_TYPE_IMPORT_DELETE, - model.JOB_TYPE_EXPORT_PROCESS, - model.JOB_TYPE_EXPORT_DELETE, - model.JOB_TYPE_CLOUD: - return a.SessionHasPermissionTo(session, model.PERMISSION_READ_JOBS), model.PERMISSION_READ_JOBS + model.JobTypeBlevePostIndexing, + model.JobTypeMigrations, + model.JobTypePlugins, + model.JobTypeProductNotices, + model.JobTypeExpiryNotify, + model.JobTypeActiveUsers, + model.JobTypeImportProcess, + model.JobTypeImportDelete, + model.JobTypeExportProcess, + model.JobTypeExportDelete, + model.JobTypeCloud: + return a.SessionHasPermissionTo(session, model.PermissionReadJobs), model.PermissionReadJobs } return false, nil diff --git a/app/job_test.go b/app/job_test.go index d6d596c311..0a82d1135f 100644 --- a/app/job_test.go +++ b/app/job_test.go @@ -39,17 +39,17 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) { jobs := []model.Job{ { Id: model.NewId(), - Type: model.JOB_TYPE_BLEVE_POST_INDEXING, + Type: model.JobTypeBlevePostIndexing, CreateAt: 1000, }, { Id: model.NewId(), - Type: model.JOB_TYPE_DATA_RETENTION, + Type: model.JobTypeDataRetention, CreateAt: 999, }, { Id: model.NewId(), - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Type: model.JobTypeMessageExport, CreateAt: 1001, }, } @@ -60,20 +60,20 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) { }{ { Job: jobs[0], - PermissionRequired: model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB, + PermissionRequired: model.PermissionCreatePostBleveIndexesJob, }, { Job: jobs[1], - PermissionRequired: model.PERMISSION_CREATE_DATA_RETENTION_JOB, + PermissionRequired: model.PermissionCreateDataRetentionJob, }, { Job: jobs[2], - PermissionRequired: model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB, + PermissionRequired: model.PermissionCreateComplianceExportJob, }, } session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, } // Check to see if admin has permission to all the jobs @@ -85,7 +85,7 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) { } session = model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemReadOnlyAdminRoleId, } // Initially the system read only admin should not have access to create these jobs @@ -97,9 +97,9 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) { } ctx := sqlstore.WithMaster(context.Background()) - role, _ := th.App.GetRoleByName(ctx, model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID) + role, _ := th.App.GetRoleByName(ctx, model.SystemReadOnlyAdminRoleId) - role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB.Id) + role.Permissions = append(role.Permissions, model.PermissionCreatePostBleveIndexesJob.Id) _, err := th.App.UpdateRole(role) require.Nil(t, err) @@ -107,14 +107,14 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) { // Now system read only admin should have ability to create a Belve Post Index job but not the others for _, testCase := range testCases { hasPermission, permissionRequired := th.App.SessionHasPermissionToCreateJob(session, &testCase.Job) - expectedHasPermission := testCase.Job.Type == model.JOB_TYPE_BLEVE_POST_INDEXING + expectedHasPermission := testCase.Job.Type == model.JobTypeBlevePostIndexing assert.Equal(t, expectedHasPermission, hasPermission) require.NotNil(t, permissionRequired) assert.Equal(t, testCase.PermissionRequired.Id, permissionRequired.Id) } - role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_DATA_RETENTION_JOB.Id) - role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB.Id) + role.Permissions = append(role.Permissions, model.PermissionCreateDataRetentionJob.Id) + role.Permissions = append(role.Permissions, model.PermissionCreateComplianceExportJob.Id) _, err = th.App.UpdateRole(role) require.Nil(t, err) @@ -135,12 +135,12 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { jobs := []model.Job{ { Id: model.NewId(), - Type: model.JOB_TYPE_DATA_RETENTION, + Type: model.JobTypeDataRetention, CreateAt: 999, }, { Id: model.NewId(), - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Type: model.JobTypeMessageExport, CreateAt: 1001, }, } @@ -150,16 +150,16 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { }{ { Job: jobs[0], - PermissionRequired: model.PERMISSION_READ_DATA_RETENTION_JOB, + PermissionRequired: model.PermissionReadDataRetentionJob, }, { Job: jobs[1], - PermissionRequired: model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB, + PermissionRequired: model.PermissionReadComplianceExportJob, }, } session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, } // Check to see if admin has permission to all the jobs @@ -171,7 +171,7 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { } session = model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_MANAGER_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemManagerRoleId, } // Initially the system manager should not have access to read these jobs @@ -183,9 +183,9 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { } ctx := sqlstore.WithMaster(context.Background()) - role, _ := th.App.GetRoleByName(ctx, model.SYSTEM_MANAGER_ROLE_ID) + role, _ := th.App.GetRoleByName(ctx, model.SystemManagerRoleId) - role.Permissions = append(role.Permissions, model.PERMISSION_READ_DATA_RETENTION_JOB.Id) + role.Permissions = append(role.Permissions, model.PermissionReadDataRetentionJob.Id) _, err := th.App.UpdateRole(role) require.Nil(t, err) @@ -193,13 +193,13 @@ func TestSessionHasPermissionToReadJob(t *testing.T) { // Now system manager should have ability to read data retention jobs for _, testCase := range testCases { hasPermission, permissionRequired := th.App.SessionHasPermissionToReadJob(session, testCase.Job.Type) - expectedHasPermission := testCase.Job.Type == model.JOB_TYPE_DATA_RETENTION + expectedHasPermission := testCase.Job.Type == model.JobTypeDataRetention assert.Equal(t, expectedHasPermission, hasPermission) require.NotNil(t, permissionRequired) assert.Equal(t, testCase.PermissionRequired.Id, permissionRequired.Id) } - role.Permissions = append(role.Permissions, model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB.Id) + role.Permissions = append(role.Permissions, model.PermissionReadComplianceExportJob.Id) _, err = th.App.UpdateRole(role) require.Nil(t, err) diff --git a/app/ldap.go b/app/ldap.go index 2fcb75b224..969dbc8700 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -128,7 +128,7 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) ( return "", err } - if user.AuthService != model.USER_AUTH_SERVICE_LDAP { + if user.AuthService != model.UserAuthServiceLdap { return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_ldap_account.app_error", nil, "", http.StatusBadRequest) } @@ -200,12 +200,12 @@ func (a *App) writeLdapFile(filename string, fileData *multipart.FileHeader) *mo } func (a *App) AddLdapPublicCertificate(fileData *multipart.FileHeader) *model.AppError { - if err := a.writeLdapFile(model.LDAP_PUBLIC_CERTIFICATE_NAME, fileData); err != nil { + if err := a.writeLdapFile(model.LdapPublicCertificateName, fileData); err != nil { return err } cfg := a.Config().Clone() - *cfg.LdapSettings.PublicCertificateFile = model.LDAP_PUBLIC_CERTIFICATE_NAME + *cfg.LdapSettings.PublicCertificateFile = model.LdapPublicCertificateName if err := cfg.IsValid(); err != nil { return err @@ -217,12 +217,12 @@ func (a *App) AddLdapPublicCertificate(fileData *multipart.FileHeader) *model.Ap } func (a *App) AddLdapPrivateCertificate(fileData *multipart.FileHeader) *model.AppError { - if err := a.writeLdapFile(model.LDAP_PRIVATE_KEY_NAME, fileData); err != nil { + if err := a.writeLdapFile(model.LdapPrivateKeyName, fileData); err != nil { return err } cfg := a.Config().Clone() - *cfg.LdapSettings.PrivateKeyFile = model.LDAP_PRIVATE_KEY_NAME + *cfg.LdapSettings.PrivateKeyFile = model.LdapPrivateKeyName if err := cfg.IsValid(); err != nil { return err diff --git a/app/license.go b/app/license.go index f0b467c5c5..e945bb7992 100644 --- a/app/license.go +++ b/app/license.go @@ -67,7 +67,7 @@ func (s *Server) LoadLicense() { licenseId := "" props, nErr := s.Store.System().Get() if nErr == nil { - licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID] + licenseId = props[model.SystemActiveLicenseId] } if !model.IsValidId(licenseId) { @@ -97,7 +97,7 @@ func (s *Server) LoadLicense() { func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { success, licenseStr := utils.LicenseValidator.ValidateLicense(licenseBytes) if !success { - return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest) + return nil, model.NewAppError("addLicense", model.InvalidLicenseError, nil, "", http.StatusBadRequest) } license := model.LicenseFromJson(strings.NewReader(licenseStr)) @@ -111,11 +111,11 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr } if license != nil && license.IsExpired() { - return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) + return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) } if ok := s.SetLicense(license); !ok { - return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) + return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) } record := &model.LicenseRecord{} @@ -135,7 +135,7 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr } sysVar := &model.System{} - sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID + sysVar.Name = model.SystemActiveLicenseId sysVar.Value = license.Id if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { s.RemoveLicense() @@ -220,10 +220,10 @@ func (s *Server) RemoveLicense() *model.AppError { return nil } - mlog.Info("Remove license.", mlog.String("id", model.SYSTEM_ACTIVE_LICENSE_ID)) + mlog.Info("Remove license.", mlog.String("id", model.SystemActiveLicenseId)) sysVar := &model.System{} - sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID + sysVar.Name = model.SystemActiveLicenseId sysVar.Value = "" if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { @@ -280,7 +280,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model. license := s.License() if license == nil { // Clean renewal token if there is no license present - if _, err := s.Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN); err != nil { + if _, err := s.Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken); err != nil { mlog.Warn("error removing the renewal token", mlog.Err(err)) } return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.no_license", nil, "", http.StatusBadRequest) @@ -290,7 +290,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model. return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.bad_license", nil, "", http.StatusBadRequest) } - currentToken, _ := s.Store.System().GetByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN) + currentToken, _ := s.Store.System().GetByName(model.SystemLicenseRenewalToken) if currentToken != nil { tokenIsValid, err := s.renewalTokenValid(currentToken.Value, license.Customer.Email) if err != nil { @@ -322,7 +322,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model. return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", nil, err.Error(), http.StatusInternalServerError) } err = s.Store.System().SaveOrUpdate(&model.System{ - Name: model.SYSTEM_LICENSE_RENEWAL_TOKEN, + Name: model.SystemLicenseRenewalToken, Value: tokenString, }) if err != nil { diff --git a/app/license_test.go b/app/license_test.go index a1eb00026d..76ec34d910 100644 --- a/app/license_test.go +++ b/app/license_test.go @@ -85,7 +85,7 @@ func TestGenerateRenewalToken(t *testing.T) { token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration) require.Nil(t, appErr) require.NotEmpty(t, token) - defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN) + defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken) customerEmail := th.App.Srv().License().Customer.Email validToken, err := th.App.Srv().renewalTokenValid(token, customerEmail) @@ -98,7 +98,7 @@ func TestGenerateRenewalToken(t *testing.T) { token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration) require.Nil(t, appErr) require.NotEmpty(t, token) - defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN) + defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken) newToken, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration) require.Nil(t, appErr) @@ -116,7 +116,7 @@ func TestGenerateRenewalToken(t *testing.T) { token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration) require.Nil(t, appErr) require.NotEmpty(t, token) - defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN) + defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken) setLicense(th, &model.Customer{ Name: "another customer", Email: "another@example.com", @@ -131,7 +131,7 @@ func TestGenerateRenewalToken(t *testing.T) { token, appErr := th.App.Srv().GenerateRenewalToken(1 * time.Second) require.Nil(t, appErr) require.NotEmpty(t, token) - defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN) + defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken) // The small time unit for expiration we're using is seconds time.Sleep(1 * time.Second) newToken, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration) diff --git a/app/login.go b/app/login.go index 54233f4f86..e2382c6e24 100644 --- a/app/login.go +++ b/app/login.go @@ -102,7 +102,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password // If client side cert is enable and it's checking as a primary source // then trust the proxy and cert that the correct user is supplied and allow // them access - if *a.Config().ExperimentalSettings.ClientSideCertEnable && *a.Config().ExperimentalSettings.ClientSideCertCheck == model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH { + if *a.Config().ExperimentalSettings.ClientSideCertEnable && *a.Config().ExperimentalSettings.ClientSideCertCheck == model.ClientSideCertCheckPrimaryAuth { // Unless the user is a bot. if err = checkUserNotBot(user); err != nil { return nil, err @@ -145,7 +145,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) // Try to get the user with LDAP if enabled if *a.Config().LdapSettings.Enable && a.Ldap() != nil { if ldapUser, err := a.Ldap().GetUser(loginId); err == nil { - if user, err := a.GetUserByAuth(ldapUser.AuthData, model.USER_AUTH_SERVICE_LDAP); err == nil { + if user, err := a.GetUserByAuth(ldapUser.AuthData, model.UserAuthServiceLdap); err == nil { return user, nil } return ldapUser, nil @@ -170,9 +170,9 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request } session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceID, IsOAuth: false, Props: map[string]string{ - model.USER_AUTH_SERVICE_IS_MOBILE: strconv.FormatBool(isMobile), - model.USER_AUTH_SERVICE_IS_SAML: strconv.FormatBool(isSaml), - model.USER_AUTH_SERVICE_IS_OAUTH: strconv.FormatBool(isOAuthUser), + model.UserAuthServiceIsMobile: strconv.FormatBool(isMobile), + model.UserAuthServiceIsSaml: strconv.FormatBool(isSaml), + model.UserAuthServiceIsOAuth: strconv.FormatBool(isOAuthUser), }} session.GenerateCSRF() @@ -199,13 +199,13 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request bname := getBrowserName(ua, r.UserAgent()) bversion := getBrowserVersion(ua, r.UserAgent()) - session.AddProp(model.SESSION_PROP_PLATFORM, plat) - session.AddProp(model.SESSION_PROP_OS, os) - session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion)) + session.AddProp(model.SessionPropPlatform, plat) + session.AddProp(model.SessionPropOs, os) + session.AddProp(model.SessionPropBrowser, fmt.Sprintf("%v/%v", bname, bversion)) if user.IsGuest() { - session.AddProp(model.SESSION_PROP_IS_GUEST, "true") + session.AddProp(model.SessionPropIsGuest, "true") } else { - session.AddProp(model.SESSION_PROP_IS_GUEST, "false") + session.AddProp(model.SessionPropIsGuest, "false") } var err *model.AppError @@ -214,7 +214,7 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request return err } - w.Header().Set(model.HEADER_TOKEN, session.Token) + w.Header().Set(model.HeaderToken, session.Token) c.SetSession(session) if a.Srv().License() != nil && *a.Srv().License().Features.LDAP && a.Ldap() != nil { @@ -250,7 +250,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0) sessionCookie := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: c.Session().Token, Path: subpath, MaxAge: maxAge, @@ -261,7 +261,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r } userCookie := &http.Cookie{ - Name: model.SESSION_COOKIE_USER, + Name: model.SessionCookieUser, Value: c.Session().UserId, Path: subpath, MaxAge: maxAge, @@ -271,7 +271,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r } csrfCookie := &http.Cookie{ - Name: model.SESSION_COOKIE_CSRF, + Name: model.SessionCookieCsrf, Value: c.Session().GetCSRF(), Path: subpath, MaxAge: maxAge, @@ -286,7 +286,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r } func GetProtocol(r *http.Request) string { - if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" || r.TLS != nil { + if r.Header.Get(model.HeaderForwardedProto) == "https" || r.TLS != nil { return "https" } return "http" diff --git a/app/migrations.go b/app/migrations.go index db52b89f11..88b1efc4bd 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -25,7 +25,7 @@ func (a *App) DoAdvancedPermissionsMigration() { func (s *Server) doAdvancedPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := s.Store.System().GetByName(model.AdvancedPermissionsMigrationKey); err == nil { return } @@ -68,7 +68,7 @@ func (s *Server) doAdvancedPermissionsMigration() { } config := s.Config() - if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.ALLOW_EDIT_POST_ALWAYS { + if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.AllowEditPostAlways { *config.ServiceSettings.PostEditTimeLimit = -1 if _, _, err := s.SaveConfig(config, true); err != nil { mlog.Error("Failed to update config in Advanced Permissions Phase 1 Migration.", mlog.Err(err)) @@ -76,7 +76,7 @@ func (s *Server) doAdvancedPermissionsMigration() { } system := model.System{ - Name: model.ADVANCED_PERMISSIONS_MIGRATION_KEY, + Name: model.AdvancedPermissionsMigrationKey, Value: "true", } @@ -87,7 +87,7 @@ func (s *Server) doAdvancedPermissionsMigration() { func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error { if !isComplete { - if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { return err } } @@ -111,19 +111,19 @@ func (s *Server) doEmojisPermissionsMigration() { mlog.Info("Migrating emojis config to database.") switch *s.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation { - case model.RESTRICT_EMOJI_CREATION_ALL: - role, err = s.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + case model.RestrictEmojiCreationAll: + role, err = s.GetRoleByName(context.Background(), model.SystemUserRoleId) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } - case model.RESTRICT_EMOJI_CREATION_ADMIN: - role, err = s.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID) + case model.RestrictEmojiCreationAdmin: + role, err = s.GetRoleByName(context.Background(), model.TeamAdminRoleId) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } - case model.RESTRICT_EMOJI_CREATION_SYSTEM_ADMIN: + case model.RestrictEmojiCreationSystemAdmin: role = nil default: mlog.Critical("Failed to migrate emojis creation permissions from mattermost config. Invalid restrict emoji creation setting") @@ -131,23 +131,23 @@ func (s *Server) doEmojisPermissionsMigration() { } if role != nil { - role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id) + role.Permissions = append(role.Permissions, model.PermissionCreateEmojis.Id, model.PermissionDeleteEmojis.Id) if _, nErr := s.Store.Role().Save(role); nErr != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(nErr)) return } } - systemAdminRole, err = s.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + systemAdminRole, err = s.GetRoleByName(context.Background(), model.SystemAdminRoleId) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } systemAdminRole.Permissions = append(systemAdminRole.Permissions, - model.PERMISSION_CREATE_EMOJIS.Id, - model.PERMISSION_DELETE_EMOJIS.Id, - model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, + model.PermissionCreateEmojis.Id, + model.PermissionDeleteEmojis.Id, + model.PermissionDeleteOthersEmojis.Id, ) if _, err := s.Store.Role().Save(systemAdminRole); err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) @@ -177,20 +177,20 @@ func (s *Server) doGuestRolesCreationMigration() { roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.ChannelGuestRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.ChannelGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.TeamGuestRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.TeamGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.SystemGuestRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.SystemGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } @@ -203,12 +203,12 @@ func (s *Server) doGuestRolesCreationMigration() { } for _, scheme := range schemes { if scheme.DefaultTeamGuestRole == "" || scheme.DefaultChannelGuestRole == "" { - if scheme.Scope == model.SCHEME_SCOPE_TEAM { + if scheme.Scope == model.SchemeScopeTeam { // Team Guest Role teamGuestRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Team Guest Role for Scheme %s", scheme.Name), - Permissions: roles[model.TEAM_GUEST_ROLE_ID].Permissions, + Permissions: roles[model.TeamGuestRoleId].Permissions, SchemeManaged: true, } @@ -224,7 +224,7 @@ func (s *Server) doGuestRolesCreationMigration() { channelGuestRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Channel Guest Role for Scheme %s", scheme.Name), - Permissions: roles[model.CHANNEL_GUEST_ROLE_ID].Permissions, + Permissions: roles[model.ChannelGuestRoleId].Permissions, SchemeManaged: true, } @@ -270,21 +270,21 @@ func (s *Server) doSystemConsoleRolesCreationMigration() { roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil { - mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_MANAGER_ROLE_ID)) + if _, err := s.Store.Role().GetByName(context.Background(), model.SystemManagerRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.SystemManagerRoleId]); err != nil { + mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemManagerRoleId)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil { - mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID)) + if _, err := s.Store.Role().GetByName(context.Background(), model.SystemReadOnlyAdminRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.SystemReadOnlyAdminRoleId]); err != nil { + mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemReadOnlyAdminRoleId)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil { - if _, err := s.Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil { - mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_USER_MANAGER_ROLE_ID)) + if _, err := s.Store.Role().GetByName(context.Background(), model.SystemUserManagerRoleId); err != nil { + if _, err := s.Store.Role().Save(roles[model.SystemUserManagerRoleId]); err != nil { + mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemUserManagerRoleId)) allSucceeded = false } } diff --git a/app/notification.go b/app/notification.go index 5dcdbe0c78..8bc943fa29 100644 --- a/app/notification.go +++ b/app/notification.go @@ -85,7 +85,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod allActivityPushUserIds := []string{} var allowChannelMentions bool var keywords map[string][]string - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { otherUserId := channel.GetOtherUserIdForDM(post.UserId) _, ok := profileMap[otherUserId] @@ -103,8 +103,8 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod mentions = getExplicitMentions(post, keywords, groups) // Add an implicit mention when a user is added to a channel // even if the user has set 'username mentions' to false in account settings. - if post.Type == model.POST_ADD_TO_CHANNEL { - addedUserId, ok := post.GetProp(model.POST_PROPS_ADDED_USER_ID).(string) + if post.Type == model.PostTypeAddToChannel { + addedUserId, ok := post.GetProp(model.PostPropsAddedUserId).(string) if ok { mentions.addMention(addedUserId, KeywordMention) } @@ -133,7 +133,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if threadPost.Id == parentPostList.Order[0] && threadPost.IsFromOAuthBot() { continue } - if profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY || (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ROOT && threadPost.Id == parentPostList.Order[0]) { + if profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyAny || (profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyRoot && threadPost.Id == parentPostList.Order[0]) { mentionType := ThreadMention if threadPost.Id == parentPostList.Order[0] { mentionType = CommentMention @@ -158,8 +158,8 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod // find which users in the channel are set up to always receive mobile notifications for _, profile := range profileMap { - if (profile.NotifyProps[model.PUSH_NOTIFY_PROP] == model.USER_NOTIFY_ALL || - channelMemberNotifyPropsMap[profile.Id][model.PUSH_NOTIFY_PROP] == model.CHANNEL_NOTIFY_ALL) && + if (profile.NotifyProps[model.PushNotifyProp] == model.UserNotifyAll || + channelMemberNotifyPropsMap[profile.Id][model.PushNotifyProp] == model.ChannelNotifyAll) && (post.UserId != profile.Id || post.GetProp("from_webhook") == "true") && !post.IsSystemMessage() { allActivityPushUserIds = append(allActivityPushUserIds, profile.Id) @@ -175,7 +175,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod var rootMentions *ExplicitMentions if parentPostList != nil { threadParticipants[parentPostList.Posts[parentPostList.Order[0]].UserId] = true - if channel.Type != model.CHANNEL_DIRECT { + if channel.Type != model.ChannelTypeDirect { rootPost := parentPostList.Posts[parentPostList.Order[0]] rootMentions = getExplicitMentions(rootPost, keywords, groups) for id := range rootMentions.Mentions { @@ -358,7 +358,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod var status *model.Status var err *model.AppError if status, err = a.GetStatus(id); err != nil { - status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: id, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], true, status, post) { @@ -366,9 +366,9 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod replyToThreadType := "" if mentionType == ThreadMention { - replyToThreadType = model.COMMENTS_NOTIFY_ANY + replyToThreadType = model.CommentsNotifyAny } else if mentionType == CommentMention { - replyToThreadType = model.COMMENTS_NOTIFY_ROOT + replyToThreadType = model.CommentsNotifyRoot } a.sendPushNotification( @@ -382,10 +382,10 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod // register that a notification was not sent a.NotificationsLog().Debug("Notification not sent", mlog.String("ackId", ""), - mlog.String("type", model.PUSH_TYPE_MESSAGE), + mlog.String("type", model.PushTypeMessage), mlog.String("userId", id), mlog.String("postId", post.Id), - mlog.String("status", model.PUSH_NOT_SENT), + mlog.String("status", model.PushNotSent), ) } } @@ -399,7 +399,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod var status *model.Status var err *model.AppError if status, err = a.GetStatus(id); err != nil { - status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: id, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], false, status, post) { @@ -414,25 +414,25 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod // register that a notification was not sent a.NotificationsLog().Debug("Notification not sent", mlog.String("ackId", ""), - mlog.String("type", model.PUSH_TYPE_MESSAGE), + mlog.String("type", model.PushTypeMessage), mlog.String("userId", id), mlog.String("postId", post.Id), - mlog.String("status", model.PUSH_NOT_SENT), + mlog.String("status", model.PushNotSent), ) } } } } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, "", post.ChannelId, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventPosted, "", post.ChannelId, "", nil) // Note that PreparePostForClient should've already been called by this point message.Add("post", post.ToJson()) message.Add("channel_type", channel.Type) - message.Add("channel_display_name", notification.GetChannelName(model.SHOW_USERNAME, "")) + message.Add("channel_display_name", notification.GetChannelName(model.ShowUsername, "")) message.Add("channel_name", channel.Name) - message.Add("sender_name", notification.GetSenderName(model.SHOW_USERNAME, *a.Config().ServiceSettings.EnablePostUsernameOverride)) + message.Add("sender_name", notification.GetSenderName(model.ShowUsername, *a.Config().ServiceSettings.EnablePostUsernameOverride)) message.Add("team_id", team.Id) message.Add("set_online", setOnline) @@ -461,19 +461,19 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod a.Publish(message) // If this is a reply in a thread, notify participants - if a.Config().FeatureFlags.CollapsedThreads && *a.Config().ServiceSettings.CollapsedThreads != model.COLLAPSED_THREADS_DISABLED && post.RootId != "" { + if a.Config().FeatureFlags.CollapsedThreads && *a.Config().ServiceSettings.CollapsedThreads != model.CollapsedThreadsDisabled && post.RootId != "" { followers, err := a.Srv().Store.Thread().GetThreadFollowers(post.RootId) if err != nil { return nil, errors.Wrapf(err, "cannot get thread %q followers", post.RootId) } for _, uid := range followers { - sendEvent := *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DEFAULT_ON + sendEvent := *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDefaultOn // check if a participant has overridden collapsed threads settings - if preference, err := a.Srv().Store.Preference().Get(uid, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED); err == nil { + if preference, err := a.Srv().Store.Preference().Get(uid, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil { sendEvent = preference.Value == "on" } if sendEvent { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, team.Id, "", uid, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, team.Id, "", uid, nil) threadMembership, err := a.Srv().Store.Thread().GetMembershipForUser(uid, post.RootId) if err != nil { return nil, errors.Wrapf(err, "cannot get thread membership %q for user %q", post.RootId, uid) @@ -496,16 +496,16 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps model.StringMap, post *model.Post) bool { - userAllowsEmails := user.NotifyProps[model.EMAIL_NOTIFY_PROP] != "false" - if channelEmail, ok := channelMemberNotificationProps[model.EMAIL_NOTIFY_PROP]; ok { - if channelEmail != model.CHANNEL_NOTIFY_DEFAULT { + userAllowsEmails := user.NotifyProps[model.EmailNotifyProp] != "false" + if channelEmail, ok := channelMemberNotificationProps[model.EmailNotifyProp]; ok { + if channelEmail != model.ChannelNotifyDefault { userAllowsEmails = channelEmail != "false" } } // Remove the user as recipient when the user has muted the channel. - if channelMuted, ok := channelMemberNotificationProps[model.MARK_UNREAD_NOTIFY_PROP]; ok { - if channelMuted == model.CHANNEL_MARK_UNREAD_MENTION { + if channelMuted, ok := channelMemberNotificationProps[model.MarkUnreadNotifyProp]; ok { + if channelMuted == model.ChannelMarkUnreadMention { mlog.Debug("Channel muted for user", mlog.String("user_id", user.Id), mlog.String("channel_mute", channelMuted)) userAllowsEmails = false } @@ -516,15 +516,15 @@ func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps m if status, err = a.GetStatus(user.Id); err != nil { status = &model.Status{ UserId: user.Id, - Status: model.STATUS_OFFLINE, + Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: "", } } - autoResponderRelated := status.Status == model.STATUS_OUT_OF_OFFICE || post.Type == model.POST_AUTO_RESPONDER - emailNotificationsAllowedForStatus := status.Status != model.STATUS_ONLINE && status.Status != model.STATUS_DND + autoResponderRelated := status.Status == model.StatusOutOfOffice || post.Type == model.PostTypeAutoResponder + emailNotificationsAllowedForStatus := status.Status != model.StatusOnline && status.Status != model.StatusDnd return userAllowsEmails && emailNotificationsAllowedForStatus && user.DeleteAt == 0 && !autoResponderRelated } @@ -577,7 +577,7 @@ func (a *App) filterOutOfChannelMentions(sender *model.User, post *model.Post, c return nil, nil, nil } - if channel.TeamId == "" || channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { + if channel.TeamId == "" || channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { return nil, nil, nil } @@ -669,7 +669,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan } props := model.StringInterface{ - model.PROPS_ADD_CHANNEL_MEMBER: model.StringInterface{ + model.PropsAddChannelMember: model.StringInterface{ "post_id": ephemeralPostId, "usernames": allUsers.Usernames(), // Kept for backwards compatibility of mobile app. @@ -844,11 +844,11 @@ func getMentionsEnabledFields(post *model.Post) model.StringArray { // allowChannelMentions returns whether or not the channel mentions are allowed for the given post. func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool { - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_CHANNEL_MENTIONS) { + if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { return false } - if post.Type == model.POST_HEADER_CHANGE || post.Type == model.POST_PURPOSE_CHANGE { + if post.Type == model.PostTypeHeaderChange || post.Type == model.PostTypePurposeChange { return false } @@ -865,11 +865,11 @@ func (a *App) allowGroupMentions(post *model.Post) bool { return false } - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) { + if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { return false } - if post.Type == model.POST_HEADER_CHANGE || post.Type == model.POST_PURPOSE_CHANGE { + if post.Type == model.PostTypeHeaderChange || post.Type == model.PostTypePurposeChange { return false } @@ -990,20 +990,20 @@ func addMentionKeywordsForUser(keywords map[string][]string, profile *model.User } // If turned on, add the user's case sensitive first name - if profile.NotifyProps[model.FIRST_NAME_NOTIFY_PROP] == "true" && profile.FirstName != "" { + if profile.NotifyProps[model.FirstNameNotifyProp] == "true" && profile.FirstName != "" { keywords[profile.FirstName] = append(keywords[profile.FirstName], profile.Id) } // Add @channel and @all to keywords if user has them turned on and the server allows them if allowChannelMentions { // Ignore channel mentions if channel is muted and channel mention setting is default - ignoreChannelMentions := channelNotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] == model.IGNORE_CHANNEL_MENTIONS_ON || (channelNotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.USER_NOTIFY_MENTION && channelNotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] == model.IGNORE_CHANNEL_MENTIONS_DEFAULT) + ignoreChannelMentions := channelNotifyProps[model.IgnoreChannelMentionsNotifyProp] == model.IgnoreChannelMentionsOn || (channelNotifyProps[model.MarkUnreadNotifyProp] == model.UserNotifyMention && channelNotifyProps[model.IgnoreChannelMentionsNotifyProp] == model.IgnoreChannelMentionsDefault) - if profile.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] == "true" && !ignoreChannelMentions { + if profile.NotifyProps[model.ChannelMentionsNotifyProp] == "true" && !ignoreChannelMentions { keywords["@channel"] = append(keywords["@channel"], profile.Id) keywords["@all"] = append(keywords["@all"], profile.Id) - if status != nil && status.Status == model.STATUS_ONLINE { + if status != nil && status.Status == model.StatusOnline { keywords["@here"] = append(keywords["@here"], profile.Id) } } @@ -1025,9 +1025,9 @@ type PostNotification struct { // channel, with an option to exclude the recipient of the message from that list. func (n *PostNotification) GetChannelName(userNameFormat, excludeId string) string { switch n.Channel.Type { - case model.CHANNEL_DIRECT: + case model.ChannelTypeDirect: return n.Sender.GetDisplayNameWithPrefix(userNameFormat, "@") - case model.CHANNEL_GROUP: + case model.ChannelTypeGroup: names := []string{} for _, user := range n.ProfileMap { if user.Id != excludeId { @@ -1050,7 +1050,7 @@ func (n *PostNotification) GetSenderName(userNameFormat string, overridesAllowed return i18n.T("system.message.name") } - if overridesAllowed && n.Channel.Type != model.CHANNEL_DIRECT { + if overridesAllowed && n.Channel.Type != model.ChannelTypeDirect { if value, ok := n.Post.GetProps()["override_username"]; ok && n.Post.GetProp("from_webhook") == "true" { return value.(string) } @@ -1182,10 +1182,10 @@ func (m *ExplicitMentions) processText(text string, keywords map[string][]string func (a *App) GetNotificationNameFormat(user *model.User) string { if !*a.Config().PrivacySettings.ShowFullName { - return model.SHOW_USERNAME + return model.ShowUsername } - data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_NAME_FORMAT) + data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameNameFormat) if err != nil { return *a.Config().TeamSettings.TeammateNameDisplay } diff --git a/app/notification_email.go b/app/notification_email.go index 8ea85f689f..43d5a84025 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -48,12 +48,12 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. if *a.Config().EmailSettings.EnableEmailBatching { var sendBatched bool - if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); err != nil { + if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval); err != nil { // if the call fails, assume that the interval has not been explicitly set and batch the notifications sendBatched = true } else { // if the user has chosen to receive notifications immediately, don't batch them - sendBatched = data.Value != model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS + sendBatched = data.Value != model.PreferenceEmailIntervalNoBatchingSeconds } if sendBatched { @@ -68,7 +68,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. translateFunc := i18n.GetUserTranslations(user.Locale) var useMilitaryTime bool - if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME); err != nil { + if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime); err != nil { useMilitaryTime = true } else { useMilitaryTime = data.Value == "true" @@ -79,15 +79,15 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. channelName := notification.GetChannelName(nameFormat, "") senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride) - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull if license := a.Srv().License(); license != nil && *license.Features.EmailNotificationContents { emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType } var subjectText string - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { subjectText = getDirectMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, senderName, useMilitaryTime) - } else if channel.Type == model.CHANNEL_GROUP { + } else if channel.Type == model.ChannelTypeGroup { subjectText = getGroupMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, channelName, emailNotificationContentsType, useMilitaryTime) } else if *a.Config().EmailSettings.UseChannelInEmailNotifications { subjectText = getNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, team.DisplayName+" ("+channelName+")", useMilitaryTime) @@ -97,7 +97,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. senderPhoto := "" embeddedFiles := make(map[string]io.Reader) - if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL && senderProfileImage != nil { + if emailNotificationContentsType == model.EmailNotificationContentsFull && senderProfileImage != nil { senderPhoto = "user-avatar.png" embeddedFiles = map[string]io.Reader{ senderPhoto: bytes.NewReader(senderProfileImage), @@ -165,7 +165,7 @@ func getGroupMessageNotificationEmailSubject(user *model.User, post *model.Post, "Day": t.Day, "Year": t.Year, } - if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { + if emailNotificationContentsType == model.EmailNotificationContentsFull { subjectParameters["ChannelName"] = channelName return translateFunc("app.notification.subject.group_message.full", subjectParameters) } @@ -198,7 +198,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, "TimeZone": t.TimeZone, } - if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { + if emailNotificationContentsType == model.EmailNotificationContentsFull { postMessage := a.GetMessageForNotification(post, translateFunc) postMessage = html.EscapeString(postMessage) normalizedPostMessage, err := a.generateHyperlinkForChannels(postMessage, teamName, landingURL) @@ -224,11 +224,11 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, data.Props["NotificationFooterInfoLogin"] = translateFunc("app.notification.footer.infoLogin") data.Props["NotificationFooterInfo"] = translateFunc("app.notification.footer.info") - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { // Direct Messages data.Props["Title"] = translateFunc("app.notification.body.dm.title", map[string]interface{}{"SenderName": senderName}) data.Props["SubTitle"] = translateFunc("app.notification.body.dm.subTitle", map[string]interface{}{"SenderName": senderName}) - } else if channel.Type == model.CHANNEL_GROUP { + } else if channel.Type == model.ChannelTypeGroup { // Group Messages data.Props["Title"] = translateFunc("app.notification.body.group.title", map[string]interface{}{"SenderName": senderName}) data.Props["SubTitle"] = translateFunc("app.notification.body.group.subTitle", map[string]interface{}{"SenderName": senderName}) @@ -240,7 +240,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, } // only include posts in notification email if email notification contents type is set to full - if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { + if emailNotificationContentsType == model.EmailNotificationContentsFull { data.Props["Posts"] = []postData{pData} } else { data.Props["Posts"] = []postData{} @@ -309,7 +309,7 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string visited := make(map[string]bool) for _, ch := range channels { - if !visited[ch.Id] && ch.Type == model.CHANNEL_OPEN { + if !visited[ch.Id] && ch.Type == model.ChannelTypeOpen { channelURL := teamURL + "/channels/" + ch.Name channelHyperLink := fmt.Sprintf("%s", channelURL, "~"+ch.Name) postMessage = strings.Replace(postMessage, "~"+ch.Name, channelHyperLink, -1) diff --git a/app/notification_email_test.go b/app/notification_email_test.go index 43aaa52f7a..957aa0a8c6 100644 --- a/app/notification_email_test.go +++ b/app/notification_email_test.go @@ -38,7 +38,7 @@ func TestGetGroupMessageNotificationEmailSubjectFull(t *testing.T) { CreateAt: 1501804801000, } translateFunc := i18n.GetUserTranslations("en") - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull subject := getGroupMessageNotificationEmailSubject(user, post, translateFunc, "http://localhost:8065", "sender", emailNotificationContentsType, true) require.Regexp(t, regexp.MustCompile("^"+regexp.QuoteMeta(expectedPrefix)), subject, fmt.Sprintf("Expected subject line prefix '%s', got %s", expectedPrefix, subject)) } @@ -50,7 +50,7 @@ func TestGetGroupMessageNotificationEmailSubjectGeneric(t *testing.T) { CreateAt: 1501804801000, } translateFunc := i18n.GetUserTranslations("en") - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC + emailNotificationContentsType := model.EmailNotificationContentsGeneric subject := getGroupMessageNotificationEmailSubject(user, post, translateFunc, "http://localhost:8065", "sender", emailNotificationContentsType, true) require.Regexp(t, regexp.MustCompile("^"+regexp.QuoteMeta(expectedPrefix)), subject, fmt.Sprintf("Expected subject line prefix '%s', got %s", expectedPrefix, subject)) } @@ -76,13 +76,13 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -107,13 +107,13 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -138,13 +138,13 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -169,13 +169,13 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -204,13 +204,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeWithTimezone(t *testi } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -238,13 +238,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeNoTimezone(t *testing } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -287,13 +287,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime12Hour(t *testing.T) } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -320,13 +320,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime24Hour(t *testing.T) } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -350,13 +350,13 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC + emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -380,13 +380,13 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC + emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -410,13 +410,13 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC + emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -440,13 +440,13 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC + emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -466,7 +466,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) { ch := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelName := "ChannelName" recipient := &model.User{} @@ -478,7 +478,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) { senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -501,7 +501,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) { ch := &model.Channel{ Name: "channelname", DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } id := model.NewId() recipient := &model.User{ @@ -518,7 +518,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) { senderName := "user1" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -547,7 +547,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { Id: model.NewId(), Name: "channelnameone", DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention := "~" + ch.Name @@ -555,7 +555,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { Id: model.NewId(), Name: "channelnametwo", DisplayName: "ChannelName2", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention2 := "~" + ch2.Name @@ -563,7 +563,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { Id: model.NewId(), Name: "channelnamethree", DisplayName: "ChannelName3", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention3 := "~" + ch3.Name @@ -584,7 +584,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { senderName := "user1" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -616,7 +616,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) { ch := &model.Channel{ Name: "channelname", DisplayName: "ChannelName", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } id := model.NewId() recipient := &model.User{ @@ -633,7 +633,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) { senderName := "user1" teamName := "testteam" teamURL := "http://localhost:8065/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -661,7 +661,7 @@ func TestGenerateHyperlinkForChannelsPublic(t *testing.T) { ch := &model.Channel{ Name: "channelname", DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } message := "This is the message " mention := "~" + ch.Name @@ -693,7 +693,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) { Id: model.NewId(), Name: "channelnameone", DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention := "~" + ch.Name @@ -701,7 +701,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) { Id: model.NewId(), Name: "channelnametwo", DisplayName: "ChannelName2", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention2 := "~" + ch2.Name @@ -709,7 +709,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) { Id: model.NewId(), Name: "channelnamethree", DisplayName: "ChannelName3", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } mention3 := "~" + ch3.Name @@ -746,7 +746,7 @@ func TestGenerateHyperlinkForChannelsPrivate(t *testing.T) { ch := &model.Channel{ Name: "channelname", DisplayName: "ChannelName", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } message := "This is the message ~" + ch.Name @@ -777,13 +777,13 @@ func TestLandingLink(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/landing#/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) @@ -807,13 +807,13 @@ func TestLandingLinkPermalink(t *testing.T) { } channel := &model.Channel{ DisplayName: "ChannelName", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelName := "ChannelName" senderName := "sender" teamName := "testteam" teamURL := "http://localhost:8065/landing#/testteam" - emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL + emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") storeMock := th.App.Srv().Store.(*mocks.Store) diff --git a/app/notification_push.go b/app/notification_push.go index 58d2c2bd45..9624cf42bc 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -122,7 +122,7 @@ func (a *App) sendPushNotificationToAllSessions(msg *model.PushNotification, use mlog.String("postId", tmpMessage.PostId), mlog.String("channelId", tmpMessage.ChannelId), mlog.String("deviceId", tmpMessage.DeviceId), - mlog.String("status", model.PUSH_SEND_SUCCESS), + mlog.String("status", model.PushSendSuccess), ) if a.Metrics() != nil { @@ -165,20 +165,20 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp // If the post only has images then push an appropriate message if postMessage == "" && hasFiles { - if channelType == model.CHANNEL_DIRECT { + if channelType == model.ChannelTypeDirect { return strings.Trim(userLocale("api.post.send_notifications_and_forget.push_image_only"), " ") } return senderName + userLocale("api.post.send_notifications_and_forget.push_image_only") } - if contentsConfig == model.FULL_NOTIFICATION { - if channelType == model.CHANNEL_DIRECT { + if contentsConfig == model.FullNotification { + if channelType == model.ChannelTypeDirect { return model.ClearMentionTags(postMessage) } return senderName + ": " + model.ClearMentionTags(postMessage) } - if channelType == model.CHANNEL_DIRECT { + if channelType == model.ChannelTypeDirect { return userLocale("api.post.send_notifications_and_forget.push_message") } @@ -190,11 +190,11 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp return senderName + userLocale("api.post.send_notifications_and_forget.push_explicit_mention") } - if replyToThreadType == model.COMMENTS_NOTIFY_ROOT { + if replyToThreadType == model.CommentsNotifyRoot { return senderName + userLocale("api.post.send_notification_and_forget.push_comment_on_post") } - if replyToThreadType == model.COMMENTS_NOTIFY_ANY { + if replyToThreadType == model.CommentsNotifyAny { return senderName + userLocale("api.post.send_notification_and_forget.push_comment_on_thread") } @@ -203,8 +203,8 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp func (a *App) clearPushNotificationSync(currentSessionId, userID, channelID string) *model.AppError { msg := &model.PushNotification{ - Type: model.PUSH_TYPE_CLEAR, - Version: model.PUSH_MESSAGE_V2, + Type: model.PushTypeClear, + Version: model.PushMessageV2, ChannelId: channelID, ContentAvailable: 1, } @@ -234,8 +234,8 @@ func (a *App) clearPushNotification(currentSessionId, userID, channelID string) func (a *App) updateMobileAppBadgeSync(userID string) *model.AppError { msg := &model.PushNotification{ - Type: model.PUSH_TYPE_UPDATE_BADGE, - Version: model.PUSH_MESSAGE_V2, + Type: model.PushTypeUpdateBadge, + Version: model.PushMessageV2, Sound: "none", ContentAvailable: 1, } @@ -360,10 +360,10 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio mlog.String("type", msg.Type), mlog.String("userId", session.UserId), mlog.String("postId", msg.PostId), - mlog.String("status", model.PUSH_SEND_PREPARE), + mlog.String("status", model.PushSendPrepare), ) - url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.API_URL_SUFFIX_V1 + "/send_push" + url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.ApiUrlSuffixV1 + "/send_push" request, err := http.NewRequest("POST", url, strings.NewReader(msg.ToJson())) if err != nil { return err @@ -377,13 +377,13 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio pushResponse := model.PushResponseFromJson(resp.Body) - switch pushResponse[model.PUSH_STATUS] { - case model.PUSH_STATUS_REMOVE: + switch pushResponse[model.PushStatus] { + case model.PushStatusRemove: a.AttachDeviceId(session.Id, "", session.ExpiresAt) a.ClearSessionCacheForUser(session.UserId) return errors.New("Device was reported as removed") - case model.PUSH_STATUS_FAIL: - return errors.New(pushResponse[model.PUSH_STATUS_ERROR_MSG]) + case model.PushStatusFail: + return errors.New(pushResponse[model.PushStatusErrorMsg]) } return nil } @@ -398,12 +398,12 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { mlog.String("type", ack.NotificationType), mlog.String("deviceType", ack.ClientPlatform), mlog.Int64("receivedAt", ack.ClientReceivedAt), - mlog.String("status", model.PUSH_RECEIVED), + mlog.String("status", model.PushReceived), ) request, err := http.NewRequest( "POST", - strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.API_URL_SUFFIX_V1+"/ack", + strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.ApiUrlSuffixV1+"/ack", strings.NewReader(ack.ToJson()), ) @@ -441,14 +441,14 @@ func ShouldSendPushNotification(user *model.User, channelNotifyProps model.Strin func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps model.StringMap, post *model.Post, wasMentioned bool) bool { userNotifyProps := user.NotifyProps - userNotify := userNotifyProps[model.PUSH_NOTIFY_PROP] - channelNotify, ok := channelNotifyProps[model.PUSH_NOTIFY_PROP] + userNotify := userNotifyProps[model.PushNotifyProp] + channelNotify, ok := channelNotifyProps[model.PushNotifyProp] if !ok || channelNotify == "" { - channelNotify = model.CHANNEL_NOTIFY_DEFAULT + channelNotify = model.ChannelNotifyDefault } // If the channel is muted do not send push notifications - if channelNotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_MARK_UNREAD_MENTION { + if channelNotifyProps[model.MarkUnreadNotifyProp] == model.ChannelMarkUnreadMention { return false } @@ -456,25 +456,25 @@ func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps m return false } - if channelNotify == model.USER_NOTIFY_NONE { + if channelNotify == model.UserNotifyNone { return false } - if channelNotify == model.CHANNEL_NOTIFY_MENTION && !wasMentioned { + if channelNotify == model.ChannelNotifyMention && !wasMentioned { return false } - if userNotify == model.USER_NOTIFY_MENTION && channelNotify == model.CHANNEL_NOTIFY_DEFAULT && !wasMentioned { + if userNotify == model.UserNotifyMention && channelNotify == model.ChannelNotifyDefault && !wasMentioned { return false } - if (userNotify == model.USER_NOTIFY_ALL || channelNotify == model.CHANNEL_NOTIFY_ALL) && + if (userNotify == model.UserNotifyAll || channelNotify == model.ChannelNotifyAll) && (post.UserId != user.Id || post.GetProp("from_webhook") == "true") { return true } - if userNotify == model.USER_NOTIFY_NONE && - channelNotify == model.CHANNEL_NOTIFY_DEFAULT { + if userNotify == model.UserNotifyNone && + channelNotify == model.ChannelNotifyDefault { return false } @@ -483,20 +483,20 @@ func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps m func DoesStatusAllowPushNotification(userNotifyProps model.StringMap, status *model.Status, channelID string) bool { // If User status is DND or OOO return false right away - if status.Status == model.STATUS_DND || status.Status == model.STATUS_OUT_OF_OFFICE { + if status.Status == model.StatusDnd || status.Status == model.StatusOutOfOffice { return false } - pushStatus, ok := userNotifyProps[model.PUSH_STATUS_NOTIFY_PROP] - if (pushStatus == model.STATUS_ONLINE || !ok) && (status.ActiveChannel != channelID || model.GetMillis()-status.LastActivityAt > model.STATUS_CHANNEL_TIMEOUT) { + pushStatus, ok := userNotifyProps[model.PushStatusNotifyProp] + if (pushStatus == model.StatusOnline || !ok) && (status.ActiveChannel != channelID || model.GetMillis()-status.LastActivityAt > model.StatusChannelTimeout) { return true } - if pushStatus == model.STATUS_AWAY && (status.Status == model.STATUS_AWAY || status.Status == model.STATUS_OFFLINE) { + if pushStatus == model.StatusAway && (status.Status == model.StatusAway || status.Status == model.StatusOffline) { return true } - if pushStatus == model.STATUS_OFFLINE && status.Status == model.STATUS_OFFLINE { + if pushStatus == model.StatusOffline && status.Status == model.StatusOffline { return true } @@ -509,11 +509,11 @@ func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Po var msg *model.PushNotification notificationInterface := a.Srv().Notification - if (notificationInterface == nil || notificationInterface.CheckLicense() != nil) && contentsConfig == model.ID_LOADED_NOTIFICATION { - contentsConfig = model.GENERIC_NOTIFICATION + if (notificationInterface == nil || notificationInterface.CheckLicense() != nil) && contentsConfig == model.IdLoadedNotification { + contentsConfig = model.GenericNotification } - if contentsConfig == model.ID_LOADED_NOTIFICATION { + if contentsConfig == model.IdLoadedNotification { msg = a.buildIdLoadedPushNotificationMessage(post, user) } else { msg = a.buildFullPushNotificationMessage(contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) @@ -533,9 +533,9 @@ func (a *App) buildIdLoadedPushNotificationMessage(post *model.Post, user *model msg := &model.PushNotification{ PostId: post.Id, ChannelId: post.ChannelId, - Category: model.CATEGORY_CAN_REPLY, - Version: model.PUSH_MESSAGE_V2, - Type: model.PUSH_TYPE_MESSAGE, + Category: model.CategoryCanReply, + Version: model.PushMessageV2, + Type: model.PushTypeMessage, IsIdLoaded: true, SenderId: user.Id, Message: userLocale("api.push_notification.id_loaded.default_message"), @@ -548,9 +548,9 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode explicitMention bool, channelWideMention bool, replyToThreadType string) *model.PushNotification { msg := &model.PushNotification{ - Category: model.CATEGORY_CAN_REPLY, - Version: model.PUSH_MESSAGE_V2, - Type: model.PUSH_TYPE_MESSAGE, + Category: model.CategoryCanReply, + Version: model.PushMessageV2, + Type: model.PushTypeMessage, TeamId: channel.TeamId, ChannelId: channel.Id, PostId: post.Id, @@ -560,7 +560,7 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode } cfg := a.Config() - if contentsConfig != model.GENERIC_NO_CHANNEL_NOTIFICATION || channel.Type == model.CHANNEL_DIRECT { + if contentsConfig != model.GenericNoChannelNotification || channel.Type == model.ChannelTypeDirect { msg.ChannelName = channelName } diff --git a/app/notification_push_test.go b/app/notification_push_test.go index 32b6f1be89..24d963649f 100644 --- a/app/notification_push_test.go +++ b/app/notification_push_test.go @@ -34,7 +34,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }{ { name: "When post is a System Message and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, channelNotifySetting: "", withSystemPost: true, wasMentioned: false, @@ -43,7 +43,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When post is a System Message and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, channelNotifySetting: "", withSystemPost: true, wasMentioned: true, @@ -52,7 +52,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, no channel props is set and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, channelNotifySetting: "", withSystemPost: false, wasMentioned: false, @@ -61,7 +61,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, no channel props is set and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, channelNotifySetting: "", withSystemPost: false, wasMentioned: true, @@ -70,7 +70,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, no channel props is set and has no mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyMention, channelNotifySetting: "", withSystemPost: false, wasMentioned: false, @@ -79,7 +79,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, no channel props is set and has mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyMention, channelNotifySetting: "", withSystemPost: false, wasMentioned: true, @@ -88,7 +88,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, no channel props is set and has no mentions", - userNotifySetting: model.USER_NOTIFY_NONE, + userNotifySetting: model.UserNotifyNone, channelNotifySetting: "", withSystemPost: false, wasMentioned: false, @@ -97,7 +97,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, no channel props is set and has mentions", - userNotifySetting: model.USER_NOTIFY_NONE, + userNotifySetting: model.UserNotifyNone, channelNotifySetting: "", withSystemPost: false, wasMentioned: true, @@ -106,8 +106,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is DEFAULT and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -115,8 +115,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is DEFAULT and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -124,8 +124,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is DEFAULT and has no mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -133,8 +133,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is DEFAULT and has mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -142,8 +142,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is DEFAULT and has no mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -151,8 +151,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is DEFAULT and has mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_DEFAULT, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyDefault, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -160,8 +160,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is ALL and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -169,8 +169,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is ALL and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -178,8 +178,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is ALL and has no mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -187,8 +187,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is ALL and has mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -196,8 +196,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is ALL and has no mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -205,8 +205,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is ALL and has mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_ALL, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyAll, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -214,8 +214,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is MENTION and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -223,8 +223,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is MENTION and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -232,8 +232,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is MENTION and has no mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -241,8 +241,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is MENTION and has mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -250,8 +250,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is MENTION and has no mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -259,8 +259,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is MENTION and has mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_MENTION, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyMention, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -268,8 +268,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is NONE and has no mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -277,8 +277,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, channel is NONE and has mentions", - userNotifySetting: model.USER_NOTIFY_ALL, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyAll, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -286,8 +286,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is NONE and has no mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -295,8 +295,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is MENTION, channel is NONE and has mentions", - userNotifySetting: model.USER_NOTIFY_MENTION, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyMention, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -304,8 +304,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is NONE and has no mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: false, isMuted: false, @@ -313,8 +313,8 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is NONE, channel is NONE and has mentions", - userNotifySetting: model.USER_NOTIFY_NONE, - channelNotifySetting: model.CHANNEL_NOTIFY_NONE, + userNotifySetting: model.UserNotifyNone, + channelNotifySetting: model.ChannelNotifyNone, withSystemPost: false, wasMentioned: true, isMuted: false, @@ -322,7 +322,7 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { }, { name: "When default is ALL, and channel is MUTED", - userNotifySetting: model.USER_NOTIFY_ALL, + userNotifySetting: model.UserNotifyAll, channelNotifySetting: "", withSystemPost: false, wasMentioned: false, @@ -334,18 +334,18 @@ func TestDoesNotifyPropsAllowPushNotification(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { user := &model.User{Id: model.NewId(), Email: "unit@test.com", NotifyProps: make(map[string]string)} - user.NotifyProps[model.PUSH_NOTIFY_PROP] = tc.userNotifySetting + user.NotifyProps[model.PushNotifyProp] = tc.userNotifySetting post := &model.Post{UserId: user.Id, ChannelId: model.NewId()} if tc.withSystemPost { - post.Type = model.POST_JOIN_CHANNEL + post.Type = model.PostTypeJoinChannel } channelNotifyProps := make(map[string]string) if tc.channelNotifySetting != "" { - channelNotifyProps[model.PUSH_NOTIFY_PROP] = tc.channelNotifySetting + channelNotifyProps[model.PushNotifyProp] = tc.channelNotifySetting } if tc.isMuted { - channelNotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_MARK_UNREAD_MENTION + channelNotifyProps[model.MarkUnreadNotifyProp] = model.ChannelMarkUnreadMention } assert.Equal(t, tc.expected, DoesNotifyPropsAllowPushNotification(user, channelNotifyProps, post, tc.wasMentioned)) }) @@ -356,10 +356,10 @@ func TestDoesStatusAllowPushNotification(t *testing.T) { userID := model.NewId() channelID := model.NewId() - offline := &model.Status{UserId: userID, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} - away := &model.Status{UserId: userID, Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""} - online := &model.Status{UserId: userID, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} - dnd := &model.Status{UserId: userID, Status: model.STATUS_DND, Manual: true, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + offline := &model.Status{UserId: userID, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + away := &model.Status{UserId: userID, Status: model.StatusAway, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + online := &model.Status{UserId: userID, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + dnd := &model.Status{UserId: userID, Status: model.StatusDnd, Manual: true, LastActivityAt: model.GetMillis(), ActiveChannel: ""} tt := []struct { name string @@ -370,168 +370,168 @@ func TestDoesStatusAllowPushNotification(t *testing.T) { }{ { name: "WHEN props is ONLINE and user is offline with channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: offline, channelID: channelID, expected: true, }, { name: "WHEN props is ONLINE and user is offline without channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: offline, channelID: "", expected: true, }, { name: "WHEN props is ONLINE and user is away with channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: away, channelID: channelID, expected: true, }, { name: "WHEN props is ONLINE and user is away without channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: away, channelID: "", expected: true, }, { name: "WHEN props is ONLINE and user is online with channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: online, channelID: channelID, expected: true, }, { name: "WHEN props is ONLINE and user is online without channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: online, channelID: "", expected: false, }, { name: "WHEN props is ONLINE and user is dnd with channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: dnd, channelID: channelID, expected: false, }, { name: "WHEN props is ONLINE and user is dnd without channel", - userNotifySetting: model.STATUS_ONLINE, + userNotifySetting: model.StatusOnline, status: dnd, channelID: "", expected: false, }, { name: "WHEN props is AWAY and user is offline with channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: offline, channelID: channelID, expected: true, }, { name: "WHEN props is AWAY and user is offline without channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: offline, channelID: "", expected: true, }, { name: "WHEN props is AWAY and user is away with channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: away, channelID: channelID, expected: true, }, { name: "WHEN props is AWAY and user is away without channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: away, channelID: "", expected: true, }, { name: "WHEN props is AWAY and user is online with channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: online, channelID: channelID, expected: false, }, { name: "WHEN props is AWAY and user is online without channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: online, channelID: "", expected: false, }, { name: "WHEN props is AWAY and user is dnd with channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: dnd, channelID: channelID, expected: false, }, { name: "WHEN props is AWAY and user is dnd without channel", - userNotifySetting: model.STATUS_AWAY, + userNotifySetting: model.StatusAway, status: dnd, channelID: "", expected: false, }, { name: "WHEN props is OFFLINE and user is offline with channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: offline, channelID: channelID, expected: true, }, { name: "WHEN props is OFFLINE and user is offline without channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: offline, channelID: "", expected: true, }, { name: "WHEN props is OFFLINE and user is away with channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: away, channelID: channelID, expected: false, }, { name: "WHEN props is OFFLINE and user is away without channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: away, channelID: "", expected: false, }, { name: "WHEN props is OFFLINE and user is online with channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: online, channelID: channelID, expected: false, }, { name: "WHEN props is OFFLINE and user is online without channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: online, channelID: "", expected: false, }, { name: "WHEN props is OFFLINE and user is dnd with channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: dnd, channelID: channelID, expected: false, }, { name: "WHEN props is OFFLINE and user is dnd without channel", - userNotifySetting: model.STATUS_OFFLINE, + userNotifySetting: model.StatusOffline, status: dnd, channelID: "", expected: false, @@ -579,314 +579,314 @@ func TestGetPushNotificationMessage(t *testing.T) { }{ "full message, public channel, no mention": { Message: "this is a message", - ChannelType: model.CHANNEL_OPEN, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user: this is a message", }, "full message, public channel, mention": { Message: "this is a message", explicitMention: true, - ChannelType: model.CHANNEL_OPEN, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user: this is a message", }, "full message, public channel, channel wide mention": { Message: "this is a message", channelWideMention: true, - ChannelType: model.CHANNEL_OPEN, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user: this is a message", }, "full message, public channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - ChannelType: model.CHANNEL_OPEN, + replyToThreadType: model.CommentsNotifyRoot, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user: this is a message", }, "full message, public channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - ChannelType: model.CHANNEL_OPEN, + replyToThreadType: model.CommentsNotifyAny, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user: this is a message", }, "full message, private channel, no mention": { Message: "this is a message", - ChannelType: model.CHANNEL_PRIVATE, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user: this is a message", }, "full message, private channel, mention": { Message: "this is a message", explicitMention: true, - ChannelType: model.CHANNEL_PRIVATE, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user: this is a message", }, "full message, private channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - ChannelType: model.CHANNEL_PRIVATE, + replyToThreadType: model.CommentsNotifyRoot, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user: this is a message", }, "full message, private channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - ChannelType: model.CHANNEL_PRIVATE, + replyToThreadType: model.CommentsNotifyAny, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user: this is a message", }, "full message, group message channel, no mention": { Message: "this is a message", - ChannelType: model.CHANNEL_GROUP, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user: this is a message", }, "full message, group message channel, mention": { Message: "this is a message", explicitMention: true, - ChannelType: model.CHANNEL_GROUP, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user: this is a message", }, "full message, group message channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - ChannelType: model.CHANNEL_GROUP, + replyToThreadType: model.CommentsNotifyRoot, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user: this is a message", }, "full message, group message channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - ChannelType: model.CHANNEL_GROUP, + replyToThreadType: model.CommentsNotifyAny, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user: this is a message", }, "full message, direct message channel, no mention": { Message: "this is a message", - ChannelType: model.CHANNEL_DIRECT, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "this is a message", }, "full message, direct message channel, mention": { Message: "this is a message", explicitMention: true, - ChannelType: model.CHANNEL_DIRECT, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "this is a message", }, "full message, direct message channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - ChannelType: model.CHANNEL_DIRECT, + replyToThreadType: model.CommentsNotifyRoot, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "this is a message", }, "full message, direct message channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - ChannelType: model.CHANNEL_DIRECT, + replyToThreadType: model.CommentsNotifyAny, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "this is a message", }, "generic message with channel, public channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user posted a message.", }, "generic message with channel, public channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user mentioned you.", }, "generic message with channel, public channel, channel wide mention": { Message: "this is a message", channelWideMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user notified the channel.", }, "generic message, public channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + replyToThreadType: model.CommentsNotifyRoot, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user commented on your post.", }, "generic message, public channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + replyToThreadType: model.CommentsNotifyAny, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user commented on a thread you participated in.", }, "generic message with channel, private channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user posted a message.", }, "generic message with channel, private channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user mentioned you.", }, "generic message with channel, private channel, channel wide mention": { Message: "this is a message", channelWideMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user notified the channel.", }, "generic message, public private, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + replyToThreadType: model.CommentsNotifyRoot, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user commented on your post.", }, "generic message, public private, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + replyToThreadType: model.CommentsNotifyAny, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user commented on a thread you participated in.", }, "generic message with channel, group message channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user posted a message.", }, "generic message with channel, group message channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user mentioned you.", }, "generic message with channel, group message channel, channel wide mention": { Message: "this is a message", channelWideMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user notified the channel.", }, "generic message, group message channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + replyToThreadType: model.CommentsNotifyRoot, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user commented on your post.", }, "generic message, group message channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + replyToThreadType: model.CommentsNotifyAny, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user commented on a thread you participated in.", }, "generic message with channel, direct message channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message with channel, direct message channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message with channel, direct message channel, channel wide mention": { Message: "this is a message", channelWideMention: true, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message, direct message channel, commented on post": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ROOT, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + replyToThreadType: model.CommentsNotifyRoot, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message, direct message channel, commented on thread": { Message: "this is a message", - replyToThreadType: model.COMMENTS_NOTIFY_ANY, - PushNotificationContents: model.GENERIC_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + replyToThreadType: model.CommentsNotifyAny, + PushNotificationContents: model.GenericNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message without channel, public channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user posted a message.", }, "generic message without channel, public channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user mentioned you.", }, "generic message without channel, private channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user posted a message.", }, "generic message without channel, private channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_PRIVATE, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user mentioned you.", }, "generic message without channel, group message channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user posted a message.", }, "generic message without channel, group message channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_GROUP, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user mentioned you.", }, "generic message without channel, direct message channel, no mention": { Message: "this is a message", - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "generic message without channel, direct message channel, mention": { Message: "this is a message", explicitMention: true, - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_DIRECT, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "sent you a message.", }, "only files, public channel": { HasFiles: true, - ChannelType: model.CHANNEL_OPEN, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user attached a file.", }, "only files, private channel": { HasFiles: true, - ChannelType: model.CHANNEL_PRIVATE, + ChannelType: model.ChannelTypePrivate, ExpectedMessage: "user attached a file.", }, "only files, group message channel": { HasFiles: true, - ChannelType: model.CHANNEL_GROUP, + ChannelType: model.ChannelTypeGroup, ExpectedMessage: "user attached a file.", }, "only files, direct message channel": { HasFiles: true, - ChannelType: model.CHANNEL_DIRECT, + ChannelType: model.ChannelTypeDirect, ExpectedMessage: "attached a file.", }, "only files without channel, public channel": { HasFiles: true, - PushNotificationContents: model.GENERIC_NO_CHANNEL_NOTIFICATION, - ChannelType: model.CHANNEL_OPEN, + PushNotificationContents: model.GenericNoChannelNotification, + ChannelType: model.ChannelTypeOpen, ExpectedMessage: "user attached a file.", }, } { @@ -898,7 +898,7 @@ func TestGetPushNotificationMessage(t *testing.T) { pushNotificationContents := tc.PushNotificationContents if pushNotificationContents == "" { - pushNotificationContents = model.FULL_NOTIFICATION + pushNotificationContents = model.FullNotification } th.App.UpdateConfig(func(cfg *model.Config) { @@ -971,7 +971,7 @@ func TestBuildPushNotificationMessageMentions(t *testing.T) { } { t.Run(name, func(t *testing.T) { receiver.NotifyProps["push"] = tc.pushNotifyProps - msg, err := th.App.BuildPushNotificationMessage(model.FULL_NOTIFICATION, post, receiver, channel1, channel1.Name, sender.Username, tc.explicitMention, tc.channelWideMention, tc.replyToThreadType) + msg, err := th.App.BuildPushNotificationMessage(model.FullNotification, post, receiver, channel1, channel1.Name, sender.Username, tc.explicitMention, tc.channelWideMention, tc.replyToThreadType) require.Nil(t, err) assert.Equal(t, tc.expectedBadge, msg.Badge) }) @@ -1151,7 +1151,7 @@ func TestClearPushNotificationSync(t *testing.T) { // We verify that 1 request has been sent, and also check the message contents. require.Equal(t, 1, handler.numReqs()) assert.Equal(t, "channel1", handler.notifications()[0].ChannelId) - assert.Equal(t, model.PUSH_TYPE_CLEAR, handler.notifications()[0].Type) + assert.Equal(t, model.PushTypeClear, handler.notifications()[0].Type) } func TestUpdateMobileAppBadgeSync(t *testing.T) { @@ -1206,9 +1206,9 @@ func TestUpdateMobileAppBadgeSync(t *testing.T) { // We verify that 2 requests have been sent, and also check the message contents. require.Equal(t, 2, handler.numReqs()) assert.Equal(t, 1, handler.notifications()[0].ContentAvailable) - assert.Equal(t, model.PUSH_TYPE_UPDATE_BADGE, handler.notifications()[0].Type) + assert.Equal(t, model.PushTypeUpdateBadge, handler.notifications()[0].Type) assert.Equal(t, 1, handler.notifications()[1].ContentAvailable) - assert.Equal(t, model.PUSH_TYPE_UPDATE_BADGE, handler.notifications()[1].Type) + assert.Equal(t, model.PushTypeUpdateBadge, handler.notifications()[1].Type) } func TestSendAckToPushProxy(t *testing.T) { @@ -1241,7 +1241,7 @@ func TestSendAckToPushProxy(t *testing.T) { ack := &model.PushNotificationAck{ Id: "testid", - NotificationType: model.PUSH_TYPE_MESSAGE, + NotificationType: model.PushTypeMessage, } err := th.App.SendAckToPushProxy(ack) require.NoError(t, err) @@ -1302,7 +1302,7 @@ func TestAllPushNotifications(t *testing.T) { defer pushServer.Close() th.App.UpdateConfig(func(cfg *model.Config) { - *cfg.EmailSettings.PushNotificationContents = model.GENERIC_NOTIFICATION + *cfg.EmailSettings.PushNotificationContents = model.GenericNotification *cfg.EmailSettings.PushNotificationServer = pushServer.URL }) @@ -1323,7 +1323,7 @@ func TestAllPushNotifications(t *testing.T) { Sender: &user, } // testing all 3 notification types. - th.App.sendPushNotification(notification, &user, true, false, model.COMMENTS_NOTIFY_ANY) + th.App.sendPushNotification(notification, &user, true, false, model.CommentsNotifyAny) }(*data.user) case 1: go func(id string) { @@ -1346,14 +1346,14 @@ func TestAllPushNotifications(t *testing.T) { var numClears, numMessages, numUpdateBadges int for _, n := range handler.notifications() { switch n.Type { - case model.PUSH_TYPE_CLEAR: + case model.PushTypeClear: numClears++ assert.Equal(t, th.BasicChannel.Id, n.ChannelId) - case model.PUSH_TYPE_MESSAGE: + case model.PushTypeMessage: numMessages++ assert.Equal(t, th.BasicChannel.Id, n.ChannelId) assert.Contains(t, n.Message, "mentioned you") - case model.PUSH_TYPE_UPDATE_BADGE: + case model.PushTypeUpdateBadge: numUpdateBadges++ assert.Equal(t, "none", n.Sound) assert.Equal(t, 1, n.ContentAvailable) @@ -1398,7 +1398,7 @@ func TestPushNotificationRace(t *testing.T) { }, Sender: &model.User{}, } - app.sendPushNotification(notification, &model.User{}, true, false, model.COMMENTS_NOTIFY_ANY) + app.sendPushNotification(notification, &model.User{}, true, false, model.CommentsNotifyAny) }) } @@ -1512,7 +1512,7 @@ func BenchmarkPushNotificationThroughput(b *testing.B) { ch := &model.Channel{ Id: model.NewId(), CreateAt: model.GetMillis(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "testch", } @@ -1545,7 +1545,7 @@ func BenchmarkPushNotificationThroughput(b *testing.B) { }, Sender: &user, } - th.App.sendPushNotification(notification, &user, true, false, model.COMMENTS_NOTIFY_ANY) + th.App.sendPushNotification(notification, &user, true, false, model.CommentsNotifyAny) }(*data.user) case 1: go func(id string) { diff --git a/app/notification_test.go b/app/notification_test.go index 2262eab4ed..f3857a3a63 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -26,8 +26,8 @@ func TestSendNotifications(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@" + th.BasicUser2.Username, - Type: model.POST_ADD_TO_CHANNEL, - Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"}, + Type: model.PostTypeAddToChannel, + Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr) @@ -103,14 +103,14 @@ func TestSendNotifications(t *testing.T) { require.False(t, utils.StringInSlice(user.Id, mentions)) } - th.BasicUser.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY + th.BasicUser.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny th.BasicUser, appErr = th.App.UpdateUser(th.BasicUser, false) require.Nil(t, appErr) t.Run("user wants notifications on all comments", func(t *testing.T) { testUserNotNotified(t, th.BasicUser) }) - th.BasicUser.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT + th.BasicUser.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyRoot th.BasicUser, appErr = th.App.UpdateUser(th.BasicUser, false) require.Nil(t, appErr) t.Run("user wants notifications on root comment", func(t *testing.T) { @@ -135,8 +135,8 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@channel", - Type: model.POST_ADD_TO_CHANNEL, - Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"}, + Type: model.PostTypeAddToChannel, + Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr1) @@ -155,8 +155,8 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@channel", - Type: model.POST_ADD_TO_CHANNEL, - Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"}, + Type: model.PostTypeAddToChannel, + Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"}, }, true) require.Nil(t, appErr1) @@ -249,7 +249,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) { t.Run("should not return results for a system message", func(t *testing.T) { post := &model.Post{ - Type: model.POST_ADD_REMOVE, + Type: model.PostTypeAddRemove, } potentialMentions := []string{user2.Username, user3.Username} @@ -263,7 +263,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) { t.Run("should not return results for a direct message", func(t *testing.T) { post := &model.Post{} directChannel := &model.Channel{ - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } potentialMentions := []string{user2.Username, user3.Username} @@ -277,7 +277,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) { t.Run("should not return results for a group message", func(t *testing.T) { post := &model.Post{} groupChannel := &model.Channel{ - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } potentialMentions := []string{user2.Username, user3.Username} @@ -1016,13 +1016,13 @@ func TestAllowChannelMentions(t *testing.T) { }) t.Run("should return false for a channel header post", func(t *testing.T) { - headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_HEADER_CHANGE} + headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange} allowChannelMentions := th.App.allowChannelMentions(headerChangePost, 5) assert.False(t, allowChannelMentions) }) t.Run("should return false for a channel purpose post", func(t *testing.T) { - purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_PURPOSE_CHANGE} + purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange} allowChannelMentions := th.App.allowChannelMentions(purposeChangePost, 5) assert.False(t, allowChannelMentions) }) @@ -1033,10 +1033,10 @@ func TestAllowChannelMentions(t *testing.T) { }) t.Run("should return false for a post where the post user does not have USE_CHANNEL_MENTIONS permission", func(t *testing.T) { - defer th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - defer th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + defer th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + defer th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) allowChannelMentions := th.App.allowChannelMentions(post, 5) assert.False(t, allowChannelMentions) }) @@ -1061,24 +1061,24 @@ func TestAllowGroupMentions(t *testing.T) { }) t.Run("should return false for a channel header post", func(t *testing.T) { - headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_HEADER_CHANGE} + headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange} allowGroupMentions := th.App.allowGroupMentions(headerChangePost) assert.False(t, allowGroupMentions) }) t.Run("should return false for a channel purpose post", func(t *testing.T) { - purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_PURPOSE_CHANGE} + purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange} allowGroupMentions := th.App.allowGroupMentions(purposeChangePost) assert.False(t, allowGroupMentions) }) t.Run("should return false for a post where the post user does not have USE_GROUP_MENTIONS permission", func(t *testing.T) { defer func() { - th.AddPermissionToRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionUseGroupMentions.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionUseGroupMentions.Id, model.ChannelAdminRoleId) }() - th.RemovePermissionFromRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelUserRoleId) + th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelAdminRoleId) allowGroupMentions := th.App.allowGroupMentions(post) assert.False(t, allowGroupMentions) }) @@ -1100,7 +1100,7 @@ func TestGetMentionKeywords(t *testing.T) { channelMemberNotifyPropsMap1Off := map[string]model.StringMap{ user1.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } @@ -1130,7 +1130,7 @@ func TestGetMentionKeywords(t *testing.T) { channelMemberNotifyPropsMap2Off := map[string]model.StringMap{ user2.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } @@ -1155,7 +1155,7 @@ func TestGetMentionKeywords(t *testing.T) { // Channel-wide mentions are not ignored on channel level channelMemberNotifyPropsMap3Off := map[string]model.StringMap{ user3.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } profiles = map[string]*model.User{user3.Id: user3} @@ -1171,7 +1171,7 @@ func TestGetMentionKeywords(t *testing.T) { // Channel member notify props is set to default channelMemberNotifyPropsMapDefault := map[string]model.StringMap{ user3.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_DEFAULT, + "ignore_channel_mentions": model.IgnoreChannelMentionsDefault, }, } profiles = map[string]*model.User{user3.Id: user3} @@ -1199,7 +1199,7 @@ func TestGetMentionKeywords(t *testing.T) { // Channel-wide mentions are ignored channel level channelMemberNotifyPropsMap3On := map[string]model.StringMap{ user3.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_ON, + "ignore_channel_mentions": model.IgnoreChannelMentionsOn, }, } mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap3On) @@ -1220,7 +1220,7 @@ func TestGetMentionKeywords(t *testing.T) { // Channel-wide mentions are not ignored on channel level channelMemberNotifyPropsMap4Off := map[string]model.StringMap{ user4.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } @@ -1249,7 +1249,7 @@ func TestGetMentionKeywords(t *testing.T) { // Channel-wide mentions are ignored on channel level channelMemberNotifyPropsMap4On := map[string]model.StringMap{ user4.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_ON, + "ignore_channel_mentions": model.IgnoreChannelMentionsOn, }, } mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap4On) @@ -1295,16 +1295,16 @@ func TestGetMentionKeywords(t *testing.T) { // Channel-wide mentions are not ignored on channel level for all users channelMemberNotifyPropsMap5Off := map[string]model.StringMap{ user1.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, user2.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, user3.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, user4.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap5Off) @@ -1393,7 +1393,7 @@ func TestGetMentionKeywords(t *testing.T) { channelMemberNotifyPropsMapEmptyOff := map[string]model.StringMap{ userNoMentionKeys.Id: { - "ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF, + "ignore_channel_mentions": model.IgnoreChannelMentionsOff, }, } @@ -1424,7 +1424,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.MENTION_KEYS_NOTIFY_PROP: "apple,BANANA,OrAnGe", + model.MentionKeysNotifyProp: "apple,BANANA,OrAnGe", }, } channelNotifyProps := map[string]string{} @@ -1442,7 +1442,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.MENTION_KEYS_NOTIFY_PROP: ",,", + model.MentionKeysNotifyProp: ",,", }, } channelNotifyProps := map[string]string{} @@ -1460,7 +1460,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) { FirstName: "William", LastName: "Robert", NotifyProps: map[string]string{ - model.FIRST_NAME_NOTIFY_PROP: "true", + model.FirstNameNotifyProp: "true", }, } channelNotifyProps := map[string]string{} @@ -1480,7 +1480,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) { FirstName: "", LastName: "Robert", NotifyProps: map[string]string{ - model.FIRST_NAME_NOTIFY_PROP: "true", + model.FirstNameNotifyProp: "true", }, } channelNotifyProps := map[string]string{} @@ -1498,7 +1498,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) { FirstName: "William", LastName: "Robert", NotifyProps: map[string]string{ - model.FIRST_NAME_NOTIFY_PROP: "false", + model.FirstNameNotifyProp: "false", }, } channelNotifyProps := map[string]string{} @@ -1516,12 +1516,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } channelNotifyProps := map[string]string{} status := &model.Status{ - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, } keywords := map[string][]string{} @@ -1537,12 +1537,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } channelNotifyProps := map[string]string{} status := &model.Status{ - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, } keywords := map[string][]string{} @@ -1558,12 +1558,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "false", + model.ChannelMentionsNotifyProp: "false", }, } channelNotifyProps := map[string]string{} status := &model.Status{ - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, } keywords := map[string][]string{} @@ -1579,14 +1579,14 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } channelNotifyProps := map[string]string{ - model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_ON, + model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn, } status := &model.Status{ - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, } keywords := map[string][]string{} @@ -1602,15 +1602,15 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } channelNotifyProps := map[string]string{ - model.MARK_UNREAD_NOTIFY_PROP: model.USER_NOTIFY_MENTION, - model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_DEFAULT, + model.MarkUnreadNotifyProp: model.UserNotifyMention, + model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsDefault, } status := &model.Status{ - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, } keywords := map[string][]string{} @@ -1626,12 +1626,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } channelNotifyProps := map[string]string{} status := &model.Status{ - Status: model.STATUS_AWAY, + Status: model.StatusAway, } keywords := map[string][]string{} @@ -1647,14 +1647,14 @@ func TestAddMentionKeywordsForUser(t *testing.T) { Id: model.NewId(), Username: "user1", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } user2 := &model.User{ Id: model.NewId(), Username: "user2", NotifyProps: map[string]string{ - model.CHANNEL_MENTIONS_NOTIFY_PROP: "true", + model.ChannelMentionsNotifyProp: "true", }, } @@ -1719,50 +1719,50 @@ func TestPostNotificationGetChannelName(t *testing.T) { expected string }{ "regular channel": { - channel: &model.Channel{Type: model.CHANNEL_OPEN, Name: "channel", DisplayName: "My Channel"}, + channel: &model.Channel{Type: model.ChannelTypeOpen, Name: "channel", DisplayName: "My Channel"}, expected: "My Channel", }, "direct channel, unspecified": { - channel: &model.Channel{Type: model.CHANNEL_DIRECT}, + channel: &model.Channel{Type: model.ChannelTypeDirect}, expected: "@sender", }, "direct channel, username": { - channel: &model.Channel{Type: model.CHANNEL_DIRECT}, - nameFormat: model.SHOW_USERNAME, + channel: &model.Channel{Type: model.ChannelTypeDirect}, + nameFormat: model.ShowUsername, expected: "@sender", }, "direct channel, full name": { - channel: &model.Channel{Type: model.CHANNEL_DIRECT}, - nameFormat: model.SHOW_FULLNAME, + channel: &model.Channel{Type: model.ChannelTypeDirect}, + nameFormat: model.ShowFullName, expected: "Sender Sender", }, "direct channel, nickname": { - channel: &model.Channel{Type: model.CHANNEL_DIRECT}, - nameFormat: model.SHOW_NICKNAME_FULLNAME, + channel: &model.Channel{Type: model.ChannelTypeDirect}, + nameFormat: model.ShowNicknameFullName, expected: "Sender", }, "group channel, unspecified": { - channel: &model.Channel{Type: model.CHANNEL_GROUP}, + channel: &model.Channel{Type: model.ChannelTypeGroup}, expected: "other, sender", }, "group channel, username": { - channel: &model.Channel{Type: model.CHANNEL_GROUP}, - nameFormat: model.SHOW_USERNAME, + channel: &model.Channel{Type: model.ChannelTypeGroup}, + nameFormat: model.ShowUsername, expected: "other, sender", }, "group channel, full name": { - channel: &model.Channel{Type: model.CHANNEL_GROUP}, - nameFormat: model.SHOW_FULLNAME, + channel: &model.Channel{Type: model.ChannelTypeGroup}, + nameFormat: model.ShowFullName, expected: "Other Other, Sender Sender", }, "group channel, nickname": { - channel: &model.Channel{Type: model.CHANNEL_GROUP}, - nameFormat: model.SHOW_NICKNAME_FULLNAME, + channel: &model.Channel{Type: model.ChannelTypeGroup}, + nameFormat: model.ShowNicknameFullName, expected: "Other, Sender", }, "group channel, not excluding current user": { - channel: &model.Channel{Type: model.CHANNEL_GROUP}, - nameFormat: model.SHOW_NICKNAME_FULLNAME, + channel: &model.Channel{Type: model.ChannelTypeGroup}, + nameFormat: model.ShowNicknameFullName, expected: "Other, Sender", recipientId: "", }, @@ -1788,7 +1788,7 @@ func TestPostNotificationGetSenderName(t *testing.T) { th := Setup(t) defer th.TearDown() - defaultChannel := &model.Channel{Type: model.CHANNEL_OPEN} + defaultChannel := &model.Channel{Type: model.ChannelTypeOpen} defaultPost := &model.Post{Props: model.StringInterface{}} sender := &model.User{Id: model.NewId(), Username: "sender", FirstName: "Sender", LastName: "Sender", Nickname: "Sender"} @@ -1810,19 +1810,19 @@ func TestPostNotificationGetSenderName(t *testing.T) { expected: "@" + sender.Username, }, "name format username": { - nameFormat: model.SHOW_USERNAME, + nameFormat: model.ShowUsername, expected: "@" + sender.Username, }, "name format full name": { - nameFormat: model.SHOW_FULLNAME, + nameFormat: model.ShowFullName, expected: sender.FirstName + " " + sender.LastName, }, "name format nickname": { - nameFormat: model.SHOW_NICKNAME_FULLNAME, + nameFormat: model.ShowNicknameFullName, expected: sender.Nickname, }, "system message": { - post: &model.Post{Type: model.POST_SYSTEM_MESSAGE_PREFIX + "custom"}, + post: &model.Post{Type: model.PostSystemMessagePrefix + "custom"}, expected: i18n.T("system.message.name"), }, "overridden username": { @@ -1831,7 +1831,7 @@ func TestPostNotificationGetSenderName(t *testing.T) { expected: overriddenPost.GetProp("override_username").(string), }, "overridden username, direct channel": { - channel: &model.Channel{Type: model.CHANNEL_DIRECT}, + channel: &model.Channel{Type: model.ChannelTypeDirect}, post: overriddenPost, allowOverrides: true, expected: "@" + sender.Username, @@ -2294,19 +2294,19 @@ func TestGetNotificationNameFormat(t *testing.T) { t.Run("show full name on", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = true - *cfg.TeamSettings.TeammateNameDisplay = model.SHOW_FULLNAME + *cfg.TeamSettings.TeammateNameDisplay = model.ShowFullName }) - assert.Equal(t, model.SHOW_FULLNAME, th.App.GetNotificationNameFormat(th.BasicUser)) + assert.Equal(t, model.ShowFullName, th.App.GetNotificationNameFormat(th.BasicUser)) }) t.Run("show full name off", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false - *cfg.TeamSettings.TeammateNameDisplay = model.SHOW_FULLNAME + *cfg.TeamSettings.TeammateNameDisplay = model.ShowFullName }) - assert.Equal(t, model.SHOW_USERNAME, th.App.GetNotificationNameFormat(th.BasicUser)) + assert.Equal(t, model.ShowUsername, th.App.GetNotificationNameFormat(th.BasicUser)) }) } @@ -2320,8 +2320,8 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOffline(user.Id, true) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } assert.True(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) @@ -2333,8 +2333,8 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOnline(user.Id, true) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) @@ -2346,8 +2346,8 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOffline(user.Id, true) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: "false", - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: "false", + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) @@ -2359,8 +2359,8 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOffline(user.Id, true) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_MENTION, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadMention, } assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) @@ -2372,11 +2372,11 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOffline(user.Id, true) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER})) + assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) t.Run("should return false in case the status is STATUS_OUT_OF_OFFICE", func(t *testing.T) { @@ -2385,11 +2385,11 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusOutOfOffice(user.Id) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER})) + assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) t.Run("should return false in case the status is STATUS_ONLINE", func(t *testing.T) { @@ -2398,11 +2398,11 @@ func TestUserAllowsEmail(t *testing.T) { th.App.SetStatusDoNotDisturb(user.Id) channelMemberNotificationProps := model.StringMap{ - model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT, - model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL, + model.EmailNotifyProp: model.ChannelNotifyDefault, + model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER})) + assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) } @@ -2483,13 +2483,13 @@ func TestInsertGroupMentions(t *testing.T) { mentions := &ExplicitMentions{} emptyProfileMap := make(map[string]*model.User) - groupChannel := &model.Channel{Type: model.CHANNEL_GROUP} + groupChannel := &model.Channel{Type: model.ChannelTypeGroup} usersMentioned, _ := th.App.insertGroupMentions(group, groupChannel, emptyProfileMap, mentions) // Ensure group channel with no group members mentioned always returns true require.Equal(t, usersMentioned, true) require.Equal(t, len(mentions.Mentions), 0) - directChannel := &model.Channel{Type: model.CHANNEL_DIRECT} + directChannel := &model.Channel{Type: model.ChannelTypeDirect} usersMentioned, _ = th.App.insertGroupMentions(group, directChannel, emptyProfileMap, mentions) // Ensure direct channel with no group members mentioned always returns true require.Equal(t, usersMentioned, true) @@ -2624,15 +2624,15 @@ func TestReplyPostNotificationsWithCRT(t *testing.T) { // Enable "Trigger notifications on messages in // reply threads that I start or participate in" // for the second user - oldValue := th.BasicUser2.NotifyProps[model.COMMENTS_NOTIFY_PROP] + oldValue := th.BasicUser2.NotifyProps[model.CommentsNotifyProp] newNotifyProps := th.BasicUser2.NotifyProps - newNotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY + newNotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny u2, appErr := th.App.PatchUser(th.BasicUser2.Id, &model.UserPatch{NotifyProps: newNotifyProps}, false) require.Nil(t, appErr) - require.Equal(t, model.COMMENTS_NOTIFY_ANY, u2.NotifyProps[model.COMMENTS_NOTIFY_PROP]) + require.Equal(t, model.CommentsNotifyAny, u2.NotifyProps[model.CommentsNotifyProp]) defer func() { newNotifyProps := th.BasicUser2.NotifyProps - newNotifyProps[model.COMMENTS_NOTIFY_PROP] = oldValue + newNotifyProps[model.CommentsNotifyProp] = oldValue _, nAppErr := th.App.PatchUser(th.BasicUser2.Id, &model.UserPatch{NotifyProps: newNotifyProps}, false) require.Nil(t, nAppErr) }() @@ -2642,7 +2642,7 @@ func TestReplyPostNotificationsWithCRT(t *testing.T) { defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) rootPost := &model.Post{ diff --git a/app/oauth.go b/app/oauth.go index 86f86ffc40..87832ab107 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -28,8 +28,8 @@ import ( ) const ( - OauthCookieMaxAgeSeconds = 30 * 60 // 30 minutes - CookieOauth = "MMOAUTH" + OAuthCookieMaxAgeSeconds = 30 * 60 // 30 minutes + CookieOAuth = "MMOAUTH" OpenIDScope = "openid" ) @@ -76,9 +76,9 @@ func (a *App) GetOAuthApp(appID string) (*model.OAuthApp, *model.AppError) { return oauthApp, nil } -func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { +func (a *App) UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { if !*a.Config().ServiceSettings.EnableOAuthServiceProvider { - return nil, model.NewAppError("UpdateOauthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) + return nil, model.NewAppError("UpdateOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } updatedApp.Id = oldApp.Id @@ -94,9 +94,9 @@ func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthAp case errors.As(err, &appErr): return nil, appErr case errors.As(err, &invErr): - return nil, model.NewAppError("UpdateOauthApp", "app.oauth.update_app.find.app_error", nil, invErr.Error(), http.StatusBadRequest) + return nil, model.NewAppError("UpdateOAuthApp", "app.oauth.update_app.find.app_error", nil, invErr.Error(), http.StatusBadRequest) default: - return nil, model.NewAppError("UpdateOauthApp", "app.oauth.update_app.updating.app_error", nil, err.Error(), http.StatusInternalServerError) + return nil, model.NewAppError("UpdateOAuthApp", "app.oauth.update_app.updating.app_error", nil, err.Error(), http.StatusInternalServerError) } } @@ -178,7 +178,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author } if authRequest.Scope == "" { - authRequest.Scope = model.DEFAULT_SCOPE + authRequest.Scope = model.DefaultScope } oauthApp, nErr := a.Srv().Store.OAuth().GetApp(authRequest.ClientId) @@ -199,9 +199,9 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author var redirectURI string var err *model.AppError switch authRequest.ResponseType { - case model.AUTHCODE_RESPONSE_TYPE: + case model.AuthCodeResponseType: redirectURI, err = a.GetOAuthCodeRedirect(userID, authRequest) - case model.IMPLICIT_RESPONSE_TYPE: + case model.ImplicitResponseType: redirectURI, err = a.GetOAuthImplicitRedirect(userID, authRequest) default: return authRequest.RedirectUri + "?error=unsupported_response_type&state=" + authRequest.State, nil @@ -215,7 +215,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author // This saves the OAuth2 app as authorized authorizedApp := model.Preference{ UserId: userID, - Category: model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, + Category: model.PreferenceCategoryAuthorizedOAuthApp, Name: authRequest.ClientId, Value: authRequest.Scope, } @@ -274,7 +274,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c var accessData *model.AccessData var accessRsp *model.AccessResponse var user *model.User - if grantType == model.ACCESS_TOKEN_GRANT_TYPE { + if grantType == model.AccessTokenGrantType { var authData *model.AuthData authData, nErr = a.Srv().Store.OAuth().GetAuthData(code) if nErr != nil { @@ -314,7 +314,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c // Return the same token and no need to create a new session accessRsp = &model.AccessResponse{ AccessToken: accessData.Token, - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, RefreshToken: accessData.RefreshToken, ExpiresIn: int32((accessData.ExpiresAt - model.GetMillis()) / 1000), } @@ -335,7 +335,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c accessRsp = &model.AccessResponse{ AccessToken: session.Token, - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, RefreshToken: accessData.RefreshToken, ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), } @@ -371,9 +371,9 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true} session.GenerateCSRF() a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays) - session.AddProp(model.SESSION_PROP_PLATFORM, appName) - session.AddProp(model.SESSION_PROP_OS, "OAuth2") - session.AddProp(model.SESSION_PROP_BROWSER, "OAuth2") + session.AddProp(model.SessionPropPlatform, appName) + session.AddProp(model.SessionPropOs, "OAuth2") + session.AddProp(model.SessionPropBrowser, "OAuth2") session, err := a.Srv().Store.Session().Save(session) if err != nil { @@ -406,7 +406,7 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData accessRsp := &model.AccessResponse{ AccessToken: session.Token, RefreshToken: accessData.RefreshToken, - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), } @@ -424,7 +424,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv stateProps["redirect_to"] = redirectTo } - stateProps[model.USER_AUTH_SERVICE_IS_MOBILE] = strconv.FormatBool(isMobile) + stateProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile) authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint) if err != nil { @@ -436,7 +436,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamID string) (string, *model.AppError) { stateProps := map[string]string{} - stateProps["action"] = model.OAUTH_ACTION_SIGNUP + stateProps["action"] = model.OAuthActionSignup if teamID != "" { stateProps["team_id"] = teamID } @@ -489,7 +489,7 @@ func (a *App) DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError { } // Deauthorize the app - if err := a.Srv().Store.Preference().Delete(userID, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appID); err != nil { + if err := a.Srv().Store.Preference().Delete(userID, model.PreferenceCategoryAuthorizedOAuthApp, appID); err != nil { return model.NewAppError("DeauthorizeOAuthAppForUser", "app.preference.delete.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -539,29 +539,29 @@ func (a *App) CompleteOAuth(c *request.Context, service string, body io.ReadClos action := props["action"] switch action { - case model.OAUTH_ACTION_SIGNUP: + case model.OAuthActionSignup: return a.CreateOAuthUser(c, service, body, teamID, tokenUser) - case model.OAUTH_ACTION_LOGIN: + case model.OAuthActionLogin: return a.LoginByOAuth(c, service, body, teamID, tokenUser) - case model.OAUTH_ACTION_EMAIL_TO_SSO: + case model.OAuthActionEmailToSSO: return a.CompleteSwitchWithOAuth(service, body, props["email"], tokenUser) - case model.OAUTH_ACTION_SSO_TO_EMAIL: + case model.OAuthActionSSOToEmail: return a.LoginByOAuth(c, service, body, teamID, tokenUser) default: return a.LoginByOAuth(c, service, body, teamID, tokenUser) } } -func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model.AppError) { +func (a *App) getSSOProvider(service string) (einterfaces.OAuthProvider, *model.AppError) { sso := a.Config().GetSSOService(service) if sso == nil || !*sso.Enable { return nil, model.NewAppError("getSSOProvider", "api.user.authorize_oauth_user.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented) } providerType := service if strings.Contains(*sso.Scope, OpenIDScope) { - providerType = model.SERVICE_OPENID + providerType = model.ServiceOpenid } - provider := einterfaces.GetOauthProvider(providerType) + provider := einterfaces.GetOAuthProvider(providerType) if provider == nil { return nil, model.NewAppError("getSSOProvider", "api.user.login_by_oauth.not_available.app_error", map[string]interface{}{"Service": strings.Title(service)}, "", http.StatusNotImplemented) @@ -672,7 +672,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email } func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) { - token := model.NewToken(model.TOKEN_TYPE_OAUTH, extra) + token := model.NewToken(model.TokenTypeOAuth, extra) if err := a.Srv().Store.Token().Save(token); err != nil { var appErr *model.AppError @@ -693,7 +693,7 @@ func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) { return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, err.Error(), http.StatusBadRequest) } - if mToken.Type != model.TOKEN_TYPE_OAUTH { + if mToken.Type != model.TokenTypeOAuth { return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, "", http.StatusBadRequest) } @@ -719,12 +719,12 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi cookieValue := model.NewId() subpath, _ := utils.GetSubpathFromConfig(a.Config()) - expiresAt := time.Unix(model.GetMillis()/1000+int64(OauthCookieMaxAgeSeconds), 0) + expiresAt := time.Unix(model.GetMillis()/1000+int64(OAuthCookieMaxAgeSeconds), 0) oauthCookie := &http.Cookie{ - Name: CookieOauth, + Name: CookieOAuth, Value: cookieValue, Path: subpath, - MaxAge: OauthCookieMaxAgeSeconds, + MaxAge: OAuthCookieMaxAgeSeconds, Expires: expiresAt, HttpOnly: true, Secure: secure, @@ -791,11 +791,11 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service stateEmail := stateProps["email"] stateAction := stateProps["action"] - if stateAction == model.OAUTH_ACTION_EMAIL_TO_SSO && stateEmail == "" { + if stateAction == model.OAuthActionEmailToSSO && stateEmail == "" { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest) } - cookie, cookieErr := r.Cookie(CookieOauth) + cookie, cookieErr := r.Cookie(CookieOAuth) if cookieErr != nil { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest) } @@ -813,7 +813,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service subpath, _ := utils.GetSubpathFromConfig(a.Config()) httpCookie := &http.Cookie{ - Name: CookieOauth, + Name: CookieOAuth, Value: "", Path: subpath, MaxAge: -1, @@ -828,7 +828,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service p.Set("client_id", *sso.Id) p.Set("client_secret", *sso.Secret) p.Set("code", code) - p.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) + p.Set("grant_type", model.AccessTokenGrantType) p.Set("redirect_uri", redirectUri) req, requestErr := http.NewRequest("POST", *sso.TokenEndpoint, strings.NewReader(p.Encode())) @@ -852,7 +852,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_response.app_error", nil, fmt.Sprintf("response_body=%s, status_code=%d", buf.String(), resp.StatusCode), http.StatusInternalServerError) } - if strings.ToLower(ar.TokenType) != model.ACCESS_TOKEN_TYPE { + if strings.ToLower(ar.TokenType) != model.AccessTokenType { return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_token.app_error", nil, "token_type="+ar.TokenType+", response_body="+buf.String(), http.StatusInternalServerError) } @@ -892,7 +892,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString)) - if service == model.SERVICE_GITLAB && resp.StatusCode == http.StatusForbidden && strings.Contains(bodyString, "Terms of Service") { + if service == model.ServiceGitlab && resp.StatusCode == http.StatusForbidden && strings.Contains(bodyString, "Terms of Service") { // Return a nicer error when the user hasn't accepted GitLab's terms of service return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "oauth.gitlab.tos.error", nil, "", http.StatusBadRequest) } @@ -919,11 +919,11 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, } stateProps := map[string]string{} - stateProps["action"] = model.OAUTH_ACTION_EMAIL_TO_SSO + stateProps["action"] = model.OAuthActionEmailToSSO stateProps["email"] = email - if service == model.USER_AUTH_SERVICE_SAML { - return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAUTH_ACTION_EMAIL_TO_SSO + "&email=" + utils.URLEncode(email), nil + if service == model.UserAuthServiceSaml { + return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAuthActionEmailToSSO + "&email=" + utils.URLEncode(email), nil } authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, "") diff --git a/app/oauth_test.go b/app/oauth_test.go index 2fbfbcaaba..9db24d0b0c 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -35,7 +35,7 @@ func TestGetOAuthAccessTokenForImplicitFlow(t *testing.T) { require.Nil(t, err) authRequest := &model.AuthorizeRequest{ - ResponseType: model.IMPLICIT_RESPONSE_TYPE, + ResponseType: model.ImplicitResponseType, ClientId: oapp.Id, RedirectUri: oapp.CallbackUrls[0], Scope: "", @@ -74,7 +74,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) { session.CreateAt = model.GetMillis() session.UserId = model.NewId() session.Token = model.NewId() - session.Roles = model.SYSTEM_USER_ROLE_ID + session.Roles = model.SystemUserRoleId th.App.SetSessionExpireInDays(session, 1) var err *model.AppError @@ -105,7 +105,7 @@ func TestOAuthDeleteApp(t *testing.T) { session.CreateAt = model.GetMillis() session.UserId = model.NewId() session.Token = model.NewId() - session.Roles = model.SYSTEM_USER_ROLE_ID + session.Roles = model.SystemUserRoleId session.IsOAuth = true th.App.srv.userService.SetSessionExpireInDays(session, 1) @@ -167,7 +167,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { if cookie != "" { request.AddCookie(&http.Cookie{ - Name: CookieOauth, + Name: CookieOAuth, Value: cookie, }) } @@ -179,7 +179,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { th := setup(t, false, true, true, "") defer th.TearDown() - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", "", "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", "", "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id) }) @@ -190,7 +190,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := "!" - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -203,7 +203,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { "token": model.NewId(), }))) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id) assert.NotEqual(t, "", err.DetailedError) @@ -218,7 +218,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := makeState(token) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id) assert.Equal(t, "", err.DetailedError) @@ -229,7 +229,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { defer th.TearDown() email := "" - action := model.OAUTH_ACTION_EMAIL_TO_SSO + action := model.OAuthActionEmailToSSO cookie := model.NewId() token, err := th.App.CreateOAuthStateToken(generateOAuthStateTokenExtra(email, action, cookie)) @@ -241,7 +241,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { "token": token.Token, }))) - _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -254,7 +254,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest("") state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -271,7 +271,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(token) - _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err = th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id) }) @@ -284,7 +284,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.token_failed.app_error", err.Id) }) @@ -302,7 +302,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id) assert.Contains(t, err.DetailedError, "status_code=418") @@ -321,7 +321,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id) assert.Contains(t, err.DetailedError, "response_body=invalid") @@ -343,7 +343,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.bad_token.app_error", err.Id) }) @@ -352,7 +352,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(&model.AccessResponse{ AccessToken: "", - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, }) })) defer server.Close() @@ -364,7 +364,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.missing.app_error", err.Id) }) @@ -373,7 +373,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(&model.AccessResponse{ AccessToken: model.NewId(), - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, }) })) defer server.Close() @@ -385,7 +385,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.service.app_error", err.Id) }) @@ -397,7 +397,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { t.Log("hit token") json.NewEncoder(w).Encode(&model.AccessResponse{ AccessToken: model.NewId(), - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, }) case "/user": t.Log("hit user") @@ -413,7 +413,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.response.app_error", err.Id) }) @@ -425,7 +425,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { t.Log("hit token") json.NewEncoder(w).Encode(&model.AccessResponse{ AccessToken: model.NewId(), - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, }) case "/user": t.Log("hit user") @@ -442,7 +442,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { request := makeRequest(cookie) state := makeState(makeToken(th, cookie)) - _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "") + _, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "") require.NotNil(t, err) assert.Equal(t, "oauth.gitlab.tos.error", err.Id) }) @@ -466,7 +466,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { case "/token": json.NewEncoder(w).Encode(&model.AccessResponse{ AccessToken: model.NewId(), - TokenType: model.ACCESS_TOKEN_TYPE, + TokenType: model.AccessTokenType, }) case "/user": w.WriteHeader(http.StatusOK) @@ -492,7 +492,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) recorder := httptest.ResponseRecorder{} - body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.SERVICE_GITLAB, "", state, "") + body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "") require.NotNil(t, body) bodyBytes, bodyErr := ioutil.ReadAll(body) @@ -519,7 +519,7 @@ func TestGetAuthorizationCode(t *testing.T) { *cfg.GitLabSettings.Enable = false }) - _, err := th.App.GetAuthorizationCode(nil, nil, model.SERVICE_GITLAB, map[string]string{}, "") + _, err := th.App.GetAuthorizationCode(nil, nil, model.ServiceGitlab, map[string]string{}, "") require.NotNil(t, err) assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id) @@ -556,7 +556,7 @@ func TestGetAuthorizationCode(t *testing.T) { } recorder := httptest.ResponseRecorder{} - url, err := th.App.GetAuthorizationCode(&recorder, request, model.SERVICE_GITLAB, stateProps, "") + url, err := th.App.GetAuthorizationCode(&recorder, request, model.ServiceGitlab, stateProps, "") require.Nil(t, err) assert.NotEmpty(t, url) diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 6a740897ce..b534660d20 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -16161,7 +16161,29 @@ func (a *OpenTracingAppLayer) UpdateMobileAppBadge(userID string) { a.app.UpdateMobileAppBadge(userID) } -func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string, tokenUser *model.User) *model.AppError { +func (a *OpenTracingAppLayer) UpdateOAuthApp(oldApp *model.OAuthApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { + origCtx := a.ctx + span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthApp") + + a.ctx = newCtx + a.app.Srv().Store.SetContext(newCtx) + defer func() { + a.app.Srv().Store.SetContext(origCtx) + a.ctx = origCtx + }() + + defer span.Finish() + resultVar0, resultVar1 := a.app.UpdateOAuthApp(oldApp, updatedApp) + + if resultVar1 != nil { + span.LogFields(spanlog.Error(resultVar1)) + ext.Error.Set(span, true) + } + + return resultVar0, resultVar1 +} + +func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthUserAttrs") @@ -16183,28 +16205,6 @@ func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *mod return resultVar0 } -func (a *OpenTracingAppLayer) UpdateOauthApp(oldApp *model.OAuthApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOauthApp") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateOauthApp(oldApp, updatedApp) - - if resultVar1 != nil { - span.LogFields(spanlog.Error(resultVar1)) - ext.Error.Set(span, true) - } - - return resultVar0, resultVar1 -} - func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(oldHook *model.OutgoingWebhook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOutgoingWebhook") diff --git a/app/permissions.go b/app/permissions.go index e9793af024..e261922275 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -56,7 +56,7 @@ func (a *App) ResetPermissionsSystem() *model.AppError { } // Remove the "System" table entry that marks the advanced permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(model.AdvancedPermissionsMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 6f613a442d..ce8d3b444c 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -222,12 +222,12 @@ func (a *App) getWebhooksPermissionsSplitMigration() (permissionsMap, error) { func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionListPrivateTeams, PermissionJoinPrivateTeams}, Remove: []string{}, }, permissionTransformation{ - On: isRole(model.SYSTEM_USER_ROLE_ID), + On: isRole(model.SystemUserRoleId), Add: []string{PermissionListPublicTeams, PermissionJoinPublicTeams}, Remove: []string{}, }, @@ -246,7 +246,7 @@ func (a *App) removePermanentDeleteUserMigration() (permissionsMap, error) { func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionCreateBot, PermissionReadBots, PermissionReadOthersBots, PermissionManageBots, PermissionManageOthersBots}, Remove: []string{}, }, @@ -256,19 +256,19 @@ func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) { func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePrivateChannelProperties))), + On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionManagePrivateChannelProperties))), Add: []string{PermissionManagePrivateChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePrivateChannel))), + On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionDeletePrivateChannel))), Add: []string{PermissionDeletePrivateChannel}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePublicChannelProperties))), + On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionManagePublicChannelProperties))), Add: []string{PermissionManagePublicChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePublicChannel))), + On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionDeletePublicChannel))), Add: []string{PermissionDeletePublicChannel}, }, }, nil @@ -277,19 +277,19 @@ func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) { func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePrivateChannelProperties)), + On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionManagePrivateChannelProperties)), Remove: []string{PermissionManagePrivateChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePrivateChannel)), - Remove: []string{model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id}, + On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionDeletePrivateChannel)), + Remove: []string{model.PermissionDeletePrivateChannel.Id}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePublicChannelProperties)), + On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionManagePublicChannelProperties)), Remove: []string{PermissionManagePublicChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePublicChannel)), + On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionDeletePublicChannel)), Remove: []string{PermissionDeletePublicChannel}, }, }, nil @@ -298,11 +298,11 @@ func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) { func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_USER_ROLE_ID), + On: isRole(model.SystemUserRoleId), Add: []string{PermissionViewMembers}, }, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionViewMembers}, }, }, nil @@ -311,7 +311,7 @@ func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) { func (a *App) getAddManageGuestsPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionPromoteGuest, PermissionDemoteToGuest, PermissionInviteGuest}, }, }, nil @@ -321,7 +321,7 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { transformations := permissionsMap{} var allTeamSchemes []*model.Scheme - next := a.SchemesIterator(model.SCHEME_SCOPE_TEAM, 100) + next := a.SchemesIterator(model.SchemeScopeTeam, 100) var schemeBatch []*model.Scheme for schemeBatch = next(); len(schemeBatch) > 0; schemeBatch = next() { allTeamSchemes = append(allTeamSchemes, schemeBatch...) @@ -396,27 +396,27 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { // ensure team admins have create_post transformations = append(transformations, permissionTransformation{ - On: isRole(model.TEAM_ADMIN_ROLE_ID), + On: isRole(model.TeamAdminRoleId), Add: []string{PermissionCreatePost}, }) // ensure channel admins have create_post transformations = append(transformations, permissionTransformation{ - On: isRole(model.CHANNEL_ADMIN_ROLE_ID), + On: isRole(model.ChannelAdminRoleId), Add: []string{PermissionCreatePost}, }) // conditionally add all other moderated permissions to team and channel admins transformations = append(transformations, teamAndChannelAdminConditionalTransformations( - model.TEAM_ADMIN_ROLE_ID, - model.CHANNEL_ADMIN_ROLE_ID, - model.CHANNEL_USER_ROLE_ID, - model.CHANNEL_GUEST_ROLE_ID, + model.TeamAdminRoleId, + model.ChannelAdminRoleId, + model.ChannelUserRoleId, + model.ChannelGuestRoleId, )...) // ensure system admin has all of the moderated permissions transformations = append(transformations, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: append(moderatedPermissionsMinusCreatePost, PermissionCreatePost), }) @@ -433,7 +433,7 @@ func (a *App) getAddUseGroupMentionsPermissionMigration() (permissionsMap, error return permissionsMap{ permissionTransformation{ On: permissionAnd( - isNotRole(model.CHANNEL_GUEST_ROLE_ID), + isNotRole(model.ChannelGuestRoleId), isNotSchemeRole("Channel Guest Role for Scheme"), permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)), ), @@ -453,7 +453,7 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error) // add the new permissions to system admin transformations = append(transformations, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: permissionsToAdd, }) @@ -502,8 +502,8 @@ func (a *App) getAddConvertChannelPermissionsMigration() (permissionsMap, error) func (a *App) getSystemRolesPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES.Id, model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES.Id}, + On: isRole(model.SystemAdminRoleId), + Add: []string{model.PermissionSysconsoleReadUserManagementSystemRoles.Id, model.PermissionSysconsoleWriteUserManagementSystemRoles.Id}, }, }, nil } @@ -511,7 +511,7 @@ func (a *App) getSystemRolesPermissionsMigration() (permissionsMap, error) { func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionManageSharedChannels}, }, }, nil @@ -520,8 +520,8 @@ func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap, func (a *App) getBillingPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{model.PERMISSION_SYSCONSOLE_READ_BILLING.Id, model.PERMISSION_SYSCONSOLE_WRITE_BILLING.Id}, + On: isRole(model.SystemAdminRoleId), + Add: []string{model.PermissionSysconsoleReadBilling.Id, model.PermissionSysconsoleWriteBilling.Id}, }, }, nil } @@ -532,14 +532,14 @@ func (a *App) getAddManageSecureConnectionsPermissionsMigration() (permissionsMa // add the new permission to system admin transformations = append(transformations, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Add: []string{PermissionManageSecureConnections}, }) // remote the decprecated permission from system admin transformations = append(transformations, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), + On: isRole(model.SystemAdminRoleId), Remove: []string{PermissionManageRemoteClusters}, }) @@ -549,25 +549,25 @@ func (a *App) getAddManageSecureConnectionsPermissionsMigration() (permissionsMa func (a *App) getAddDownloadComplianceExportResult() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsToAddComplianceRead := []string{model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id, model.PERMISSION_READ_DATA_RETENTION_JOB.Id} - permissionsToAddComplianceWrite := []string{model.PERMISSION_MANAGE_JOBS.Id} + permissionsToAddComplianceRead := []string{model.PermissionDownloadComplianceExportResult.Id, model.PermissionReadDataRetentionJob.Id} + permissionsToAddComplianceWrite := []string{model.PermissionManageJobs.Id} // add the new permissions to system admin transformations = append(transformations, permissionTransformation{ - On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id}, + On: isRole(model.SystemAdminRoleId), + Add: []string{model.PermissionDownloadComplianceExportResult.Id}, }) // add Download Compliance Export Result and Read Jobs to all roles with sysconsole_read_compliance transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE.Id), + On: permissionExists(model.PermissionSysconsoleReadCompliance.Id), Add: permissionsToAddComplianceRead, }) // add manage_jobs to all roles with sysconsole_write_compliance transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE.Id), + On: permissionExists(model.PermissionSysconsoleWriteCompliance.Id), Add: permissionsToAddComplianceWrite, }) @@ -577,25 +577,25 @@ func (a *App) getAddDownloadComplianceExportResult() (permissionsMap, error) { func (a *App) getAddExperimentalSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsExperimentalRead := []string{model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE.Id, model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES.Id, model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS.Id} - permissionsExperimentalWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE.Id, model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES.Id, model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS.Id} + permissionsExperimentalRead := []string{model.PermissionSysconsoleReadExperimentalBleve.Id, model.PermissionSysconsoleReadExperimentalFeatures.Id, model.PermissionSysconsoleReadExperimentalFeatureFlags.Id} + permissionsExperimentalWrite := []string{model.PermissionSysconsoleWriteExperimentalBleve.Id, model.PermissionSysconsoleWriteExperimentalFeatures.Id, model.PermissionSysconsoleWriteExperimentalFeatureFlags.Id} // Give the new subsection READ permissions to any user with READ_EXPERIMENTAL transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL.Id), + On: permissionExists(model.PermissionSysconsoleReadExperimental.Id), Add: permissionsExperimentalRead, }) // Give the new subsection WRITE permissions to any user with WRITE_EXPERIMENTAL transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL.Id), + On: permissionExists(model.PermissionSysconsoleWriteExperimental.Id), Add: permissionsExperimentalWrite, }) // Give the ancillary permissions MANAGE_JOBS and PURGE_BLEVE_INDEXES to anyone with WRITE_EXPERIMENTAL_BLEVE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE.Id), - Add: []string{model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB.Id, model.PERMISSION_PURGE_BLEVE_INDEXES.Id}, + On: permissionExists(model.PermissionSysconsoleWriteExperimentalBleve.Id), + Add: []string{model.PermissionCreatePostBleveIndexesJob.Id, model.PermissionPurgeBleveIndexes.Id}, }) return transformations, nil @@ -604,18 +604,18 @@ func (a *App) getAddExperimentalSubsectionPermissions() (permissionsMap, error) func (a *App) getAddIntegrationsSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsIntegrationsRead := []string{model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id} - permissionsIntegrationsWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS.Id} + permissionsIntegrationsRead := []string{model.PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, model.PermissionSysconsoleReadIntegrationsBotAccounts.Id, model.PermissionSysconsoleReadIntegrationsGif.Id, model.PermissionSysconsoleReadIntegrationsCors.Id} + permissionsIntegrationsWrite := []string{model.PermissionSysconsoleWriteIntegrationsIntegrationManagement.Id, model.PermissionSysconsoleWriteIntegrationsBotAccounts.Id, model.PermissionSysconsoleWriteIntegrationsGif.Id, model.PermissionSysconsoleWriteIntegrationsCors.Id} // Give the new subsection READ permissions to any user with READ_INTEGRATIONS transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS.Id), + On: permissionExists(model.PermissionSysconsoleReadIntegrations.Id), Add: permissionsIntegrationsRead, }) // Give the new subsection WRITE permissions to any user with WRITE_EXPERIMENTAL transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS.Id), + On: permissionExists(model.PermissionSysconsoleWriteIntegrations.Id), Add: permissionsIntegrationsWrite, }) @@ -625,25 +625,25 @@ func (a *App) getAddIntegrationsSubsectionPermissions() (permissionsMap, error) func (a *App) getAddSiteSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsSiteRead := []string{model.PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_EMOJI.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_POSTS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_NOTICES.Id} - permissionsSiteWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES.Id} + permissionsSiteRead := []string{model.PermissionSysconsoleReadSiteCustomization.Id, model.PermissionSysconsoleReadSiteLocalization.Id, model.PermissionSysconsoleReadSiteUsersAndTeams.Id, model.PermissionSysconsoleReadSiteNotifications.Id, model.PermissionSysconsoleReadSiteAnnouncementBanner.Id, model.PermissionSysconsoleReadSiteEmoji.Id, model.PermissionSysconsoleReadSitePosts.Id, model.PermissionSysconsoleReadSiteFileSharingAndDownloads.Id, model.PermissionSysconsoleReadSitePublicLinks.Id, model.PermissionSysconsoleReadSiteNotices.Id} + permissionsSiteWrite := []string{model.PermissionSysconsoleWriteSiteCustomization.Id, model.PermissionSysconsoleWriteSiteLocalization.Id, model.PermissionSysconsoleWriteSiteUsersAndTeams.Id, model.PermissionSysconsoleWriteSiteNotifications.Id, model.PermissionSysconsoleWriteSiteAnnouncementBanner.Id, model.PermissionSysconsoleWriteSiteEmoji.Id, model.PermissionSysconsoleWriteSitePosts.Id, model.PermissionSysconsoleWriteSiteFileSharingAndDownloads.Id, model.PermissionSysconsoleWriteSitePublicLinks.Id, model.PermissionSysconsoleWriteSiteNotices.Id} // Give the new subsection READ permissions to any user with READ_SITE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_SITE.Id), + On: permissionExists(model.PermissionSysconsoleReadSite.Id), Add: permissionsSiteRead, }) // Give the new subsection WRITE permissions to any user with WRITE_SITE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_SITE.Id), + On: permissionExists(model.PermissionSysconsoleWriteSite.Id), Add: permissionsSiteWrite, }) // Give the ancillary permissions EDIT_BRAND to anyone with WRITE_SITE_CUSTOMIZATION transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id), - Add: []string{model.PERMISSION_EDIT_BRAND.Id}, + On: permissionExists(model.PermissionSysconsoleWriteSiteCustomization.Id), + Add: []string{model.PermissionEditBrand.Id}, }) return transformations, nil @@ -652,45 +652,45 @@ func (a *App) getAddSiteSubsectionPermissions() (permissionsMap, error) { func (a *App) getAddComplianceSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsComplianceRead := []string{model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id} - permissionsComplianceWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id} + permissionsComplianceRead := []string{model.PermissionSysconsoleReadComplianceDataRetentionPolicy.Id, model.PermissionSysconsoleReadComplianceComplianceExport.Id, model.PermissionSysconsoleReadComplianceComplianceMonitoring.Id, model.PermissionSysconsoleReadComplianceCustomTermsOfService.Id} + permissionsComplianceWrite := []string{model.PermissionSysconsoleWriteComplianceDataRetentionPolicy.Id, model.PermissionSysconsoleWriteComplianceComplianceExport.Id, model.PermissionSysconsoleWriteComplianceComplianceMonitoring.Id, model.PermissionSysconsoleWriteComplianceCustomTermsOfService.Id} // Give the new subsection READ permissions to any user with READ_COMPLIANCE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE.Id), + On: permissionExists(model.PermissionSysconsoleReadCompliance.Id), Add: permissionsComplianceRead, }) // Give the new subsection WRITE permissions to any user with WRITE_COMPLIANCE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE.Id), + On: permissionExists(model.PermissionSysconsoleWriteCompliance.Id), Add: permissionsComplianceWrite, }) // Ancilary permissions transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY.Id), - Add: []string{model.PERMISSION_CREATE_DATA_RETENTION_JOB.Id}, + On: permissionExists(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy.Id), + Add: []string{model.PermissionCreateDataRetentionJob.Id}, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id), - Add: []string{model.PERMISSION_READ_DATA_RETENTION_JOB.Id}, + On: permissionExists(model.PermissionSysconsoleReadComplianceDataRetentionPolicy.Id), + Add: []string{model.PermissionReadDataRetentionJob.Id}, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT.Id), - Add: []string{model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB.Id, model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id}, + On: permissionExists(model.PermissionSysconsoleWriteComplianceComplianceExport.Id), + Add: []string{model.PermissionCreateComplianceExportJob.Id, model.PermissionDownloadComplianceExportResult.Id}, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id), - Add: []string{model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB.Id, model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id}, + On: permissionExists(model.PermissionSysconsoleReadComplianceComplianceExport.Id), + Add: []string{model.PermissionReadComplianceExportJob.Id, model.PermissionDownloadComplianceExportResult.Id}, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id), - Add: []string{model.PERMISSION_READ_AUDITS.Id}, + On: permissionExists(model.PermissionSysconsoleReadComplianceCustomTermsOfService.Id), + Add: []string{model.PermissionReadAudits.Id}, }) return transformations, nil @@ -700,88 +700,88 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} permissionsEnvironmentRead := []string{ - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING.Id, - model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER.Id, + model.PermissionSysconsoleReadEnvironmentWebServer.Id, + model.PermissionSysconsoleReadEnvironmentDatabase.Id, + model.PermissionSysconsoleReadEnvironmentElasticsearch.Id, + model.PermissionSysconsoleReadEnvironmentFileStorage.Id, + model.PermissionSysconsoleReadEnvironmentImageProxy.Id, + model.PermissionSysconsoleReadEnvironmentSmtp.Id, + model.PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, + model.PermissionSysconsoleReadEnvironmentHighAvailability.Id, + model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, + model.PermissionSysconsoleReadEnvironmentLogging.Id, + model.PermissionSysconsoleReadEnvironmentSessionLengths.Id, + model.PermissionSysconsoleReadEnvironmentPerformanceMonitoring.Id, + model.PermissionSysconsoleReadEnvironmentDeveloper.Id, } permissionsEnvironmentWrite := []string{ - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING.Id, - model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER.Id, + model.PermissionSysconsoleWriteEnvironmentWebServer.Id, + model.PermissionSysconsoleWriteEnvironmentDatabase.Id, + model.PermissionSysconsoleWriteEnvironmentElasticsearch.Id, + model.PermissionSysconsoleWriteEnvironmentFileStorage.Id, + model.PermissionSysconsoleWriteEnvironmentImageProxy.Id, + model.PermissionSysconsoleWriteEnvironmentSmtp.Id, + model.PermissionSysconsoleWriteEnvironmentPushNotificationServer.Id, + model.PermissionSysconsoleWriteEnvironmentHighAvailability.Id, + model.PermissionSysconsoleWriteEnvironmentRateLimiting.Id, + model.PermissionSysconsoleWriteEnvironmentLogging.Id, + model.PermissionSysconsoleWriteEnvironmentSessionLengths.Id, + model.PermissionSysconsoleWriteEnvironmentPerformanceMonitoring.Id, + model.PermissionSysconsoleWriteEnvironmentDeveloper.Id, } // Give the new subsection READ permissions to any user with READ_ENVIRONMENT transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT.Id), + On: permissionExists(model.PermissionSysconsoleReadEnvironment.Id), Add: permissionsEnvironmentRead, }) // Give the new subsection WRITE permissions to any user with WRITE_ENVIRONMENT transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT.Id), + On: permissionExists(model.PermissionSysconsoleWriteEnvironment.Id), Add: permissionsEnvironmentWrite, }) // Give these ancillary permissions to anyone with READ_ENVIRONMENT_ELASTICSEARCH transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id), + On: permissionExists(model.PermissionSysconsoleReadEnvironmentElasticsearch.Id), Add: []string{ - model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB.Id, - model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB.Id, + model.PermissionReadElasticsearchPostIndexingJob.Id, + model.PermissionReadElasticsearchPostAggregationJob.Id, }, }) // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_WEB_SERVER transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id), + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentWebServer.Id), Add: []string{ - model.PERMISSION_TEST_SITE_URL.Id, - model.PERMISSION_RELOAD_CONFIG.Id, - model.PERMISSION_INVALIDATE_CACHES.Id, + model.PermissionTestSiteUrl.Id, + model.PermissionReloadConfig.Id, + model.PermissionInvalidateCaches.Id, }, }) // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_DATABASE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id), - Add: []string{model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS.Id}, + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentDatabase.Id), + Add: []string{model.PermissionRecycleDatabaseConnections.Id}, }) // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_ELASTICSEARCH transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id), + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentElasticsearch.Id), Add: []string{ - model.PERMISSION_TEST_ELASTICSEARCH.Id, - model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB.Id, - model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB.Id, - model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES.Id, + model.PermissionTestElasticsearch.Id, + model.PermissionCreateElasticsearchPostIndexingJob.Id, + model.PermissionCreateElasticsearchPostAggregationJob.Id, + model.PermissionPurgeElasticsearchIndexes.Id, }, }) // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_FILE_STORAGE transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id), - Add: []string{model.PERMISSION_TEST_S3.Id}, + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentFileStorage.Id), + Add: []string{model.PermissionTestS3.Id}, }) return transformations, nil @@ -790,27 +790,27 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) { func (a *App) getAddAboutSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsAboutRead := []string{model.PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id} - permissionsAboutWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id} + permissionsAboutRead := []string{model.PermissionSysconsoleReadAboutEditionAndLicense.Id} + permissionsAboutWrite := []string{model.PermissionSysconsoleWriteAboutEditionAndLicense.Id} transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ABOUT.Id), + On: permissionExists(model.PermissionSysconsoleReadAbout.Id), Add: permissionsAboutRead, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT.Id), + On: permissionExists(model.PermissionSysconsoleWriteAbout.Id), Add: permissionsAboutWrite, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id), - Add: []string{model.PERMISSION_READ_LICENSE_INFORMATION.Id}, + On: permissionExists(model.PermissionSysconsoleReadAboutEditionAndLicense.Id), + Add: []string{model.PermissionReadLicenseInformation.Id}, }) transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id), - Add: []string{model.PERMISSION_MANAGE_LICENSE_INFORMATION.Id}, + On: permissionExists(model.PermissionSysconsoleWriteAboutEditionAndLicense.Id), + Add: []string{model.PermissionManageLicenseInformation.Id}, }) return transformations, nil @@ -820,38 +820,38 @@ func (a *App) getAddReportingSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} permissionsReportingRead := []string{ - model.PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id, - model.PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS.Id, - model.PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id, + model.PermissionSysconsoleReadReportingSiteStatistics.Id, + model.PermissionSysconsoleReadReportingTeamStatistics.Id, + model.PermissionSysconsoleReadReportingServerLogs.Id, } permissionsReportingWrite := []string{ - model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS.Id, - model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS.Id, - model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS.Id, + model.PermissionSysconsoleWriteReportingSiteStatistics.Id, + model.PermissionSysconsoleWriteReportingTeamStatistics.Id, + model.PermissionSysconsoleWriteReportingServerLogs.Id, } // Give the new subsection READ permissions to any user with READ_REPORTING transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING.Id), + On: permissionExists(model.PermissionSysconsoleReadReporting.Id), Add: permissionsReportingRead, }) // Give the new subsection WRITE permissions to any user with WRITE_REPORTING transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_REPORTING.Id), + On: permissionExists(model.PermissionSysconsoleWriteReporting.Id), Add: permissionsReportingWrite, }) // Give the ancillary permissions PERMISSION_GET_ANALYTICS to anyone with PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS or PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS transformations = append(transformations, permissionTransformation{ - On: permissionOr(permissionExists(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS.Id), permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id)), - Add: []string{model.PERMISSION_GET_ANALYTICS.Id}, + On: permissionOr(permissionExists(model.PermissionSysconsoleReadUserManagementUsers.Id), permissionExists(model.PermissionSysconsoleReadReportingSiteStatistics.Id)), + Add: []string{model.PermissionGetAnalytics.Id}, }) // Give the ancillary permissions PERMISSION_GET_LOGS to anyone with PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id), - Add: []string{model.PERMISSION_GET_LOGS.Id}, + On: permissionExists(model.PermissionSysconsoleReadReportingServerLogs.Id), + Add: []string{model.PermissionGetLogs.Id}, }) return transformations, nil @@ -860,43 +860,43 @@ func (a *App) getAddReportingSubsectionPermissions() (permissionsMap, error) { func (a *App) getAddAuthenticationSubsectionPermissions() (permissionsMap, error) { transformations := []permissionTransformation{} - permissionsAuthenticationRead := []string{model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS.Id} - permissionsAuthenticationWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_MFA.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_OPENID.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS.Id} + permissionsAuthenticationRead := []string{model.PermissionSysconsoleReadAuthenticationSignup.Id, model.PermissionSysconsoleReadAuthenticationEmail.Id, model.PermissionSysconsoleReadAuthenticationPassword.Id, model.PermissionSysconsoleReadAuthenticationMfa.Id, model.PermissionSysconsoleReadAuthenticationLdap.Id, model.PermissionSysconsoleReadAuthenticationSaml.Id, model.PermissionSysconsoleReadAuthenticationOpenid.Id, model.PermissionSysconsoleReadAuthenticationGuestAccess.Id} + permissionsAuthenticationWrite := []string{model.PermissionSysconsoleWriteAuthenticationSignup.Id, model.PermissionSysconsoleWriteAuthenticationEmail.Id, model.PermissionSysconsoleWriteAuthenticationPassword.Id, model.PermissionSysconsoleWriteAuthenticationMfa.Id, model.PermissionSysconsoleWriteAuthenticationLdap.Id, model.PermissionSysconsoleWriteAuthenticationSaml.Id, model.PermissionSysconsoleWriteAuthenticationOpenid.Id, model.PermissionSysconsoleWriteAuthenticationGuestAccess.Id} // Give the new subsection READ permissions to any user with READ_AUTHENTICATION transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION.Id), + On: permissionExists(model.PermissionSysconsoleReadAuthentication.Id), Add: permissionsAuthenticationRead, }) // Give the new subsection WRITE permissions to any user with WRITE_AUTHENTICATION transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION.Id), + On: permissionExists(model.PermissionSysconsoleWriteAuthentication.Id), Add: permissionsAuthenticationWrite, }) // Give the ancillary permissions for LDAP to anyone with WRITE_AUTHENTICATION_LDAP transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP.Id), - Add: []string{model.PERMISSION_CREATE_LDAP_SYNC_JOB.Id, model.PERMISSION_TEST_LDAP.Id, model.PERMISSION_ADD_LDAP_PUBLIC_CERT.Id, model.PERMISSION_ADD_LDAP_PRIVATE_CERT.Id, model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT.Id, model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT.Id}, + On: permissionExists(model.PermissionSysconsoleWriteAuthenticationLdap.Id), + Add: []string{model.PermissionCreateLdapSyncJob.Id, model.PermissionTestLdap.Id, model.PermissionAddLdapPublicCert.Id, model.PermissionAddLdapPrivateCert.Id, model.PermissionRemoveLdapPublicCert.Id, model.PermissionRemoveLdapPrivateCert.Id}, }) // Give the ancillary permissions PERMISSION_TEST_LDAP to anyone with READ_AUTHENTICATION_LDAP transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id), - Add: []string{model.PERMISSION_READ_LDAP_SYNC_JOB.Id}, + On: permissionExists(model.PermissionSysconsoleReadAuthenticationLdap.Id), + Add: []string{model.PermissionReadLdapSyncJob.Id}, }) // Give the ancillary permissions PERMISSION_INVALIDATE_EMAIL_INVITE to anyone with WRITE_AUTHENTICATION_EMAIL transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL.Id), - Add: []string{model.PERMISSION_INVALIDATE_EMAIL_INVITE.Id}, + On: permissionExists(model.PermissionSysconsoleWriteAuthenticationEmail.Id), + Add: []string{model.PermissionInvalidateEmailInvite.Id}, }) // Give the ancillary permissions for SAML to anyone with WRITE_AUTHENTICATION_SAML transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML.Id), - Add: []string{model.PERMISSION_GET_SAML_METADATA_FROM_IDP.Id, model.PERMISSION_ADD_SAML_PUBLIC_CERT.Id, model.PERMISSION_ADD_SAML_PRIVATE_CERT.Id, model.PERMISSION_ADD_SAML_IDP_CERT.Id, model.PERMISSION_REMOVE_SAML_PUBLIC_CERT.Id, model.PERMISSION_REMOVE_SAML_PRIVATE_CERT.Id, model.PERMISSION_REMOVE_SAML_IDP_CERT.Id, model.PERMISSION_GET_SAML_CERT_STATUS.Id}, + On: permissionExists(model.PermissionSysconsoleWriteAuthenticationSaml.Id), + Add: []string{model.PermissionGetSamlMetadataFromIdp.Id, model.PermissionAddSamlPublicCert.Id, model.PermissionAddSamlPrivateCert.Id, model.PermissionAddSamlIdpCert.Id, model.PermissionRemoveSamlPublicCert.Id, model.PermissionRemoveSamlPrivateCert.Id, model.PermissionRemoveSamlIdpCert.Id, model.PermissionGetSamlCertStatus.Id}, }) return transformations, nil @@ -908,8 +908,8 @@ func (a *App) getAddTestEmailAncillaryPermission() (permissionsMap, error) { // Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_SMTP transformations = append(transformations, permissionTransformation{ - On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id), - Add: []string{model.PERMISSION_TEST_EMAIL.Id}, + On: permissionExists(model.PermissionSysconsoleWriteEnvironmentSmtp.Id), + Add: []string{model.PermissionTestEmail.Id}, }) return transformations, nil @@ -926,33 +926,33 @@ func (s *Server) doPermissionsMigrations() error { Key string Migration func() (permissionsMap, error) }{ - {Key: model.MIGRATION_KEY_EMOJI_PERMISSIONS_SPLIT, Migration: a.getEmojisPermissionsSplitMigration}, - {Key: model.MIGRATION_KEY_WEBHOOK_PERMISSIONS_SPLIT, Migration: a.getWebhooksPermissionsSplitMigration}, - {Key: model.MIGRATION_KEY_LIST_JOIN_PUBLIC_PRIVATE_TEAMS, Migration: a.getListJoinPublicPrivateTeamsPermissionsMigration}, - {Key: model.MIGRATION_KEY_REMOVE_PERMANENT_DELETE_USER, Migration: a.removePermanentDeleteUserMigration}, - {Key: model.MIGRATION_KEY_ADD_BOT_PERMISSIONS, Migration: a.getAddBotPermissionsMigration}, - {Key: model.MIGRATION_KEY_APPLY_CHANNEL_MANAGE_DELETE_TO_CHANNEL_USER, Migration: a.applyChannelManageDeleteToChannelUser}, - {Key: model.MIGRATION_KEY_REMOVE_CHANNEL_MANAGE_DELETE_FROM_TEAM_USER, Migration: a.removeChannelManageDeleteFromTeamUser}, - {Key: model.MIGRATION_KEY_VIEW_MEMBERS_NEW_PERMISSION, Migration: a.getViewMembersPermissionMigration}, - {Key: model.MIGRATION_KEY_ADD_MANAGE_GUESTS_PERMISSIONS, Migration: a.getAddManageGuestsPermissionsMigration}, - {Key: model.MIGRATION_KEY_CHANNEL_MODERATIONS_PERMISSIONS, Migration: a.channelModerationPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_USE_GROUP_MENTIONS_PERMISSION, Migration: a.getAddUseGroupMentionsPermissionMigration}, - {Key: model.MIGRATION_KEY_ADD_SYSTEM_CONSOLE_PERMISSIONS, Migration: a.getAddSystemConsolePermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_CONVERT_CHANNEL_PERMISSIONS, Migration: a.getAddConvertChannelPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_MANAGE_SHARED_CHANNEL_PERMISSIONS, Migration: a.getAddManageSharedChannelsPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_MANAGE_SECURE_CONNECTIONS_PERMISSIONS, Migration: a.getAddManageSecureConnectionsPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_SYSTEM_ROLES_PERMISSIONS, Migration: a.getSystemRolesPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_BILLING_PERMISSIONS, Migration: a.getBillingPermissionsMigration}, - {Key: model.MIGRATION_KEY_ADD_DOWNLOAD_COMPLIANCE_EXPORT_RESULTS, Migration: a.getAddDownloadComplianceExportResult}, - {Key: model.MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS, Migration: a.getAddExperimentalSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_AUTHENTICATION_SUBSECTION_PERMISSIONS, Migration: a.getAddAuthenticationSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_INTEGRATIONS_SUBSECTION_PERMISSIONS, Migration: a.getAddIntegrationsSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_SITE_SUBSECTION_PERMISSIONS, Migration: a.getAddSiteSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_COMPLIANCE_SUBSECTION_PERMISSIONS, Migration: a.getAddComplianceSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_ENVIRONMENT_SUBSECTION_PERMISSIONS, Migration: a.getAddEnvironmentSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_ABOUT_SUBSECTION_PERMISSIONS, Migration: a.getAddAboutSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS, Migration: a.getAddReportingSubsectionPermissions}, - {Key: model.MIGRATION_KEY_ADD_TEST_EMAIL_ANCILLARY_PERMISSION, Migration: a.getAddTestEmailAncillaryPermission}, + {Key: model.MigrationKeyEmojiPermissionsSplit, Migration: a.getEmojisPermissionsSplitMigration}, + {Key: model.MigrationKeyWebhookPermissionsSplit, Migration: a.getWebhooksPermissionsSplitMigration}, + {Key: model.MigrationKeyListJoinPublicPrivateTeams, Migration: a.getListJoinPublicPrivateTeamsPermissionsMigration}, + {Key: model.MigrationKeyRemovePermanentDeleteUser, Migration: a.removePermanentDeleteUserMigration}, + {Key: model.MigrationKeyAddBotPermissions, Migration: a.getAddBotPermissionsMigration}, + {Key: model.MigrationKeyApplyChannelManageDeleteToChannelUser, Migration: a.applyChannelManageDeleteToChannelUser}, + {Key: model.MigrationKeyRemoveChannelManageDeleteFromTeamUser, Migration: a.removeChannelManageDeleteFromTeamUser}, + {Key: model.MigrationKeyViewMembersNewPermission, Migration: a.getViewMembersPermissionMigration}, + {Key: model.MigrationKeyAddManageGuestsPermissions, Migration: a.getAddManageGuestsPermissionsMigration}, + {Key: model.MigrationKeyChannelModerationsPermissions, Migration: a.channelModerationPermissionsMigration}, + {Key: model.MigrationKeyAddUseGroupMentionsPermission, Migration: a.getAddUseGroupMentionsPermissionMigration}, + {Key: model.MigrationKeyAddSystemConsolePermissions, Migration: a.getAddSystemConsolePermissionsMigration}, + {Key: model.MigrationKeyAddConvertChannelPermissions, Migration: a.getAddConvertChannelPermissionsMigration}, + {Key: model.MigrationKeyAddManageSharedChannelPermissions, Migration: a.getAddManageSharedChannelsPermissionsMigration}, + {Key: model.MigrationKeyAddManageSecureConnectionsPermissions, Migration: a.getAddManageSecureConnectionsPermissionsMigration}, + {Key: model.MigrationKeyAddSystemRolesPermissions, Migration: a.getSystemRolesPermissionsMigration}, + {Key: model.MigrationKeyAddBillingPermissions, Migration: a.getBillingPermissionsMigration}, + {Key: model.MigrationKeyAddDownloadComplianceExportResults, Migration: a.getAddDownloadComplianceExportResult}, + {Key: model.MigrationKeyAddExperimentalSubsectionPermissions, Migration: a.getAddExperimentalSubsectionPermissions}, + {Key: model.MigrationKeyAddAuthenticationSubsectionPermissions, Migration: a.getAddAuthenticationSubsectionPermissions}, + {Key: model.MigrationKeyAddIntegrationsSubsectionPermissions, Migration: a.getAddIntegrationsSubsectionPermissions}, + {Key: model.MigrationKeyAddSiteSubsectionPermissions, Migration: a.getAddSiteSubsectionPermissions}, + {Key: model.MigrationKeyAddComplianceSubsectionPermissions, Migration: a.getAddComplianceSubsectionPermissions}, + {Key: model.MigrationKeyAddEnvironmentSubsectionPermissions, Migration: a.getAddEnvironmentSubsectionPermissions}, + {Key: model.MigrationKeyAddAboutSubsectionPermissions, Migration: a.getAddAboutSubsectionPermissions}, + {Key: model.MigrationKeyAddReportingSubsectionPermissions, Migration: a.getAddReportingSubsectionPermissions}, + {Key: model.MigrationKeyAddTestEmailAncillaryPermission, Migration: a.getAddTestEmailAncillaryPermission}, } roles, err := s.Store.Role().GetAll() diff --git a/app/permissions_test.go b/app/permissions_test.go index ac28ee28da..6071cf87af 100644 --- a/app/permissions_test.go +++ b/app/permissions_test.go @@ -99,7 +99,7 @@ func TestImportPermissions(t *testing.T) { name := model.NewId() displayName := model.NewId() description := "my test description" - scope := model.SCHEME_SCOPE_CHANNEL + scope := model.SchemeScopeChannel roleName1 := model.NewId() roleName2 := model.NewId() @@ -179,7 +179,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) { name := model.NewId() displayName := model.NewId() description := "my test description" - scope := model.SCHEME_SCOPE_CHANNEL + scope := model.SchemeScopeChannel roleName1 := model.NewId() roleName2 := model.NewId() @@ -191,7 +191,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) { var expected int withMigrationMarkedComplete(th, func() { var appErr *model.AppError - results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100) + results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100) if appErr != nil { panic(appErr) } @@ -202,7 +202,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) { t.Error(err) } - results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100) + results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100) if appErr != nil { panic(appErr) } @@ -233,7 +233,7 @@ func TestImportPermissions_schemeDeletedOnRoleFailure(t *testing.T) { var expected int withMigrationMarkedComplete(th, func() { var appErr *model.AppError - results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100) + results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100) if appErr != nil { panic(appErr) } @@ -244,7 +244,7 @@ func TestImportPermissions_schemeDeletedOnRoleFailure(t *testing.T) { t.Error(err) } - results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100) + results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100) if appErr != nil { panic(appErr) } @@ -261,30 +261,30 @@ func TestMigration(t *testing.T) { th := Setup(t) defer th.TearDown() - role, err := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + role, err := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId) require.Nil(t, err) - assert.Contains(t, role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_USE_GROUP_MENTIONS.Id) + assert.Contains(t, role.Permissions, model.PermissionCreateEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionDeleteEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionDeleteOthersEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionUseGroupMentions.Id) th.App.ResetPermissionsSystem() - role, err = th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + role, err = th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId) require.Nil(t, err) - assert.Contains(t, role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id) - assert.Contains(t, role.Permissions, model.PERMISSION_USE_GROUP_MENTIONS.Id) + assert.Contains(t, role.Permissions, model.PermissionCreateEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionDeleteEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionDeleteOthersEmojis.Id) + assert.Contains(t, role.Permissions, model.PermissionUseGroupMentions.Id) } func withMigrationMarkedComplete(th *TestHelper, f func()) { // Mark the migration as done. - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) - th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) // Un-mark the migration at the end of the test. defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() f() } diff --git a/app/plugin.go b/app/plugin.go index 0937c707c3..d2257e91d3 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -127,7 +127,7 @@ func (s *Server) syncPluginsActiveState() { deactivated := pluginsEnvironment.Deactivate(plugin.Manifest.Id) if deactivated && plugin.Manifest.HasClient() { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_DISABLED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventPluginDisabled, "", "", "", nil) message.Add("manifest", plugin.Manifest.ClientManifest()) s.Publish(message) } @@ -803,7 +803,7 @@ func (s *Server) notifyPluginEnabled(manifest *model.Manifest) error { } // Notify all cluster peer clients. - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_ENABLED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventPluginEnabled, "", "", "", nil) message.Add("manifest", manifest.ClientManifest()) s.Publish(message) @@ -823,7 +823,7 @@ func (s *Server) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pl pluginSignaturePathMap := make(map[string]*pluginSignaturePath) fsPrefix := "" - if *s.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 { + if *s.Config().FileSettings.DriverName == model.ImageDriverS3 { ptr := s.Config().FileSettings.AmazonS3PathPrefix if ptr != nil && *ptr != "" { fsPrefix = *ptr + "/" diff --git a/app/plugin_api.go b/app/plugin_api.go index eecee38575..983a636a5f 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -315,13 +315,13 @@ func (api *PluginAPI) GetUserStatusesByIds(userIDs []string) ([]*model.Status, * func (api *PluginAPI) UpdateUserStatus(userID, status string) (*model.Status, *model.AppError) { switch status { - case model.STATUS_ONLINE: + case model.StatusOnline: api.app.SetStatusOnline(userID, true) - case model.STATUS_OFFLINE: + case model.StatusOffline: api.app.SetStatusOffline(userID, true) - case model.STATUS_AWAY: + case model.StatusAway: api.app.SetStatusAwayIfNeeded(userID, true) - case model.STATUS_DND: + case model.StatusDnd: api.app.SetStatusDoNotDisturb(userID) default: return nil, model.NewAppError("UpdateUserStatus", "plugin.api.update_user_status.bad_status", nil, "unrecognized status", http.StatusBadRequest) @@ -340,13 +340,13 @@ func (api *PluginAPI) SetUserStatusTimedDND(userID string, endTime int64) (*mode func (api *PluginAPI) GetUsersInChannel(channelID, sortBy string, page, perPage int) ([]*model.User, *model.AppError) { switch sortBy { - case model.CHANNEL_SORT_BY_USERNAME: + case model.ChannelSortByUsername: return api.app.GetUsersInChannel(&model.UserGetOptions{ InChannelId: channelID, Page: page, PerPage: perPage, }) - case model.CHANNEL_SORT_BY_STATUS: + case model.ChannelSortByStatus: return api.app.GetUsersInChannelByStatus(&model.UserGetOptions{ InChannelId: channelID, Page: page, @@ -372,8 +372,8 @@ func (api *PluginAPI) GetLDAPUserAttributes(userID string, attributes []string) } // Only bother running the query if the user's auth service is LDAP or it's SAML and sync is enabled. - if user.AuthService == model.USER_AUTH_SERVICE_LDAP || - (user.AuthService == model.USER_AUTH_SERVICE_SAML && *api.app.Config().SamlSettings.EnableSyncWithLdap) { + if user.AuthService == model.UserAuthServiceLdap || + (user.AuthService == model.UserAuthServiceSaml && *api.app.Config().SamlSettings.EnableSyncWithLdap) { return api.app.Ldap().GetUserAttributes(*user.AuthData, attributes) } @@ -1116,7 +1116,7 @@ func (api *PluginAPI) UpdateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *mod return nil, err } - return api.app.UpdateOauthApp(oldApp, app) + return api.app.UpdateOAuthApp(oldApp, app) } func (api *PluginAPI) DeleteOAuthApp(appID string) *model.AppError { @@ -1132,7 +1132,7 @@ func (api *PluginAPI) PublishPluginClusterEvent(ev model.PluginClusterEvent, } msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_PLUGIN_EVENT, + Event: model.ClusterEventPluginEvent, SendType: opts.SendType, WaitForAllToSend: false, Props: map[string]string{ @@ -1175,7 +1175,7 @@ func (api *PluginAPI) RequestTrialLicense(requesterID string, users int, termsAc trialLicenseRequest := &model.TrialLicenseRequest{ ServerID: api.app.TelemetryId(), - Name: requester.GetDisplayName(model.SHOW_FULLNAME), + Name: requester.GetDisplayName(model.ShowFullName), Email: requester.Email, SiteName: *api.app.Config().TeamSettings.SiteName, SiteURL: *api.app.Config().ServiceSettings.SiteURL, diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index a189958718..52af411062 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -180,7 +180,7 @@ func TestPluginAPIGetUserPreferences(t *testing.T) { assert.Equal(t, 1, len(preferences)) assert.Equal(t, user1.Id, preferences[0].UserId) - assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category) + assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category) assert.Equal(t, user1.Id, preferences[0].Name) assert.Equal(t, "0", preferences[0].Value) } @@ -219,7 +219,7 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) { preference := model.Preference{ Name: user2.Id, UserId: user2.Id, - Category: model.PREFERENCE_CATEGORY_THEME, + Category: model.PreferenceCategoryTheme, Value: `{"color": "#ff0000", "color2": "#faf"}`, } err = api.UpdatePreferencesForUser(user2.Id, []model.Preference{preference}) @@ -234,7 +234,7 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) { preferences, err = api.GetPreferencesForUser(user2.Id) require.Nil(t, err) assert.Equal(t, 1, len(preferences)) - assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category) + assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category) } func TestPluginAPIUpdateUserPreferences(t *testing.T) { @@ -254,14 +254,14 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) { require.Nil(t, err) assert.Equal(t, 1, len(preferences)) assert.Equal(t, user1.Id, preferences[0].UserId) - assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category) + assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category) assert.Equal(t, user1.Id, preferences[0].Name) assert.Equal(t, "0", preferences[0].Value) preference := model.Preference{ Name: user1.Id, UserId: user1.Id, - Category: model.PREFERENCE_CATEGORY_THEME, + Category: model.PreferenceCategoryTheme, Value: `{"color": "#ff0000", "color2": "#faf"}`, } @@ -272,12 +272,12 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) { require.Nil(t, err) assert.Equal(t, 2, len(preferences)) - expectedCategories := []string{model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, model.PREFERENCE_CATEGORY_THEME} + expectedCategories := []string{model.PreferenceCategoryTutorialSteps, model.PreferenceCategoryTheme} for _, pref := range preferences { assert.Contains(t, expectedCategories, pref.Category) assert.Equal(t, user1.Id, pref.UserId) assert.Equal(t, user1.Id, pref.Name) - if pref.Category == model.PREFERENCE_CATEGORY_TUTORIAL_STEPS { + if pref.Category == model.PreferenceCategoryTutorialSteps { assert.Equal(t, "0", pref.Value) } else { newTheme, _ := json.Marshal(map[string]string{"color": "#ff0000", "color2": "#faf"}) @@ -586,7 +586,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { t.Run("get file infos filtered by channel ordered by created at descending", func(t *testing.T) { fileInfos, err := api.GetFileInfos(0, 5, &model.GetFileInfosOptions{ ChannelIds: []string{th.BasicChannel.Id}, - SortBy: model.FILEINFO_SORT_BY_CREATED, + SortBy: model.FileinfoSortByCreated, SortDescending: true, }) require.Nil(t, err) @@ -1316,33 +1316,33 @@ func TestPluginAPIGetConfig(t *testing.T) { config := api.GetConfig() if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" { - assert.Equal(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) + assert.Equal(t, *config.LdapSettings.BindPassword, model.FakeSetting) } - assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) + assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FakeSetting) if *config.FileSettings.AmazonS3SecretAccessKey != "" { - assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) + assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FakeSetting) } if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" { - assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) + assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FakeSetting) } if *config.GitLabSettings.Secret != "" { - assert.Equal(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) + assert.Equal(t, *config.GitLabSettings.Secret, model.FakeSetting) } - assert.Equal(t, *config.SqlSettings.DataSource, model.FAKE_SETTING) - assert.Equal(t, *config.SqlSettings.AtRestEncryptKey, model.FAKE_SETTING) - assert.Equal(t, *config.ElasticsearchSettings.Password, model.FAKE_SETTING) + assert.Equal(t, *config.SqlSettings.DataSource, model.FakeSetting) + assert.Equal(t, *config.SqlSettings.AtRestEncryptKey, model.FakeSetting) + assert.Equal(t, *config.ElasticsearchSettings.Password, model.FakeSetting) for i := range config.SqlSettings.DataSourceReplicas { - assert.Equal(t, config.SqlSettings.DataSourceReplicas[i], model.FAKE_SETTING) + assert.Equal(t, config.SqlSettings.DataSourceReplicas[i], model.FakeSetting) } for i := range config.SqlSettings.DataSourceSearchReplicas { - assert.Equal(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FAKE_SETTING) + assert.Equal(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FakeSetting) } } @@ -1353,33 +1353,33 @@ func TestPluginAPIGetUnsanitizedConfig(t *testing.T) { config := api.GetUnsanitizedConfig() if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" { - assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING) + assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FakeSetting) } - assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING) + assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FakeSetting) if *config.FileSettings.AmazonS3SecretAccessKey != "" { - assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING) + assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FakeSetting) } if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" { - assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING) + assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FakeSetting) } if *config.GitLabSettings.Secret != "" { - assert.NotEqual(t, *config.GitLabSettings.Secret, model.FAKE_SETTING) + assert.NotEqual(t, *config.GitLabSettings.Secret, model.FakeSetting) } - assert.NotEqual(t, *config.SqlSettings.DataSource, model.FAKE_SETTING) - assert.NotEqual(t, *config.SqlSettings.AtRestEncryptKey, model.FAKE_SETTING) - assert.NotEqual(t, *config.ElasticsearchSettings.Password, model.FAKE_SETTING) + assert.NotEqual(t, *config.SqlSettings.DataSource, model.FakeSetting) + assert.NotEqual(t, *config.SqlSettings.AtRestEncryptKey, model.FakeSetting) + assert.NotEqual(t, *config.ElasticsearchSettings.Password, model.FakeSetting) for i := range config.SqlSettings.DataSourceReplicas { - assert.NotEqual(t, config.SqlSettings.DataSourceReplicas[i], model.FAKE_SETTING) + assert.NotEqual(t, config.SqlSettings.DataSourceReplicas[i], model.FakeSetting) } for i := range config.SqlSettings.DataSourceSearchReplicas { - assert.NotEqual(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FAKE_SETTING) + assert.NotEqual(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FakeSetting) } } @@ -1712,7 +1712,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) { defer wsc.Close() resp := <-wsc.ResponseChannel - require.Equal(t, resp.Status, model.STATUS_OK) + require.Equal(t, resp.Status, model.StatusOk) for i := 0; i < 10; i++ { wsc.SendMessage("custom_action", map[string]interface{}{"value": i}) @@ -1722,7 +1722,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) { case <-time.After(1 * time.Second): } require.NotNil(t, resp) - require.Equal(t, resp.Status, model.STATUS_OK) + require.Equal(t, resp.Status, model.StatusOk) require.Equal(t, "custom_action", resp.Data["action"]) require.Equal(t, float64(i), resp.Data["value"]) } @@ -1750,7 +1750,7 @@ func (mscp *MockSlashCommandProvider) DoCommand(a *App, c *request.Context, args mscp.Message = message return &model.CommandResponse{ Text: "mock", - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/plugin_api_tests/test_update_user_status_plugin/main.go b/app/plugin_api_tests/test_update_user_status_plugin/main.go index 36c91897f7..fb9a5d0cfe 100644 --- a/app/plugin_api_tests/test_update_user_status_plugin/main.go +++ b/app/plugin_api_tests/test_update_user_status_plugin/main.go @@ -26,7 +26,7 @@ func (p *MyPlugin) OnConfigurationChange() error { func (p *MyPlugin) MessageWillBePosted(_ *plugin.Context, _ *model.Post) (*model.Post, string) { uid := p.configuration.BasicUserID - statuses := []string{model.STATUS_ONLINE, model.STATUS_AWAY, model.STATUS_DND, model.STATUS_OFFLINE} + statuses := []string{model.StatusOnline, model.StatusAway, model.StatusDnd, model.StatusOffline} for _, s := range statuses { status, err := p.API.UpdateUserStatus(uid, s) diff --git a/app/plugin_commands_test.go b/app/plugin_commands_test.go index 8145aca87f..ca005d7d95 100644 --- a/app/plugin_commands_test.go +++ b/app/plugin_commands_test.go @@ -78,7 +78,7 @@ func TestPluginCommand(t *testing.T) { func (p *MyPlugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: "text", }, nil } @@ -93,7 +93,7 @@ func TestPluginCommand(t *testing.T) { resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) - require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType) + require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType) require.Equal(t, "text", resp.Text) err2 := th.App.DisablePlugin(pluginIDs[0]) @@ -172,7 +172,7 @@ func TestPluginCommand(t *testing.T) { p.API.LogInfo("ExecuteCommand, saved plugin config") return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: "text", }, nil } @@ -196,7 +196,7 @@ func TestPluginCommand(t *testing.T) { // Ignore if we kill below. if !killed { require.Nil(t, err) - require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType) + require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType) require.Equal(t, "text", resp.Text) } }() @@ -266,7 +266,7 @@ func TestPluginCommand(t *testing.T) { func (p *MyPlugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: "text", }, nil } @@ -282,7 +282,7 @@ func TestPluginCommand(t *testing.T) { args.Command = "/code" resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) - require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType) + require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType) require.Equal(t, "text", resp.Text) th.App.RemovePlugin(pluginIDs[0]) diff --git a/app/plugin_event.go b/app/plugin_event.go index e3fbd78f2e..47bbe406cc 100644 --- a/app/plugin_event.go +++ b/app/plugin_event.go @@ -11,7 +11,7 @@ func (s *Server) notifyClusterPluginEvent(event string, data model.PluginEventDa if s.Cluster != nil { s.Cluster.SendClusterMessage(&model.ClusterMessage{ Event: event, - SendType: model.CLUSTER_SEND_RELIABLE, + SendType: model.ClusterSendReliable, WaitForAllToSend: true, Data: data.ToJson(), }) diff --git a/app/plugin_install.go b/app/plugin_install.go index 0aade1809e..e7c37fe954 100644 --- a/app/plugin_install.go +++ b/app/plugin_install.go @@ -170,7 +170,7 @@ func (s *Server) installPlugin(pluginFile, signature io.ReadSeeker, installation } s.notifyClusterPluginEvent( - model.CLUSTER_EVENT_INSTALL_PLUGIN, + model.ClusterEventInstallPlugin, model.PluginEventData{ Id: manifest.Id, }, @@ -444,7 +444,7 @@ func (s *Server) removePlugin(id string) *model.AppError { } s.notifyClusterPluginEvent( - model.CLUSTER_EVENT_REMOVE_PLUGIN, + model.ClusterEventRemovePlugin, model.PluginEventData{ Id: id, }, diff --git a/app/plugin_requests.go b/app/plugin_requests.go index 9144e4d2b4..caaa0811ef 100644 --- a/app/plugin_requests.go +++ b/app/plugin_requests.go @@ -125,12 +125,12 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand } cookieAuth := false - authHeader := r.Header.Get(model.HEADER_AUTH) - if strings.HasPrefix(strings.ToUpper(authHeader), model.HEADER_BEARER+" ") { - token = authHeader[len(model.HEADER_BEARER)+1:] - } else if strings.HasPrefix(strings.ToLower(authHeader), model.HEADER_TOKEN+" ") { - token = authHeader[len(model.HEADER_TOKEN)+1:] - } else if cookie, _ := r.Cookie(model.SESSION_COOKIE_TOKEN); cookie != nil { + authHeader := r.Header.Get(model.HeaderAuth) + if strings.HasPrefix(strings.ToUpper(authHeader), model.HeaderBearer+" ") { + token = authHeader[len(model.HeaderBearer)+1:] + } else if strings.HasPrefix(strings.ToLower(authHeader), model.HeaderToken+" ") { + token = authHeader[len(model.HeaderToken)+1:] + } else if cookie, _ := r.Cookie(model.SessionCookieToken); cookie != nil { token = cookie.Value cookieAuth = true } else { @@ -150,14 +150,14 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand if session != nil && err == nil && cookieAuth && r.Method != "GET" { sentToken := "" - if r.Header.Get(model.HEADER_CSRF_TOKEN) == "" { + if r.Header.Get(model.HeaderCsrfToken) == "" { bodyBytes, _ := ioutil.ReadAll(r.Body) r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) r.ParseForm() sentToken = r.FormValue("csrf") r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) } else { - sentToken = r.Header.Get(model.HEADER_CSRF_TOKEN) + sentToken = r.Header.Get(model.HeaderCsrfToken) } expectedToken := session.GetCSRF() @@ -167,7 +167,7 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand } // ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657) - if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML && !csrfCheckPassed { + if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml && !csrfCheckPassed { csrfErrorMessage := "CSRF Check failed for request - Please migrate your plugin to either send a CSRF Header or Form Field, XMLHttpRequest is deprecated" sid := "" userID := "" @@ -204,11 +204,11 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand cookies := r.Cookies() r.Header.Del("Cookie") for _, c := range cookies { - if c.Name != model.SESSION_COOKIE_TOKEN { + if c.Name != model.SessionCookieToken { r.AddCookie(c) } } - r.Header.Del(model.HEADER_AUTH) + r.Header.Del(model.HeaderAuth) r.Header.Del("Referer") params := mux.Vars(r) diff --git a/app/plugin_statuses.go b/app/plugin_statuses.go index 17e335266f..ab9e2e8f5c 100644 --- a/app/plugin_statuses.go +++ b/app/plugin_statuses.go @@ -99,7 +99,7 @@ func (s *Server) notifyPluginStatusesChanged() error { } // Notify any system admins. - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventPluginStatusesChanged, "", "", "", nil) message.Add("plugin_statuses", pluginStatuses) message.GetBroadcast().ContainsSensitiveData = true s.Publish(message) diff --git a/app/plugin_test.go b/app/plugin_test.go index 169406ea4b..f3a98e9eba 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -476,7 +476,7 @@ func TestPluginSync(t *testing.T) { { "local", func(cfg *model.Config) { - cfg.FileSettings.DriverName = model.NewString(model.IMAGE_DRIVER_LOCAL) + cfg.FileSettings.DriverName = model.NewString(model.ImageDriverLocal) }, }, { @@ -493,10 +493,10 @@ func TestPluginSync(t *testing.T) { } s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port) - cfg.FileSettings.DriverName = model.NewString(model.IMAGE_DRIVER_S3) - cfg.FileSettings.AmazonS3AccessKeyId = model.NewString(model.MINIO_ACCESS_KEY) - cfg.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.MINIO_SECRET_KEY) - cfg.FileSettings.AmazonS3Bucket = model.NewString(model.MINIO_BUCKET) + cfg.FileSettings.DriverName = model.NewString(model.ImageDriverS3) + cfg.FileSettings.AmazonS3AccessKeyId = model.NewString(model.MinioAccessKey) + cfg.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.MinioSecretKey) + cfg.FileSettings.AmazonS3Bucket = model.NewString(model.MinioBucket) cfg.FileSettings.AmazonS3PathPrefix = model.NewString("") cfg.FileSettings.AmazonS3Endpoint = model.NewString(s3Endpoint) cfg.FileSettings.AmazonS3Region = model.NewString("") diff --git a/app/post.go b/app/post.go index 95811b66fa..8831d0b849 100644 --- a/app/post.go +++ b/app/post.go @@ -37,7 +37,7 @@ func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSess return nil, err } - if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) { + if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -211,13 +211,13 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && !post.IsSystemMessage() && - channel.Name == model.DEFAULT_CHANNEL && - !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { + channel.Name == model.DefaultChannelName && + !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) { return nil, model.NewAppError("createPost", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden) } var ephemeralPost *model.Post - if post.Type == "" && !a.HasPermissionToChannel(user.Id, channel.Id, model.PERMISSION_USE_CHANNEL_MENTIONS) { + if post.Type == "" && !a.HasPermissionToChannel(user.Id, channel.Id, model.PermissionUseChannelMentions) { mention := post.DisableMentionHighlights() if mention != "" { T := i18n.GetUserTranslations(user.Locale) @@ -227,7 +227,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch ParentId: post.ParentId, ChannelId: channel.Id, Message: T("model.post.channel_notifications_disabled_in_channel.message", model.StringInterface{"ChannelName": channel.Name, "Mention": mention}), - Props: model.StringInterface{model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + Props: model.StringInterface{model.PostPropsMentionHighlightDisabled: true}, } } } @@ -422,7 +422,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A } for _, mentioned := range mentionedChannels { - if mentioned.Type == model.CHANNEL_OPEN { + if mentioned.Type == model.ChannelTypeOpen { team, err := a.Srv().Store.Team().Get(mentioned.TeamId) if err != nil { mlog.Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err)) @@ -442,9 +442,9 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A post.DelProp("channel_mentions") } - matched := model.AT_MENTION_PATTEN.MatchString(post.Message) - if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) { - post.AddProp(model.POST_PROPS_GROUP_HIGHLIGHT_DISABLED, true) + matched := model.AtMentionPattern.MatchString(post.Message) + if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { + post.AddProp(model.PostPropsGroupHighlightDisabled, true) } return nil @@ -470,7 +470,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model return err } - if post.Type != model.POST_AUTO_RESPONDER { // don't respond to an auto-responder + if post.Type != model.PostTypeAutoResponder { // don't respond to an auto-responder a.Srv().Go(func() { _, err := a.SendAutoResponseIfNecessary(c, channel, user, post) if err != nil { @@ -491,7 +491,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model } func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { - post.Type = model.POST_EPHEMERAL + post.Type = model.PostTypeEphemeral // fill in fields which haven't been specified which have sensible defaults if post.Id == "" { @@ -505,7 +505,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { } post.GenerateActionIds() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE, "", post.ChannelId, userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventEphemeralMessage, "", post.ChannelId, userID, nil) post = a.PreparePostForClient(post, true, false) post = model.AddPostActionCookies(post, a.PostActionCookieSecret()) message.Add("post", post.ToJson()) @@ -515,7 +515,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { } func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { - post.Type = model.POST_EPHEMERAL + post.Type = model.PostTypeEphemeral post.UpdateAt = model.GetMillis() if post.GetProps() == nil { @@ -523,7 +523,7 @@ func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { } post.GenerateActionIds() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", post.ChannelId, userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", post.ChannelId, userID, nil) post = a.PreparePostForClient(post, true, false) post = model.AddPostActionCookies(post, a.PostActionCookieSecret()) message.Add("post", post.ToJson()) @@ -536,12 +536,12 @@ func (a *App) DeleteEphemeralPost(userID, postID string) { post := &model.Post{ Id: postID, UserId: userID, - Type: model.POST_EPHEMERAL, + Type: model.PostTypeEphemeral, DeleteAt: model.GetMillis(), UpdateAt: model.GetMillis(), } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", "", userID, nil) message.Add("post", post.ToJson()) a.Publish(message) } @@ -664,7 +664,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) // individually. rpost.IsFollowing = nil - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", rpost.ChannelId, "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", rpost.ChannelId, "", nil) message.Add("post", rpost.ToJson()) a.Publish(message) @@ -689,7 +689,7 @@ func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatc return nil, err } - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_CHANNEL_MENTIONS) { + if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { patch.DisableMentionHighlights() } @@ -1058,12 +1058,12 @@ func (a *App) DeletePost(postID, deleteByID string) (*model.Post, *model.AppErro postData := a.PreparePostForClient(post, false, false).ToJson() - userMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", post.ChannelId, "", nil) + userMessage := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", post.ChannelId, "", nil) userMessage.Add("post", postData) userMessage.GetBroadcast().ContainsSanitizedData = true a.Publish(userMessage) - adminMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", post.ChannelId, "", nil) + adminMessage := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", post.ChannelId, "", nil) adminMessage.Add("post", postData) adminMessage.Add("delete_by", deleteByID) adminMessage.GetBroadcast().ContainsSensitiveData = true @@ -1082,7 +1082,7 @@ func (a *App) DeletePost(postID, deleteByID string) (*model.Post, *model.AppErro } func (a *App) DeleteFlaggedPosts(postID string) { - if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postID); err != nil { + if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PreferenceCategoryFlaggedPost, postID); err != nil { mlog.Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err)) return } @@ -1346,7 +1346,7 @@ func (a *App) ImageProxyRemover() (f func(string) string) { func (s *Server) MaxPostSize() int { maxPostSize := s.Store.Post().GetMaxPostSize() if maxPostSize == 0 { - return model.POST_MESSAGE_MAX_RUNES_V1 + return model.PostMessageMaxRunesV1 } return maxPostSize @@ -1367,7 +1367,7 @@ func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID str map[string][]string{}, user, map[string]string{}, - &model.Status{Status: model.STATUS_ONLINE}, // Assume the user is online since they would've triggered this + &model.Status{Status: model.StatusOnline}, // Assume the user is online since they would've triggered this true, // Assume channel mentions are always allowed for simplicity ) @@ -1378,7 +1378,7 @@ func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID str count := 0 - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { // In a DM channel, every post made by the other user is a mention otherId := channel.GetOtherUserIdForDM(user.Id) for _, p := range posts { @@ -1424,7 +1424,7 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, in return 0, 0, err } - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { // In a DM channel, every post made by the other user is a mention count, countRoot, nErr := a.Srv().Store.Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id)) if nErr != nil { @@ -1443,11 +1443,11 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, in map[string][]string{}, user, channelMember.NotifyProps, - &model.Status{Status: model.STATUS_ONLINE}, // Assume the user is online since they would've triggered this + &model.Status{Status: model.StatusOnline}, // Assume the user is online since they would've triggered this true, // Assume channel mentions are always allowed for simplicity ) - commentMentions := user.NotifyProps[model.COMMENTS_NOTIFY_PROP] - checkForCommentMentions := commentMentions == model.COMMENTS_NOTIFY_ROOT || commentMentions == model.COMMENTS_NOTIFY_ANY + commentMentions := user.NotifyProps[model.CommentsNotifyProp] + checkForCommentMentions := commentMentions == model.CommentsNotifyRoot || commentMentions == model.CommentsNotifyAny // A mapping of thread root IDs to whether or not a post in that thread mentions the user mentionedByThread := make(map[string]bool) @@ -1513,7 +1513,7 @@ func isCommentMention(user *model.User, post *model.Post, otherPosts map[string] mentioned := otherPosts[post.RootId].UserId == user.Id // Or because they commented on it before this post - if !mentioned && user.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY { + if !mentioned && user.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyAny { for _, otherPost := range otherPosts { if otherPost.Id == post.Id { continue @@ -1548,8 +1548,8 @@ func isPostMention(user *model.User, post *model.Post, keywords map[string][]str } // Check for mentions caused by being added to the channel - if post.Type == model.POST_ADD_TO_CHANNEL { - if addedUserId, ok := post.GetProp(model.POST_PROPS_ADDED_USER_ID).(string); ok && addedUserId == user.Id { + if post.Type == model.PostTypeAddToChannel { + if addedUserId, ok := post.GetProp(model.PostPropsAddedUserId).(string); ok && addedUserId == user.Id { return true } } diff --git a/app/post_metadata.go b/app/post_metadata.go index ad3107da6e..48f23d9fdc 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -68,7 +68,7 @@ func (a *App) PreparePostListForClient(originalList *model.PostList) *model.Post // OverrideIconURLIfEmoji changes the post icon override URL prop, if it has an emoji icon, // so that it points to the URL (relative) of the emoji - static if emoji is default, /api if custom. func (a *App) OverrideIconURLIfEmoji(post *model.Post) { - prop, ok := post.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI] + prop, ok := post.GetProps()[model.PostPropsOverrideIconEmoji] if !ok || prop == nil { return } @@ -85,7 +85,7 @@ func (a *App) OverrideIconURLIfEmoji(post *model.Post) { emojiName = strings.ReplaceAll(emojiName, ":", "") if emojiUrl, err := a.GetEmojiStaticUrl(emojiName); err == nil { - post.AddProp(model.POST_PROPS_OVERRIDE_ICON_URL, emojiUrl) + post.AddProp(model.PostPropsOverrideIconUrl, emojiUrl) } else { mlog.Warn("Failed to retrieve URL for overridden profile icon (emoji)", mlog.String("emojiName", emojiName), mlog.Err(err)) } @@ -167,7 +167,7 @@ func (a *App) getEmojisAndReactionsForPost(post *model.Post) ([]*model.Emoji, [] func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool) (*model.PostEmbed, error) { if _, ok := post.GetProps()["attachments"]; ok { return &model.PostEmbed{ - Type: model.POST_EMBED_MESSAGE_ATTACHMENT, + Type: model.PostEmbedMessageAttachment, }, nil } @@ -182,7 +182,7 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool if og != nil { return &model.PostEmbed{ - Type: model.POST_EMBED_OPENGRAPH, + Type: model.PostEmbedOpengraph, URL: firstLink, Data: og, }, nil @@ -191,13 +191,13 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool if image != nil { // Note that we're not passing the image info here since it'll be part of the PostMetadata.Images field return &model.PostEmbed{ - Type: model.POST_EMBED_IMAGE, + Type: model.PostEmbedImage, URL: firstLink, }, nil } return &model.PostEmbed{ - Type: model.POST_EMBED_LINK, + Type: model.PostEmbedLink, URL: firstLink, }, nil } @@ -207,14 +207,14 @@ func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost b for _, embed := range post.Metadata.Embeds { switch embed.Type { - case model.POST_EMBED_IMAGE: + case model.PostEmbedImage: // These dimensions will generally be cached by a previous call to getEmbedForPost imageURLs = append(imageURLs, embed.URL) - case model.POST_EMBED_MESSAGE_ATTACHMENT: + case model.PostEmbedMessageAttachment: imageURLs = append(imageURLs, a.getImagesInMessageAttachments(post)...) - case model.POST_EMBED_OPENGRAPH: + case model.PostEmbedOpengraph: for _, image := range embed.Data.(*opengraph.OpenGraph).Images { var imageURL string if image.SecureURL != "" { @@ -250,7 +250,7 @@ func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost b } func getEmojiNamesForString(s string) []string { - names := model.EMOJI_PATTERN.FindAllString(s, -1) + names := model.EmojiPattern.FindAllString(s, -1) for i, name := range names { names[i] = strings.Trim(name, ":") @@ -503,13 +503,13 @@ func (a *App) saveLinkMetadataToDatabase(requestURL string, timestamp int64, og } if og != nil { - metadata.Type = model.LINK_METADATA_TYPE_OPENGRAPH + metadata.Type = model.LinkMetadataTypeOpengraph metadata.Data = og } else if image != nil { - metadata.Type = model.LINK_METADATA_TYPE_IMAGE + metadata.Type = model.LinkMetadataTypeImage metadata.Data = image } else { - metadata.Type = model.LINK_METADATA_TYPE_NONE + metadata.Type = model.LinkMetadataTypeNone } _, err := a.Srv().Store.LinkMetadata().Save(metadata) diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index 0b71b1c090..63100d6338 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -297,8 +297,8 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) - post.AddProp(model.POST_PROPS_OVERRIDE_ICON_URL, url) - post.AddProp(model.POST_PROPS_OVERRIDE_ICON_EMOJI, emoji) + post.AddProp(model.PostPropsOverrideIconUrl, url) + post.AddProp(model.PostPropsOverrideIconEmoji, emoji) return th.App.PreparePostForClient(post, false, false) } @@ -310,10 +310,10 @@ func TestPreparePostForClient(t *testing.T) { t.Run("does not override icon URL", func(t *testing.T) { clientPost := prepare(false, url, emoji) - s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] assert.True(t, ok) assert.EqualValues(t, url, s) - s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI] + s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] assert.True(t, ok) assert.EqualValues(t, emoji, s) }) @@ -321,10 +321,10 @@ func TestPreparePostForClient(t *testing.T) { t.Run("overrides icon URL", func(t *testing.T) { clientPost := prepare(true, url, emoji) - s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] assert.True(t, ok) assert.EqualValues(t, overridenUrl, s) - s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI] + s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] assert.True(t, ok) assert.EqualValues(t, emoji, s) }) @@ -333,10 +333,10 @@ func TestPreparePostForClient(t *testing.T) { colonEmoji := ":basketball:" clientPost := prepare(true, url, colonEmoji) - s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL] + s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl] assert.True(t, ok) assert.EqualValues(t, overridenUrl, s) - s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI] + s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji] assert.True(t, ok) assert.EqualValues(t, colonEmoji, s) }) @@ -384,7 +384,7 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) // this value expected to be a string - post.AddProp(model.POST_PROPS_OVERRIDE_ICON_EMOJI, true) + post.AddProp(model.PostPropsOverrideIconEmoji, true) require.NotPanics(t, func() { _ = th.App.PreparePostForClient(post, false, false) @@ -424,7 +424,7 @@ func TestPreparePostForClient(t *testing.T) { t.Run("populates embeds", func(t *testing.T) { assert.ElementsMatch(t, []*model.PostEmbed{ { - Type: model.POST_EMBED_IMAGE, + Type: model.PostEmbedImage, URL: server.URL + "/test-image2.png", }, }, clientPost.Metadata.Embeds) @@ -457,7 +457,7 @@ func TestPreparePostForClient(t *testing.T) { ogData := firstEmbed.Data.(*opengraph.OpenGraph) t.Run("populates embeds", func(t *testing.T) { - assert.Equal(t, firstEmbed.Type, model.POST_EMBED_OPENGRAPH) + assert.Equal(t, firstEmbed.Type, model.PostEmbedOpengraph) assert.Equal(t, firstEmbed.URL, server.URL) assert.Equal(t, ogData.Description, "Contribute to hmhealey/test-files development by creating an account on GitHub.") assert.Equal(t, ogData.SiteName, "GitHub") @@ -500,7 +500,7 @@ func TestPreparePostForClient(t *testing.T) { t.Run("populates embeds", func(t *testing.T) { assert.ElementsMatch(t, []*model.PostEmbed{ { - Type: model.POST_EMBED_MESSAGE_ATTACHMENT, + Type: model.PostEmbedMessageAttachment, }, }, clientPost.Metadata.Embeds) }) @@ -644,7 +644,7 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) { require.Len(t, embeds, 1, "should have one embed") embed := embeds[0] - assert.Equal(t, model.POST_EMBED_OPENGRAPH, embed.Type, "embed type should be OpenGraph") + assert.Equal(t, model.PostEmbedOpengraph, embed.Type, "embed type should be OpenGraph") assert.Equal(t, server.URL, embed.URL, "embed URL should be correct") og, ok := embed.Data.(*opengraph.OpenGraph) @@ -718,7 +718,7 @@ func TestGetEmbedForPost(t *testing.T) { }, "", false) assert.Equal(t, &model.PostEmbed{ - Type: model.POST_EMBED_MESSAGE_ATTACHMENT, + Type: model.PostEmbedMessageAttachment, }, embed) assert.NoError(t, err) }) @@ -727,7 +727,7 @@ func TestGetEmbedForPost(t *testing.T) { embed, err := th.App.getEmbedForPost(&model.Post{}, imageURL, false) assert.Equal(t, &model.PostEmbed{ - Type: model.POST_EMBED_IMAGE, + Type: model.PostEmbedImage, URL: imageURL, }, embed) assert.NoError(t, err) @@ -737,7 +737,7 @@ func TestGetEmbedForPost(t *testing.T) { embed, err := th.App.getEmbedForPost(&model.Post{}, ogURL, false) assert.Equal(t, &model.PostEmbed{ - Type: model.POST_EMBED_OPENGRAPH, + Type: model.PostEmbedOpengraph, URL: ogURL, Data: &opengraph.OpenGraph{ Title: "Title", @@ -750,7 +750,7 @@ func TestGetEmbedForPost(t *testing.T) { embed, err := th.App.getEmbedForPost(&model.Post{}, otherURL, false) assert.Equal(t, &model.PostEmbed{ - Type: model.POST_EMBED_LINK, + Type: model.PostEmbedLink, URL: otherURL, }, embed) assert.NoError(t, err) @@ -778,7 +778,7 @@ func TestGetEmbedForPost(t *testing.T) { }, "", false) assert.Equal(t, &model.PostEmbed{ - Type: model.POST_EMBED_MESSAGE_ATTACHMENT, + Type: model.PostEmbedMessageAttachment, }, embed) assert.NoError(t, err) }) @@ -890,7 +890,7 @@ func TestGetImagesForPost(t *testing.T) { Metadata: &model.PostMetadata{ Embeds: []*model.PostEmbed{ { - Type: model.POST_EMBED_OPENGRAPH, + Type: model.PostEmbedOpengraph, URL: ogURL, Data: &opengraph.OpenGraph{ Images: []*opengraph.Image{ @@ -944,7 +944,7 @@ func TestGetImagesForPost(t *testing.T) { Metadata: &model.PostMetadata{ Embeds: []*model.PostEmbed{ { - Type: model.POST_EMBED_OPENGRAPH, + Type: model.PostEmbedOpengraph, URL: ogURL, Data: &opengraph.OpenGraph{ Images: []*opengraph.Image{ @@ -997,7 +997,7 @@ func TestGetImagesForPost(t *testing.T) { Metadata: &model.PostMetadata{ Embeds: []*model.PostEmbed{ { - Type: model.POST_EMBED_OPENGRAPH, + Type: model.PostEmbedOpengraph, URL: ogURL, Data: &opengraph.OpenGraph{ Images: []*opengraph.Image{ diff --git a/app/post_test.go b/app/post_test.go index 6de58a6aa1..5607f6ebc5 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -414,7 +414,7 @@ func TestPostChannelMentions(t *testing.T) { channelToMention, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "Mention Test", Name: "mention-test", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, }, false) require.Nil(t, err) @@ -484,7 +484,7 @@ func TestImageProxy(t *testing.T) { ProxiedRemovedImageURL string }{ "atmos/camo": { - ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO, + ProxyType: model.ImageProxyTypeAtmosCamo, ProxyURL: "https://127.0.0.1", ProxyOptions: "foo", ImageURL: "http://mydomain.com/myimage", @@ -492,7 +492,7 @@ func TestImageProxy(t *testing.T) { ProxiedImageURL: "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage", }, "atmos/camo_SameSite": { - ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO, + ProxyType: model.ImageProxyTypeAtmosCamo, ProxyURL: "https://127.0.0.1", ProxyOptions: "foo", ImageURL: "http://mymattermost.com/myimage", @@ -500,7 +500,7 @@ func TestImageProxy(t *testing.T) { ProxiedImageURL: "http://mymattermost.com/myimage", }, "atmos/camo_PathOnly": { - ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO, + ProxyType: model.ImageProxyTypeAtmosCamo, ProxyURL: "https://127.0.0.1", ProxyOptions: "foo", ImageURL: "/myimage", @@ -508,7 +508,7 @@ func TestImageProxy(t *testing.T) { ProxiedImageURL: "http://mymattermost.com/myimage", }, "atmos/camo_EmptyImageURL": { - ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO, + ProxyType: model.ImageProxyTypeAtmosCamo, ProxyURL: "https://127.0.0.1", ProxyOptions: "foo", ImageURL: "", @@ -516,25 +516,25 @@ func TestImageProxy(t *testing.T) { ProxiedImageURL: "", }, "local": { - ProxyType: model.IMAGE_PROXY_TYPE_LOCAL, + ProxyType: model.ImageProxyTypeLocal, ImageURL: "http://mydomain.com/myimage", ProxiedRemovedImageURL: "http://mydomain.com/myimage", ProxiedImageURL: "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage", }, "local_SameSite": { - ProxyType: model.IMAGE_PROXY_TYPE_LOCAL, + ProxyType: model.ImageProxyTypeLocal, ImageURL: "http://mymattermost.com/myimage", ProxiedRemovedImageURL: "http://mymattermost.com/myimage", ProxiedImageURL: "http://mymattermost.com/myimage", }, "local_PathOnly": { - ProxyType: model.IMAGE_PROXY_TYPE_LOCAL, + ProxyType: model.ImageProxyTypeLocal, ImageURL: "/myimage", ProxiedRemovedImageURL: "http://mymattermost.com/myimage", ProxiedImageURL: "http://mymattermost.com/myimage", }, "local_EmptyImageURL": { - ProxyType: model.IMAGE_PROXY_TYPE_LOCAL, + ProxyType: model.ImageProxyTypeLocal, ImageURL: "", ProxiedRemovedImageURL: "", ProxiedImageURL: "", @@ -585,7 +585,7 @@ func TestMaxPostSize(t *testing.T) { { "Max post size less than model.model.POST_MESSAGE_MAX_RUNES_V1 ", 0, - model.POST_MESSAGE_MAX_RUNES_V1, + model.PostMessageMaxRunesV1, }, { "4000 rune limit", @@ -730,8 +730,8 @@ func TestCreatePost(t *testing.T) { }) t.Run("Sets prop when post has mentions and user does not have USE_CHANNEL_MENTIONS", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) postWithNoMention := &model.Post{ ChannelId: th.BasicChannel.Id, @@ -749,10 +749,10 @@ func TestCreatePost(t *testing.T) { } rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true) require.Nil(t, err) - assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true) + assert.Equal(t, rpost.GetProp(model.PostPropsMentionHighlightDisabled), true) - th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) }) }) } @@ -824,8 +824,8 @@ func TestPatchPost(t *testing.T) { }) t.Run("Sets prop when user does not have USE_CHANNEL_MENTIONS", func(t *testing.T) { - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch still does not have a mention")} rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention) @@ -836,10 +836,10 @@ func TestPatchPost(t *testing.T) { rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention) require.Nil(t, err) - assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true) + assert.Equal(t, rpost.GetProp(model.PostPropsMentionHighlightDisabled), true) - th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) + th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) + th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) }) }) } @@ -1246,7 +1246,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP] = "apple" + user2.NotifyProps[model.MentionKeysNotifyProp] = "apple" post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, @@ -1285,7 +1285,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true" + user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true" post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, @@ -1324,7 +1324,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "false" + user2.NotifyProps[model.ChannelMentionsNotifyProp] = "false" post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, @@ -1361,10 +1361,10 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true" + user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true" _, err := th.App.UpdateChannelMemberNotifyProps(map[string]string{ - model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_ON, + model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn, }, channel.Id, user2.Id) require.Nil(t, err) @@ -1403,7 +1403,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT + user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyRoot post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, @@ -1457,7 +1457,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY + user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, @@ -1515,9 +1515,9 @@ func TestCountMentionsFromPost(t *testing.T) { UserId: user1.Id, ChannelId: channel.Id, Message: "test", - Type: model.POST_ADD_TO_CHANNEL, + Type: model.PostTypeAddToChannel, Props: map[string]interface{}{ - model.POST_PROPS_ADDED_USER_ID: model.NewId(), + model.PostPropsAddedUserId: model.NewId(), }, }, channel, false, true) require.Nil(t, err) @@ -1525,9 +1525,9 @@ func TestCountMentionsFromPost(t *testing.T) { UserId: user1.Id, ChannelId: channel.Id, Message: "test2", - Type: model.POST_ADD_TO_CHANNEL, + Type: model.PostTypeAddToChannel, Props: map[string]interface{}{ - model.POST_PROPS_ADDED_USER_ID: user2.Id, + model.PostPropsAddedUserId: user2.Id, }, }, channel, false, true) require.Nil(t, err) @@ -1535,9 +1535,9 @@ func TestCountMentionsFromPost(t *testing.T) { UserId: user1.Id, ChannelId: channel.Id, Message: "test3", - Type: model.POST_ADD_TO_CHANNEL, + Type: model.PostTypeAddToChannel, Props: map[string]interface{}{ - model.POST_PROPS_ADDED_USER_ID: user2.Id, + model.PostPropsAddedUserId: user2.Id, }, }, channel, false, true) require.Nil(t, err) @@ -1663,7 +1663,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY + user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, @@ -1931,7 +1931,7 @@ func TestFollowThreadSkipsParticipants(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) channel := th.BasicChannel @@ -1989,7 +1989,7 @@ func TestAutofollowBasedOnRootPost(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) channel := th.BasicChannel @@ -2019,7 +2019,7 @@ func TestViewChannelShouldNotUpdateThreads(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) channel := th.BasicChannel @@ -2052,7 +2052,7 @@ func TestCollapsedThreadFetch(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) user1 := th.BasicUser user2 := th.BasicUser2 @@ -2144,8 +2144,8 @@ func TestReplyToPostWithLag(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - if *th.App.Srv().Config().SqlSettings.DriverName != model.DATABASE_DRIVER_MYSQL { - t.Skipf("requires %q database driver", model.DATABASE_DRIVER_MYSQL) + if *th.App.Srv().Config().SqlSettings.DriverName != model.DatabaseDriverMysql { + t.Skipf("requires %q database driver", model.DatabaseDriverMysql) } mainHelper.SQLStore.UpdateLicense(model.NewTestLicense("somelicense")) @@ -2268,7 +2268,7 @@ func TestAutofollowOnPostingAfterUnfollow(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) channel := th.BasicChannel diff --git a/app/preference.go b/app/preference.go index 03493531c0..7a2b80d53a 100644 --- a/app/preference.go +++ b/app/preference.go @@ -60,11 +60,11 @@ func (a *App) UpdatePreferences(userID string, preferences model.Preferences) *m return model.NewAppError("UpdatePreferences", "api.preference.update_preferences.update_sidebar.app_error", nil, err.Error(), http.StatusInternalServerError) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, "", "", userID, nil) // TODO this needs to be updated to include information on which categories changed a.Publish(message) - message = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCES_CHANGED, "", "", userID, nil) + message = model.NewWebSocketEvent(model.WebsocketEventPreferencesChanged, "", "", userID, nil) message.Add("preferences", preferences.ToJson()) a.Publish(message) @@ -90,11 +90,11 @@ func (a *App) DeletePreferences(userID string, preferences model.Preferences) *m return model.NewAppError("DeletePreferences", "api.preference.delete_preferences.update_sidebar.app_error", nil, err.Error(), http.StatusInternalServerError) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, "", "", userID, nil) // TODO this needs to be updated to include information on which categories changed a.Publish(message) - message = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCES_DELETED, "", "", userID, nil) + message = model.NewWebSocketEvent(model.WebsocketEventPreferencesDeleted, "", "", userID, nil) message.Add("preferences", preferences.ToJson()) a.Publish(message) diff --git a/app/product_notices.go b/app/product_notices.go index 91c0e6139b..6065417762 100644 --- a/app/product_notices.go +++ b/app/product_notices.go @@ -68,7 +68,7 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS // check if client version is in notice range clientVersions := cnd.DesktopVersion - if client == model.NoticeClientType_MobileAndroid || client == model.NoticeClientType_MobileIos { + if client == model.NoticeClientTypeMobileAndroid || client == model.NoticeClientTypeMobileIos { clientVersions = cnd.MobileVersion } @@ -155,7 +155,7 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS } switch cnd.DeprecatingDependency.Name { - case model.DATABASE_DRIVER_MYSQL, model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverMysql, model.DatabaseDriverPostgres: if dbName != cnd.DeprecatingDependency.Name { return false, nil } @@ -164,8 +164,8 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS return false, errors.Wrapf(err, "Cannot parse DBMS version %s", dbVer) } return extDepVersion.GreaterThan(serverDBMSVersion), nil - case model.SEARCHENGINE_ELASTICSEARCH: - if searchEngineName != model.SEARCHENGINE_ELASTICSEARCH { + case model.SearchengineElasticsearch: + if searchEngineName != model.SearchengineElasticsearch { return false, nil } semverESVersion, err := semver.NewVersion(searchEngineVer) @@ -239,8 +239,8 @@ func validateConfigEntry(conf *model.Config, path string, expectedValue interfac // GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller func (a *App) GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) { - isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM) - isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PERMISSION_MANAGE_TEAM) + isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PermissionManageSystem) + isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PermissionManageTeam) // check if notices for regular users are disabled if !*a.Srv().Config().AnnouncementSettings.UserNoticesEnabled && !isSystemAdmin { diff --git a/app/product_notices_test.go b/app/product_notices_test.go index 6f6a184c23..267ebda2e1 100644 --- a/app/product_notices_test.go +++ b/app/product_notices_test.go @@ -101,7 +101,7 @@ func TestNoticeValidation(t *testing.T) { notice: &model.ProductNotice{ Conditions: model.Conditions{ - ClientType: model.NewNoticeClientType(model.NoticeClientType_Mobile), + ClientType: model.NewNoticeClientType(model.NoticeClientTypeMobile), }, }, }, @@ -396,7 +396,7 @@ func TestNoticeValidation(t *testing.T) { systemAdmin: true, notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_Sysadmin), + Audience: model.NewNoticeAudience(model.NoticeAudienceSysadmin), }, }, }, @@ -409,7 +409,7 @@ func TestNoticeValidation(t *testing.T) { systemAdmin: false, notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_Sysadmin), + Audience: model.NewNoticeAudience(model.NoticeAudienceSysadmin), }, }, }, @@ -422,7 +422,7 @@ func TestNoticeValidation(t *testing.T) { teamAdmin: true, notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_TeamAdmin), + Audience: model.NewNoticeAudience(model.NoticeAudienceTeamAdmin), }, }, }, @@ -435,7 +435,7 @@ func TestNoticeValidation(t *testing.T) { teamAdmin: false, notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_TeamAdmin), + Audience: model.NewNoticeAudience(model.NoticeAudienceTeamAdmin), }, }, }, @@ -447,7 +447,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_Member), + Audience: model.NewNoticeAudience(model.NoticeAudienceMember), }, }, }, @@ -460,7 +460,7 @@ func TestNoticeValidation(t *testing.T) { systemAdmin: true, notice: &model.ProductNotice{ Conditions: model.Conditions{ - Audience: model.NewNoticeAudience(model.NoticeAudience_Member), + Audience: model.NewNoticeAudience(model.NoticeAudienceMember), }, }, }, @@ -473,7 +473,7 @@ func TestNoticeValidation(t *testing.T) { sku: "e20", notice: &model.ProductNotice{ Conditions: model.Conditions{ - Sku: model.NewNoticeSKU(model.NoticeSKU_E20), + Sku: model.NewNoticeSKU(model.NoticeSKUE20), }, }, }, @@ -486,7 +486,7 @@ func TestNoticeValidation(t *testing.T) { sku: "e20", notice: &model.ProductNotice{ Conditions: model.Conditions{ - Sku: model.NewNoticeSKU(model.NoticeSKU_E10), + Sku: model.NewNoticeSKU(model.NoticeSKUE10), }, }, }, @@ -499,7 +499,7 @@ func TestNoticeValidation(t *testing.T) { sku: "", notice: &model.ProductNotice{ Conditions: model.Conditions{ - Sku: model.NewNoticeSKU(model.NoticeSKU_Team), + Sku: model.NewNoticeSKU(model.NoticeSKUTeam), }, }, }, @@ -511,7 +511,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - Sku: model.NewNoticeSKU(model.NoticeSKU_All), + Sku: model.NewNoticeSKU(model.NoticeSKUAll), }, }, }, @@ -524,7 +524,7 @@ func TestNoticeValidation(t *testing.T) { cloud: true, notice: &model.ProductNotice{ Conditions: model.Conditions{ - InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceType_Cloud), + InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceTypeCloud), }, }, }, @@ -536,7 +536,7 @@ func TestNoticeValidation(t *testing.T) { args: args{ notice: &model.ProductNotice{ Conditions: model.Conditions{ - InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceType_Both), + InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceTypeBoth), }, }, }, @@ -719,7 +719,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them for specified user - messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 1) @@ -728,7 +728,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them again, see that none are returned - messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 0) @@ -747,7 +747,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them again, since conditions don't match we should be zero - messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 0) diff --git a/app/ratelimit_test.go b/app/ratelimit_test.go index 00126fc59d..82f1cc14d2 100644 --- a/app/ratelimit_test.go +++ b/app/ratelimit_test.go @@ -73,7 +73,7 @@ func TestGenerateKey(t *testing.T) { req := httptest.NewRequest("GET", "/", nil) if tc.authTokenResult != "" { req.AddCookie(&http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: tc.authTokenResult, }) } diff --git a/app/reaction.go b/app/reaction.go index c699ffc023..1e33eecd96 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -27,14 +27,14 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden) } - if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DefaultChannelName { var user *model.User user, err = a.GetUser(reaction.UserId) if err != nil { return nil, err } - if !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { + if !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) { return nil, model.NewAppError("saveReactionForPost", "api.reaction.town_square_read_only", nil, "", http.StatusForbidden) } } @@ -64,7 +64,7 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) } a.Srv().Go(func() { - a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, reaction, post) + a.sendReactionEvent(model.WebsocketEventReactionAdded, reaction, post) }) return reaction, nil @@ -121,13 +121,13 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction return model.NewAppError("DeleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden) } - if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DefaultChannelName { user, err := a.GetUser(reaction.UserId) if err != nil { return err } - if !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { + if !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) { return model.NewAppError("DeleteReactionForPost", "api.reaction.town_square_read_only", nil, "", http.StatusForbidden) } } @@ -150,7 +150,7 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction } a.Srv().Go(func() { - a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, reaction, post) + a.sendReactionEvent(model.WebsocketEventReactionRemoved, reaction, post) }) return nil diff --git a/app/role.go b/app/role.go index d6640150d6..70d92b7c9b 100644 --- a/app/role.go +++ b/app/role.go @@ -163,9 +163,9 @@ func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) { } builtInChannelRoles := []string{ - model.CHANNEL_GUEST_ROLE_ID, - model.CHANNEL_USER_ROLE_ID, - model.CHANNEL_ADMIN_ROLE_ID, + model.ChannelGuestRoleId, + model.ChannelUserRoleId, + model.ChannelAdminRoleId, } builtInRolesMinusChannelRoles := append(utils.RemoveStringsFromSlice(model.BuiltInSchemeManagedRoleIDs, builtInChannelRoles...), model.NewSystemRoleIDs...) @@ -239,7 +239,7 @@ func (a *App) CheckRolesExist(roleNames []string) *model.AppError { } func (a *App) sendUpdatedRoleEvent(role *model.Role) { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ROLE_UPDATED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventRoleUpdated, "", "", "", nil) message.Add("role", role.ToJson()) a.Srv().Go(func() { diff --git a/app/role_test.go b/app/role_test.go index b3cae19515..d6d06aee13 100644 --- a/app/role_test.go +++ b/app/role_test.go @@ -70,15 +70,15 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th th.App.SetPhase2PermissionsMigrationStatus(true) permissionsDefault := []string{ - model.PERMISSION_MANAGE_CHANNEL_ROLES.Id, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, + model.PermissionManageChannelRoles.Id, + model.PermissionManagePublicChannelMembers.Id, } // Defer resetting the system scheme permissions systemSchemeRoles, err := th.App.GetRolesByNames([]string{ - model.CHANNEL_GUEST_ROLE_ID, - model.CHANNEL_USER_ROLE_ID, - model.CHANNEL_ADMIN_ROLE_ID, + model.ChannelGuestRoleId, + model.ChannelUserRoleId, + model.ChannelAdminRoleId, }) require.Nil(t, err) require.Len(t, systemSchemeRoles, 3) @@ -94,7 +94,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th channelScheme, err := th.App.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }) require.Nil(t, err) defer th.App.DeleteScheme(channelScheme.Id) @@ -154,9 +154,9 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th // select the permission to test (moderated or non-moderated) var permission *model.Permission if permissionIsModerated { - permission = model.PERMISSION_CREATE_POST // moderated + permission = model.PermissionCreatePost // moderated } else { - permission = model.PERMISSION_READ_CHANNEL // non-moderated + permission = model.PermissionReadChannel // non-moderated } // add or remove the permission from the higher-scoped scheme @@ -208,13 +208,13 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th } // test 24 combinations where the higher-scoped scheme is the SYSTEM scheme - test(model.CHANNEL_GUEST_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID) + test(model.ChannelGuestRoleId, model.ChannelUserRoleId, model.ChannelAdminRoleId) // create a team scheme teamScheme, err := th.App.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }) require.Nil(t, err) defer th.App.DeleteScheme(teamScheme.Id) diff --git a/app/saml.go b/app/saml.go index 9cf2a2f626..4179bb76ce 100644 --- a/app/saml.go +++ b/app/saml.go @@ -288,7 +288,7 @@ func (a *App) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return } - numAffected, err := a.srv.Store.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, userIDs, includeDeleted, dryRun) + numAffected, err := a.srv.Store.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun) if err != nil { appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.failure_reset_authdata_to_email.app_error", nil, err.Error(), http.StatusInternalServerError) return diff --git a/app/scheme.go b/app/scheme.go index 786984b537..9c77b80f6f 100644 --- a/app/scheme.go +++ b/app/scheme.go @@ -202,7 +202,7 @@ func (s *Server) IsPhase2MigrationCompleted() *model.AppError { return nil } - if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { + if _, err := s.Store.System().GetByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented) } diff --git a/app/searchengine.go b/app/searchengine.go index 8a13fd98de..b1e9adaa70 100644 --- a/app/searchengine.go +++ b/app/searchengine.go @@ -11,7 +11,7 @@ import ( ) func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { - if *cfg.ElasticsearchSettings.Password == model.FAKE_SETTING { + if *cfg.ElasticsearchSettings.Password == model.FakeSetting { if *cfg.ElasticsearchSettings.ConnectionUrl == *a.Config().ElasticsearchSettings.ConnectionUrl && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username { *cfg.ElasticsearchSettings.Password = *a.Config().ElasticsearchSettings.Password } else { diff --git a/app/security_update_check.go b/app/security_update_check.go index ad0c226a72..731f9c562f 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -41,7 +41,7 @@ func (s *Server) DoSecurityUpdateCheck() { return } - lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0) + lastSecurityTime, _ := strconv.ParseInt(props[model.SystemLastSecurityTime], 10, 0) currentTime := model.GetMillis() if (currentTime - lastSecurityTime) > SecurityUpdatePeriod { @@ -55,13 +55,13 @@ func (s *Server) DoSecurityUpdateCheck() { v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName) v.Set(PropSecurityOS, runtime.GOOS) - if props[model.SYSTEM_RAN_UNIT_TESTS] != "" { + if props[model.SystemRanUnitTests] != "" { v.Set(PropSecurityUnitTests, "1") } else { v.Set(PropSecurityUnitTests, "0") } - systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)} + systemSecurityLastTime := &model.System{Name: model.SystemLastSecurityTime, Value: strconv.FormatInt(currentTime, 10)} if lastSecurityTime == 0 { s.Store.System().Save(systemSecurityLastTime) } else { diff --git a/app/server.go b/app/server.go index 5c944aa4d6..e13b5f020e 100644 --- a/app/server.go +++ b/app/server.go @@ -338,7 +338,7 @@ func NewServer(options ...Option) (*Server, error) { return nil, errors.Wrap(err, "Unable to create pending post ids cache") } if s.statusCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{ - Size: model.STATUS_CACHE_SIZE, + Size: model.StatusCacheSize, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }); err != nil { @@ -426,7 +426,7 @@ func NewServer(options ...Option) (*Server, error) { s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) { s.configOrLicenseListener() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventConfigChanged, "", "", "", nil) message.Add("config", s.ClientConfigWithComputed()) s.Go(func() { @@ -436,7 +436,7 @@ func NewServer(options ...Option) (*Server, error) { s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { s.configOrLicenseListener() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventLicenseChanged, "", "", "", nil) message.Add("license", s.GetSanitizedClientLicense()) s.Go(func() { s.Publish(message) @@ -1109,7 +1109,7 @@ func (s *Server) Restart() error { } func (s *Server) isUpgradedFromTE() bool { - val, err := s.Store.System().GetByName(model.SYSTEM_UPGRADED_FROM_TE_ID) + val, err := s.Store.System().GetByName(model.SystemUpgradedFromTeId) if err != nil { return false } @@ -1124,7 +1124,7 @@ func (s *Server) UpgradeToE0() error { if err := upgrader.UpgradeToE0(); err != nil { return err } - upgradedFromTE := &model.System{Name: model.SYSTEM_UPGRADED_FROM_TE_ID, Value: "true"} + upgradedFromTE := &model.System{Name: model.SystemUpgradedFromTeId, Value: "true"} s.Store.System().Save(upgradedFromTE) return nil } @@ -1247,7 +1247,7 @@ func (s *Server) Start() error { addr := *s.Config().ServiceSettings.ListenAddress if addr == "" { - if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { + if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls { addr = ":https" } else { addr = ":http" @@ -1307,7 +1307,7 @@ func (s *Server) Start() error { s.didFinishListen = make(chan struct{}) go func() { var err error - if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { + if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls { tlsConfig := &tls.Config{ PreferServerCipherSuites: true, @@ -1486,7 +1486,7 @@ func (s *Server) runLicenseExpirationCheckJob() { func runReportToAWSMeterJob(s *Server) { model.CreateRecurringTask("Collect and send usage report to AWS Metering Service", func() { doReportUsageToAWSMeteringService(s) - }, time.Hour*model.AWS_METERING_REPORT_INTERVAL) + }, time.Hour*model.AwsMeteringReportInterval) } func doReportUsageToAWSMeteringService(s *Server) { @@ -1496,8 +1496,8 @@ func doReportUsageToAWSMeteringService(s *Server) { return } - dimensions := []string{model.AWS_METERING_DIMENSION_USAGE_HRS} - reports := awsMeter.GetUserCategoryUsage(dimensions, time.Now().UTC(), time.Now().Add(-model.AWS_METERING_REPORT_INTERVAL*time.Hour).UTC()) + dimensions := []string{model.AwsMeteringDimensionUsageHrs} + reports := awsMeter.GetUserCategoryUsage(dimensions, time.Now().UTC(), time.Now().Add(-model.AwsMeteringReportInterval*time.Hour).UTC()) awsMeter.ReportUserCategoryUsage(reports) } @@ -1506,14 +1506,14 @@ func runCheckWarnMetricStatusJob(a *App, c *request.Context) { doCheckWarnMetricStatus(a, c) model.CreateRecurringTask("Check Warn Metric Status Job", func() { doCheckWarnMetricStatus(a, c) - }, time.Hour*model.WARN_METRIC_JOB_INTERVAL) + }, time.Hour*model.WarnMetricJobInterval) } func runCheckAdminSupportStatusJob(a *App, c *request.Context) { doCheckAdminSupportStatus(a, c) model.CreateRecurringTask("Check Admin Support Status Job", func() { doCheckAdminSupportStatus(a, c) - }, time.Hour*model.WARN_METRIC_JOB_INTERVAL) + }, time.Hour*model.WarnMetricJobInterval) } func doSecurity(s *Server) { @@ -1554,10 +1554,10 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { warnMetricStatusFromStore := make(map[string]string) for key, value := range systemDataList { - if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) { + if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) { if _, ok := model.WarnMetricsTable[key]; ok { warnMetricStatusFromStore[key] = value - if value == model.WARN_METRIC_STATUS_ACK { + if value == model.WarnMetricStatusAck { // If any warn metric has already been acked, we return mlog.Debug("Warn metrics have been acked, skip") return @@ -1572,7 +1572,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { } else { currentTime := utils.MillisFromTime(time.Now()) // If the admin advisory has already been shown in the last 7 days - if (currentTime-lastWarnMetricRunTimestamp)/(model.WARN_METRIC_JOB_WAIT_TIME) < 1 { + if (currentTime-lastWarnMetricRunTimestamp)/(model.WarnMetricJobWaitTime) < 1 { mlog.Debug("No advisories should be shown during the wait interval time") return } @@ -1588,7 +1588,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { mlog.Debug("Error attempting to get number of teams.", mlog.Err(err1)) } - openChannelCount, err2 := a.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) + openChannelCount, err2 := a.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) if err2 != nil { mlog.Debug("Error attempting to get number of public channels.", mlog.Err(err2)) } @@ -1604,31 +1604,31 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { warnMetrics := []model.WarnMetric{} - if numberOfActiveUsers < model.WARN_METRIC_NUMBER_OF_ACTIVE_USERS_25 { + if numberOfActiveUsers < model.WarnMetricNumberOfActiveUsers25 { return - } else if teamCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5]) - } else if *a.Config().ServiceSettings.EnableMultifactorAuthentication && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_MFA] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_MFA]) - } else if isDiffEmailAccount && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN]) - } else if openChannelCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50]) + } else if teamCount >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfTeams5].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfTeams5] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfTeams5]) + } else if *a.Config().ServiceSettings.EnableMultifactorAuthentication && warnMetricStatusFromStore[model.SystemWarnMetricMfa] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricMfa]) + } else if isDiffEmailAccount && warnMetricStatusFromStore[model.SystemWarnMetricEmailDomain] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricEmailDomain]) + } else if openChannelCount >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfChannels50].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfChannels50] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfChannels50]) } // If the system did not cross any of the thresholds for the Contextual Advisories if len(warnMetrics) == 0 { - if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100]) - } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200]) - } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300] != model.WARN_METRIC_STATUS_RUNONCE { - warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300]) - } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit { + if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers100].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers100] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers100]) + } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers200] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200]) + } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers300] != model.WarnMetricStatusRunonce { + warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300]) + } else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500].Limit { var tWarnMetric model.WarnMetric - if warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500] != model.WARN_METRIC_STATUS_RUNONCE { - tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500] + if warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers500] != model.WarnMetricStatusRunonce { + tWarnMetric = model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500] } postsCount, err4 := a.Srv().Store.Post().AnalyticsPostCount("", false, false) @@ -1636,8 +1636,8 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { mlog.Debug("Error attempting to get number of posts.", mlog.Err(err4)) } - if postsCount > model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M] != model.WARN_METRIC_STATUS_RUNONCE { - tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M] + if postsCount > model.WarnMetricsTable[model.SystemWarnMetricNumberOfPosts2m].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfPosts2m] != model.WarnMetricStatusRunonce { + tWarnMetric = model.WarnMetricsTable[model.SystemWarnMetricNumberOfPosts2m] } if tWarnMetric != (model.WarnMetric{}) { @@ -1650,7 +1650,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { for _, warnMetric := range warnMetrics { data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id) - if nErr == nil && data != nil && warnMetric.IsBotOnly && data.Value == model.WARN_METRIC_STATUS_RUNONCE { + if nErr == nil && data != nil && warnMetric.IsBotOnly && data.Value == model.WarnMetricStatusRunonce { mlog.Debug("This metric warning is bot only and ran once") continue } @@ -1658,12 +1658,12 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { warnMetricStatus, _ := a.getWarnMetricStatusAndDisplayTextsForId(warnMetric.Id, nil, isE0Edition) if !warnMetric.IsBotOnly { // Banner and bot metric types - send websocket event every interval - message := model.NewWebSocketEvent(model.WEBSOCKET_WARN_METRIC_STATUS_RECEIVED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketWarnMetricStatusReceived, "", "", "", nil) message.Add("warnMetricStatus", warnMetricStatus.ToJson()) a.Publish(message) // Banner and bot metric types, send the bot message only once - if data != nil && data.Value == model.WARN_METRIC_STATUS_RUNONCE { + if data != nil && data.Value == model.WarnMetricStatusRunonce { continue } } @@ -1673,9 +1673,9 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { } if warnMetric.IsRunOnce { - a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_RUNONCE) + a.setWarnMetricsStatusForId(warnMetric.Id, model.WarnMetricStatusRunonce) } else { - a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_LIMIT_REACHED) + a.setWarnMetricsStatusForId(warnMetric.Id, model.WarnMetricStatusLimitReached) } } } @@ -1683,8 +1683,8 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) { func doCheckAdminSupportStatus(a *App, c *request.Context) { isE0Edition := model.BuildEnterpriseReady == "true" - if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL { - if err := a.notifyAdminsOfWarnMetricStatus(c, model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil { + if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SupportSettingsDefaultSupportEmail { + if err := a.notifyAdminsOfWarnMetricStatus(c, model.SystemMetricSupportEmailNotConfigured, isE0Edition); err != nil { mlog.Error("Failed to send notifications to admin users.", mlog.Err(err)) } } @@ -1791,7 +1791,7 @@ func (s *Server) startMetricsServer() { } func (s *Server) sendLicenseUpForRenewalEmail(users map[string]*model.User, license *model.License) *model.AppError { - key := model.LICENSE_UP_FOR_RENEWAL_EMAIL_SENT + license.Id + key := model.LicenseUpForRenewalEmailSent + license.Id if _, err := s.Store.System().GetByName(key); err == nil { // return early because the key already exists and that means we already executed the code below to send email successfully return nil diff --git a/app/server_test.go b/app/server_test.go index 18dbd908c8..12013a8701 100644 --- a/app/server_test.go +++ b/app/server_test.go @@ -66,10 +66,10 @@ func TestReadReplicaDisabledBasedOnLicense(t *testing.T) { cfg.SetDefaults() driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") if driverName == "" { - driverName = model.DATABASE_DRIVER_POSTGRES + driverName = model.DatabaseDriverPostgres } dsn := "" - if driverName == model.DATABASE_DRIVER_POSTGRES { + if driverName == model.DatabaseDriverPostgres { dsn = os.Getenv("TEST_DATABASE_POSTGRESQL_DSN") } else { dsn = os.Getenv("TEST_DATABASE_MYSQL_DSN") @@ -172,9 +172,9 @@ func TestStartServerNoS3Bucket(t *testing.T) { server.configStore = store server.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings = model.FileSettings{ - DriverName: model.NewString(model.IMAGE_DRIVER_S3), - AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY), - AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY), + DriverName: model.NewString(model.ImageDriverS3), + AmazonS3AccessKeyId: model.NewString(model.MinioAccessKey), + AmazonS3SecretAccessKey: model.NewString(model.MinioSecretKey), AmazonS3Bucket: model.NewString("nosuchbucket"), AmazonS3Endpoint: model.NewString(s3Endpoint), AmazonS3Region: model.NewString(""), @@ -707,7 +707,7 @@ func TestAdminAdvisor(t *testing.T) { Username: "vader" + model.NewId(), Password: "passwd1", AuthService: "", - Roles: model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemAdminRoleId, } ruser, err := th.App.CreateUser(th.Context, &user) assert.Nil(t, err, "User should be created") @@ -716,7 +716,7 @@ func TestAdminAdvisor(t *testing.T) { t.Run("Should notify admin of un-configured support email", func(t *testing.T) { doCheckAdminSupportStatus(th.App, th.Context) - bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME) + bot, err := th.App.GetUserByUsername(model.BotWarnMetricBotUsername) assert.NotNil(t, bot, "Bot should have been created now") assert.Nil(t, err, "No error should be generated") @@ -731,7 +731,7 @@ func TestAdminAdvisor(t *testing.T) { m.SupportSettings.SupportEmail = &email }) - bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME) + bot, err := th.App.GetUserByUsername(model.BotWarnMetricBotUsername) assert.NotNil(t, bot, "Bot should be already created") assert.Nil(t, err, "No error should be generated") diff --git a/app/session.go b/app/session.go index 0983f792ee..fd7c77ed90 100644 --- a/app/session.go +++ b/app/session.go @@ -41,7 +41,7 @@ func (a *App) GetCloudSession(token string) (*model.Session, *model.AppError) { IsOAuth: false, } - session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_CLOUD_KEY) + session.AddProp(model.SessionPropType, model.SessionTypeCloudKey) return session, nil } return nil, model.NewAppError("GetCloudSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) @@ -56,7 +56,7 @@ func (a *App) GetRemoteClusterSession(token string, remoteId string) (*model.Ses IsOAuth: false, } - session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_REMOTECLUSTER_TOKEN) + session.AddProp(model.SessionPropType, model.SessionTypeRemoteclusterToken) return session, nil } return nil, model.NewAppError("GetRemoteClusterSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized) @@ -98,7 +98,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { if *a.Config().ServiceSettings.SessionIdleTimeoutInMinutes > 0 && !session.IsOAuth && !session.IsMobileApp() && - session.Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_USER_ACCESS_TOKEN && + session.Props[model.SessionPropType] != model.SessionTypeUserAccessToken && !*a.Config().ServiceSettings.ExtendSessionLengthWithActivity { timeout := int64(*a.Config().ServiceSettings.SessionIdleTimeoutInMinutes) * 1000 * 60 @@ -239,7 +239,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { a.UpdateWebConnUserActivity(session, now) - if now-session.LastActivityAt < model.SESSION_ACTIVITY_TIMEOUT { + if now-session.LastActivityAt < model.SessionActivityTimeout { return } @@ -407,17 +407,17 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio IsOAuth: false, } - session.AddProp(model.SESSION_PROP_USER_ACCESS_TOKEN_ID, token.Id) - session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN) + session.AddProp(model.SessionPropUserAccessTokenId, token.Id) + session.AddProp(model.SessionPropType, model.SessionTypeUserAccessToken) if user.IsBot { - session.AddProp(model.SESSION_PROP_IS_BOT, model.SESSION_PROP_IS_BOT_VALUE) + session.AddProp(model.SessionPropIsBot, model.SessionPropIsBotValue) } if user.IsGuest() { - session.AddProp(model.SESSION_PROP_IS_GUEST, "true") + session.AddProp(model.SessionPropIsGuest, "true") } else { - session.AddProp(model.SESSION_PROP_IS_GUEST, "false") + session.AddProp(model.SessionPropIsGuest, "false") } - a.srv.userService.SetSessionExpireInDays(session, model.SESSION_USER_ACCESS_TOKEN_EXPIRY) + a.srv.userService.SetSessionExpireInDays(session, model.SessionUserAccessTokenExpiry) session, nErr = a.Srv().Store.Session().Save(session) if nErr != nil { diff --git a/app/session_test.go b/app/session_test.go index 9cf00e41be..7e0f313950 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -64,7 +64,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session = &model.Session{ UserId: model.NewId(), } - session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN) + session.AddProp(model.SessionPropType, model.SessionTypeUserAccessToken) session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) @@ -103,48 +103,48 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) { t.Run("Promote Guest to User updates the session", func(t *testing.T) { guest := th.CreateGuest() - session, err := th.App.CreateSession(&model.Session{UserId: guest.Id, Props: model.StringMap{model.SESSION_PROP_IS_GUEST: "true"}}) + session, err := th.App.CreateSession(&model.Session{UserId: guest.Id, Props: model.StringMap{model.SessionPropIsGuest: "true"}}) require.Nil(t, err) rsession, err := th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest]) err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) rsession, err = th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest]) th.App.ClearSessionCacheForUser(session.UserId) rsession, err = th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest]) }) t.Run("Demote User to Guest updates the session", func(t *testing.T) { user := th.CreateUser() - session, err := th.App.CreateSession(&model.Session{UserId: user.Id, Props: model.StringMap{model.SESSION_PROP_IS_GUEST: "false"}}) + session, err := th.App.CreateSession(&model.Session{UserId: user.Id, Props: model.StringMap{model.SessionPropIsGuest: "false"}}) require.Nil(t, err) rsession, err := th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest]) err = th.App.DemoteUserToGuest(user) require.Nil(t, err) rsession, err = th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest]) th.App.ClearSessionCacheForUser(session.UserId) rsession, err = th.App.GetSession(session.Token) require.Nil(t, err) - assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST]) + assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest]) }) } @@ -175,7 +175,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) { session := &model.Session{ UserId: model.NewId(), Props: map[string]string{ - model.USER_AUTH_SERVICE_IS_MOBILE: "true", + model.UserAuthServiceIsMobile: "true", }, } session, err := th.App.CreateSession(session) @@ -189,8 +189,8 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) { session := &model.Session{ UserId: model.NewId(), Props: map[string]string{ - model.USER_AUTH_SERVICE_IS_MOBILE: "true", - model.USER_AUTH_SERVICE_IS_SAML: "true", + model.UserAuthServiceIsMobile: "true", + model.UserAuthServiceIsSaml: "true", }, } session, err := th.App.CreateSession(session) @@ -204,7 +204,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) { session := &model.Session{ UserId: model.NewId(), Props: map[string]string{ - model.USER_AUTH_SERVICE_IS_OAUTH: "true", + model.UserAuthServiceIsOAuth: "true", }, } session, err := th.App.CreateSession(session) @@ -218,7 +218,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) { session := &model.Session{ UserId: model.NewId(), Props: map[string]string{ - model.USER_AUTH_SERVICE_IS_SAML: "true", + model.UserAuthServiceIsSaml: "true", }} session, err := th.App.CreateSession(session) require.Nil(t, err) diff --git a/app/shared_channel_notifier.go b/app/shared_channel_notifier.go index e04db7e514..3acddc3d73 100644 --- a/app/shared_channel_notifier.go +++ b/app/shared_channel_notifier.go @@ -15,15 +15,15 @@ import ( ) var sharedChannelEventsForSync model.StringArray = []string{ - model.WEBSOCKET_EVENT_POSTED, - model.WEBSOCKET_EVENT_POST_EDITED, - model.WEBSOCKET_EVENT_POST_DELETED, - model.WEBSOCKET_EVENT_REACTION_ADDED, - model.WEBSOCKET_EVENT_REACTION_REMOVED, + model.WebsocketEventPosted, + model.WebsocketEventPostEdited, + model.WebsocketEventPostDeleted, + model.WebsocketEventReactionAdded, + model.WebsocketEventReactionRemoved, } var sharedChannelEventsForInvitation model.StringArray = []string{ - model.WEBSOCKET_EVENT_DIRECT_ADDED, + model.WebsocketEventDirectAdded, } // SharedChannelSyncHandler is called when a websocket event is received by a cluster node. diff --git a/app/shared_channel_notifier_test.go b/app/shared_channel_notifier_test.go index 5f56dab957..3fe6bee217 100644 --- a/app/shared_channel_notifier_test.go +++ b/app/shared_channel_notifier_test.go @@ -33,7 +33,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { th.App.srv.SetSharedChannelSyncService(mockService) channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, model.NewId(), channel.Id, "", nil) + websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil) th.App.srv.SharedChannelSyncHandler(websocketEvent) assert.Empty(t, mockService.channelNotifications) @@ -47,7 +47,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService.active = true th.App.srv.SetSharedChannelSyncService(mockService) - websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, model.NewId(), model.NewId(), "", nil) + websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), model.NewId(), "", nil) th.App.srv.SharedChannelSyncHandler(websocketEvent) assert.Empty(t, mockService.channelNotifications) @@ -62,7 +62,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { th.App.srv.SetSharedChannelSyncService(mockService) channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, model.NewId(), channel.Id, "", nil) + websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil) th.App.srv.SharedChannelSyncHandler(websocketEvent) assert.Len(t, mockService.channelNotifications, 1) diff --git a/app/slashcommands/auto_constants.go b/app/slashcommands/auto_constants.go index 099a65d0aa..114633ffd1 100644 --- a/app/slashcommands/auto_constants.go +++ b/app/slashcommands/auto_constants.go @@ -10,11 +10,11 @@ import ( const ( UserPassword = "Usr@MMTest123" - ChannelType = model.CHANNEL_OPEN + ChannelType = model.ChannelTypeOpen BTestTeamDisplayName = "TestTeam" BTestTeamName = "z-z-testdomaina" BTestTeamEmail = "test@nowhere.com" - BTestTeamType = model.TEAM_OPEN + BTestTeamType = model.TeamOpen BTestUserName = "Mr. Testing Tester" BTestUserEmail = "success+ttester@simulator.amazonses.com" BTestUserPassword = "passwd" diff --git a/app/slashcommands/auto_teams.go b/app/slashcommands/auto_teams.go index d84fb230d1..98f0607bb9 100644 --- a/app/slashcommands/auto_teams.go +++ b/app/slashcommands/auto_teams.go @@ -54,7 +54,7 @@ func (cfg *AutoTeamCreator) createRandomTeam() (*model.Team, error) { DisplayName: teamDisplayName, Name: teamName, Email: teamEmail, - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } createdTeam, resp := cfg.client.CreateTeam(team) diff --git a/app/slashcommands/auto_users.go b/app/slashcommands/auto_users.go index b376a40525..7a3f79cba8 100644 --- a/app/slashcommands/auto_users.go +++ b/app/slashcommands/auto_users.go @@ -99,7 +99,7 @@ func (cfg *AutoUserCreator) createRandomUser(c *request.Context) (*model.User, e return nil, appErr } - status := &model.Status{UserId: ruser.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + status := &model.Status{UserId: ruser.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} if err := cfg.app.Srv().Store.Status().SaveOrUpdate(status); err != nil { return nil, err } diff --git a/app/slashcommands/command_away.go b/app/slashcommands/command_away.go index c29b1baaa5..9153940bf7 100644 --- a/app/slashcommands/command_away.go +++ b/app/slashcommands/command_away.go @@ -37,5 +37,5 @@ func (*AwayProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command func (*AwayProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusAwayIfNeeded(args.UserId, true) - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_away.success")} } diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index 57f4ce6316..3ff4169432 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -42,49 +42,49 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_header.channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } switch channel.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_GROUP, model.CHANNEL_DIRECT: + case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. var channelMember *model.ChannelMember channelMember, err = a.GetChannelMember(context.Background(), args.ChannelId, args.UserId) if err != nil || channelMember == nil { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } default: return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_header.message.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -98,13 +98,13 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com text := args.T("api.command_channel_header.update_channel.app_error") if err.Id == "model.channel.is_valid.header.app_error" { text = args.T("api.command_channel_header.update_channel.max_length", map[string]interface{}{ - "MaxLength": model.CHANNEL_HEADER_MAX_RUNES, + "MaxLength": model.ChannelHeaderMaxRunes, }) } return &model.CommandResponse{ Text: text, - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_channel_header_test.go b/app/slashcommands/command_channel_header_test.go index adfa6f265d..bff1d1527e 100644 --- a/app/slashcommands/command_channel_header_test.go +++ b/app/slashcommands/command_channel_header_test.go @@ -17,7 +17,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { hp := HeaderProvider{} - th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) // Try a public channel *with* permission. args := &model.CommandArgs{ @@ -34,7 +34,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { assert.Equal(t, expected, actual) } - th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) // Try a public channel *without* permission. args = &model.CommandArgs{ @@ -46,7 +46,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { actual := hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_header.permission.app_error", actual) - th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) // Try a private channel *with* permission. privateChannel := th.createPrivateChannel(th.BasicTeam) @@ -60,7 +60,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) - th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) // Try a private channel *without* permission. args = &model.CommandArgs{ diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index 128492788a..8b3f52fabb 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -40,36 +40,36 @@ func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.Co if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } switch channel.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } default: return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.direct_group.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.message.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -83,13 +83,13 @@ func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.Co text := args.T("api.command_channel_purpose.update_channel.app_error") if err.Id == "model.channel.is_valid.purpose.app_error" { text = args.T("api.command_channel_purpose.update_channel.max_length", map[string]interface{}{ - "MaxLength": model.CHANNEL_PURPOSE_MAX_RUNES, + "MaxLength": model.ChannelPurposeMaxRunes, }) } return &model.CommandResponse{ Text: text, - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_channel_purpose_test.go b/app/slashcommands/command_channel_purpose_test.go index 0a31d1039e..81d0fd39da 100644 --- a/app/slashcommands/command_channel_purpose_test.go +++ b/app/slashcommands/command_channel_purpose_test.go @@ -18,7 +18,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { pp := PurposeProvider{} // Try a public channel *with* permission. - th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args := &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -35,7 +35,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { } // Try a public channel *without* permission. - th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -48,7 +48,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { // Try a private channel *with* permission. privateChannel := th.createPrivateChannel(th.BasicTeam) - th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -60,7 +60,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { assert.Equal(t, "", actual) // Try a private channel *without* permission. - th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index 13d747b62f..43036d2491 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -43,47 +43,47 @@ func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } switch channel.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } default: - return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if message == "" { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.message.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } - } else if len(message) > model.CHANNEL_NAME_MAX_LENGTH { + } else if len(message) > model.ChannelNameMaxLength { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.too_long.app_error", map[string]interface{}{ - "Length": model.CHANNEL_NAME_MAX_LENGTH, + "Length": model.ChannelNameMaxLength, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } - } else if len(message) < model.CHANNEL_NAME_MIN_LENGTH { + } else if len(message) < model.ChannelNameMinLength { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.too_short.app_error", map[string]interface{}{ - "Length": model.CHANNEL_NAME_MIN_LENGTH, + "Length": model.ChannelNameMinLength, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -96,7 +96,7 @@ func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.update_channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_channel_rename_test.go b/app/slashcommands/command_channel_rename_test.go index e5bfaf7be2..b0ebacaca4 100644 --- a/app/slashcommands/command_channel_rename_test.go +++ b/app/slashcommands/command_channel_rename_test.go @@ -16,7 +16,7 @@ func TestRenameProviderDoCommand(t *testing.T) { th := setup(t).initBasic() defer th.tearDown() - th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) rp := RenameProvider{} args := &model.CommandArgs{ @@ -38,7 +38,7 @@ func TestRenameProviderDoCommand(t *testing.T) { } // Try a public channel *without* permission. - th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -52,7 +52,7 @@ func TestRenameProviderDoCommand(t *testing.T) { // Try a private channel *with* permission. privateChannel := th.createPrivateChannel(th.BasicTeam) - th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -64,7 +64,7 @@ func TestRenameProviderDoCommand(t *testing.T) { assert.Equal(t, "", actual) // Try a private channel *without* permission. - th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, diff --git a/app/slashcommands/command_code.go b/app/slashcommands/command_code.go index f61e614fc6..37cdc10e6d 100644 --- a/app/slashcommands/command_code.go +++ b/app/slashcommands/command_code.go @@ -39,8 +39,8 @@ func (*CodeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command func (*CodeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if message == "" { - return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } rmsg := " " + strings.Join(strings.Split(message, "\n"), "\n ") - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: rmsg, SkipSlackParsing: true} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeInChannel, Text: rmsg, SkipSlackParsing: true} } diff --git a/app/slashcommands/command_custom_status.go b/app/slashcommands/command_custom_status.go index b2c1e6097a..7a86eae071 100644 --- a/app/slashcommands/command_custom_status.go +++ b/app/slashcommands/command_custom_status.go @@ -50,11 +50,11 @@ func (*CustomStatusProvider) DoCommand(a *app.App, c *request.Context, args *mod if message == CmdCustomStatusClear { if err := a.RemoveCustomStatus(args.UserId); err != nil { mlog.Debug(err.Error()) - return &model.CommandResponse{Text: args.T("api.command_custom_status.clear.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_custom_status.clear.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_custom_status.clear.success"), } } @@ -63,11 +63,11 @@ func (*CustomStatusProvider) DoCommand(a *app.App, c *request.Context, args *mod customStatus.PreSave() if err := a.SetCustomStatus(args.UserId, customStatus); err != nil { mlog.Debug(err.Error()) - return &model.CommandResponse{Text: args.T("api.command_custom_status.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_custom_status.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_custom_status.success", map[string]interface{}{ "EmojiName": ":" + customStatus.Emoji + ":", "StatusMessage": customStatus.Text, @@ -81,7 +81,7 @@ func GetCustomStatus(message string) *model.CustomStatus { Text: message, } - firstEmojiLocations := model.EMOJI_PATTERN.FindIndex([]byte(message)) + firstEmojiLocations := model.EmojiPattern.FindIndex([]byte(message)) if len(firstEmojiLocations) > 0 && firstEmojiLocations[0] == 0 { // emoji found at starting index customStatus.Emoji = message[firstEmojiLocations[0]+1 : firstEmojiLocations[1]-1] diff --git a/app/slashcommands/command_dnd.go b/app/slashcommands/command_dnd.go index 86f238e999..2dc92ab4a8 100644 --- a/app/slashcommands/command_dnd.go +++ b/app/slashcommands/command_dnd.go @@ -37,5 +37,5 @@ func (*DndProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command func (*DndProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusDoNotDisturb(args.UserId) - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.success")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_dnd.success")} } diff --git a/app/slashcommands/command_echo.go b/app/slashcommands/command_echo.go index 504dfe7a42..8ac6c34c3b 100644 --- a/app/slashcommands/command_echo.go +++ b/app/slashcommands/command_echo.go @@ -44,7 +44,7 @@ func (*EchoProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command func (*EchoProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if message == "" { - return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } maxThreads := 100 @@ -66,7 +66,7 @@ func (*EchoProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma } if delay > 10000 { - return &model.CommandResponse{Text: args.T("api.command_echo.delay.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_echo.delay.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if echoSem == nil { @@ -75,7 +75,7 @@ func (*EchoProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma } if len(echoSem) >= maxThreads { - return &model.CommandResponse{Text: args.T("api.command_echo.high_volume.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_echo.high_volume.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } echoSem <- true diff --git a/app/slashcommands/command_expand_collapse.go b/app/slashcommands/command_expand_collapse.go index fe43a100ba..66aee356dd 100644 --- a/app/slashcommands/command_expand_collapse.go +++ b/app/slashcommands/command_expand_collapse.go @@ -65,16 +65,16 @@ func (*CollapseProvider) DoCommand(a *app.App, c *request.Context, args *model.C func setCollapsePreference(a *app.App, args *model.CommandArgs, isCollapse bool) *model.CommandResponse { pref := model.Preference{ UserId: args.UserId, - Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, - Name: model.PREFERENCE_NAME_COLLAPSE_SETTING, + Category: model.PreferenceCategoryDisplaySettings, + Name: model.PreferenceNameCollapseSetting, Value: strconv.FormatBool(isCollapse), } if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil { - return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - socketMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCE_CHANGED, "", "", args.UserId, nil) + socketMessage := model.NewWebSocketEvent(model.WebsocketEventPreferenceChanged, "", "", args.UserId, nil) socketMessage.Add("preference", pref.ToJson()) a.Publish(socketMessage) @@ -85,5 +85,5 @@ func setCollapsePreference(a *app.App, args *model.CommandArgs, isCollapse bool) } else { rmsg = args.T("api.command_expand.success") } - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: rmsg} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: rmsg} } diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 4537089516..d00a223e78 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -57,7 +57,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C canSee, err := a.UserCanSeeOtherUser(args.UserId, targetUser.Id) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if !canSee { @@ -78,7 +78,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C } return &model.CommandResponse{ Text: args.T("api.command_groupmsg.invalid_user.app_error", len(invalidUsernames), invalidUsersString), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -86,39 +86,39 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C return app.GetCommandProvider("msg").DoCommand(a, c, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage)) } - if len(targetUsersSlice) < model.CHANNEL_GROUP_MIN_USERS { + if len(targetUsersSlice) < model.ChannelGroupMinUsers { minUsers := map[string]interface{}{ - "MinUsers": model.CHANNEL_GROUP_MIN_USERS - 1, + "MinUsers": model.ChannelGroupMinUsers - 1, } return &model.CommandResponse{ Text: args.T("api.command_groupmsg.min_users.app_error", minUsers), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - if len(targetUsersSlice) > model.CHANNEL_GROUP_MAX_USERS { + if len(targetUsersSlice) > model.ChannelGroupMaxUsers { maxUsers := map[string]interface{}{ - "MaxUsers": model.CHANNEL_GROUP_MAX_USERS - 1, + "MaxUsers": model.ChannelGroupMaxUsers - 1, } return &model.CommandResponse{ Text: args.T("api.command_groupmsg.max_users.app_error", maxUsers), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } var groupChannel *model.Channel var channelErr *model.AppError - if a.HasPermissionTo(args.UserId, model.PERMISSION_CREATE_GROUP_CHANNEL) { + if a.HasPermissionTo(args.UserId, model.PermissionCreateGroupChannel) { groupChannel, channelErr = a.CreateGroupChannel(targetUsersSlice, args.UserId) if channelErr != nil { mlog.Error(channelErr.Error()) - return &model.CommandResponse{Text: args.T("api.command_groupmsg.group_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_groupmsg.group_fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } else { groupChannel, channelErr = a.GetGroupChannel(targetUsersSlice) if channelErr != nil { - return &model.CommandResponse{Text: args.T("api.command_groupmsg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_groupmsg.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } @@ -128,16 +128,16 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C post.ChannelId = groupChannel.Id post.UserId = args.UserId if _, err := a.CreatePostMissingChannel(c, post, true); err != nil { - return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } team, err := a.GetTeam(args.TeamId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + groupChannel.Name, Text: "", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + groupChannel.Name, Text: "", ResponseType: model.CommandResponseTypeEphemeral} } func groupMsgUsernames(message string) ([]string, string) { diff --git a/app/slashcommands/command_groupmsg_test.go b/app/slashcommands/command_groupmsg_test.go index bbd3453323..8097a0636c 100644 --- a/app/slashcommands/command_groupmsg_test.go +++ b/app/slashcommands/command_groupmsg_test.go @@ -64,7 +64,7 @@ func TestGroupMsgProvider(t *testing.T) { th.linkUserToTeam(th.BasicUser, team) cmd := &groupmsgProvider{} - th.removePermissionFromRole(model.PERMISSION_CREATE_GROUP_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionCreateGroupChannel.Id, model.SystemUserRoleId) t.Run("Check without permission to create a GM channel.", func(t *testing.T) { resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ @@ -78,11 +78,11 @@ func TestGroupMsgProvider(t *testing.T) { assert.Equal(t, "", resp.GotoLocation) }) - th.addPermissionToRole(model.PERMISSION_CREATE_GROUP_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionCreateGroupChannel.Id, model.SystemUserRoleId) t.Run("Check without permissions to view a user in the list.", func(t *testing.T) { - th.removePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - defer th.addPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) + defer th.addPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId) resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", diff --git a/app/slashcommands/command_help.go b/app/slashcommands/command_help.go index 26984083cb..6e92ef2af7 100644 --- a/app/slashcommands/command_help.go +++ b/app/slashcommands/command_help.go @@ -38,7 +38,7 @@ func (h *HelpProvider) DoCommand(a *app.App, c *request.Context, args *model.Com helpLink := *a.Config().SupportSettings.HelpLink if helpLink == "" { - helpLink = model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK + helpLink = model.SupportSettingsDefaultHelpLink } return &model.CommandResponse{GotoLocation: helpLink} diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index 5a94146738..6eddb3fba6 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -43,7 +43,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if message == "" { return &model.CommandResponse{ Text: args.T("api.command_invite.missing_message.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -56,14 +56,14 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com mlog.Error(nErr.Error()) return &model.CommandResponse{ Text: args.T("api.command_invite.missing_user.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } if userProfile.DeleteAt != 0 { return &model.CommandResponse{ Text: args.T("api.command_invite.missing_user.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -78,7 +78,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com Text: args.T("api.command_invite.channel.error", map[string]interface{}{ "Channel": targetChannelName, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } } else { @@ -86,25 +86,25 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if err != nil { return &model.CommandResponse{ Text: args.T("api.command_invite.channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } } // Permissions Check switch channelToJoin.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PermissionManagePublicChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_invite.permission.app_error", map[string]interface{}{ "User": userProfile.Username, "Channel": channelToJoin.Name, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PermissionManagePrivateChannelMembers) { if _, err = a.GetChannelMember(context.Background(), channelToJoin.Id, args.UserId); err == nil { // User doing the inviting is a member of the channel. return &model.CommandResponse{ @@ -112,7 +112,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com "User": userProfile.Username, "Channel": channelToJoin.Name, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } // User doing the inviting is *not* a member of the channel. @@ -120,13 +120,13 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com Text: args.T("api.command_invite.private_channel.app_error", map[string]interface{}{ "Channel": channelToJoin.Name, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } default: return &model.CommandResponse{ Text: args.T("api.command_invite.directchannel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -137,7 +137,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com Text: args.T("api.command_invite.user_already_in_channel.app_error", map[string]interface{}{ "User": userProfile.Username, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -157,7 +157,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } return &model.CommandResponse{ Text: text, - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -167,7 +167,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com "User": userProfile.Username, "Channel": channelToJoin.Name, }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_invite_people.go b/app/slashcommands/command_invite_people.go index a27f2594b9..10c7529e86 100644 --- a/app/slashcommands/command_invite_people.go +++ b/app/slashcommands/command_invite_people.go @@ -43,24 +43,24 @@ func (*InvitePeopleProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model } func (*InvitePeopleProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PERMISSION_INVITE_USER) { - return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PermissionInviteUser) { + return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { - return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PermissionAddUserToTeam) { + return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if !*a.Config().EmailSettings.SendEmailNotifications { - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.email_off")} } if !*a.Config().TeamSettings.EnableUserCreation { - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.invite_off")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.invite_off")} } if !*a.Config().ServiceSettings.EnableEmailInvitations { - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_invitations_off")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.email_invitations_off")} } emailList := strings.Fields(message) @@ -73,13 +73,13 @@ func (*InvitePeopleProvider) DoCommand(a *app.App, c *request.Context, args *mod } if len(emailList) == 0 { - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.no_email")} } if err := a.InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { mlog.Error(err.Error()) - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.fail")} } - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.sent")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.sent")} } diff --git a/app/slashcommands/command_invite_test.go b/app/slashcommands/command_invite_test.go index 7b37d7ad47..25712a14c1 100644 --- a/app/slashcommands/command_invite_test.go +++ b/app/slashcommands/command_invite_test.go @@ -17,10 +17,10 @@ func TestInviteProvider(t *testing.T) { th := setup(t).initBasic() defer th.tearDown() - channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) - privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) + channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) + privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) dmChannel := th.createDmChannel(th.BasicUser2) - privateChannel2 := th.createChannelWithAnotherUser(th.BasicTeam, model.CHANNEL_PRIVATE, th.BasicUser2.Id) + privateChannel2 := th.createChannelWithAnotherUser(th.BasicTeam, model.ChannelTypePrivate, th.BasicUser2.Id) basicUser3 := th.createUser() th.linkUserToTeam(basicUser3, th.BasicTeam) @@ -72,7 +72,7 @@ func TestInviteProvider(t *testing.T) { userAndInvalidPrivate := "@" + basicUser3.Username + " ~" + privateChannel2.Name deactivatedUserPublicChannel := "@" + deactivatedUser.Username + " ~" + channel.Name - groupChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) + groupChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) _, err = th.App.AddChannelMember(th.Context, th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{}) require.Nil(t, err) groupChannel.GroupConstrained = model.NewBool(true) @@ -186,7 +186,7 @@ func TestInviteGroup(t *testing.T) { require.Nil(t, err) th.BasicTeam, _ = th.App.UpdateTeam(th.BasicTeam) - privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) + privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) groupChannelUser1 := "@" + th.BasicUser.Username + " ~" + privateChannel.Name groupChannelUser2 := "@" + th.BasicUser2.Username + " ~" + privateChannel.Name diff --git a/app/slashcommands/command_join.go b/app/slashcommands/command_join.go index 56ee55aca7..0391d14fe0 100644 --- a/app/slashcommands/command_join.go +++ b/app/slashcommands/command_join.go @@ -46,33 +46,33 @@ func (*JoinProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma channel, err := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if channel.Name != channelName { - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_join.missing.app_error")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_join.missing.app_error")} } switch channel.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PERMISSION_JOIN_PUBLIC_CHANNELS) { - return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PermissionJoinPublicChannels) { + return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PERMISSION_READ_CHANNEL) { - return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PermissionReadChannel) { + return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } default: - return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if appErr := a.JoinChannel(c, channel, args.UserId); appErr != nil { - return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } team, appErr := a.GetTeam(channel.TeamId) if appErr != nil { - return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channel.Name} diff --git a/app/slashcommands/command_join_test.go b/app/slashcommands/command_join_test.go index 09f1050973..13557932ea 100644 --- a/app/slashcommands/command_join_test.go +++ b/app/slashcommands/command_join_test.go @@ -42,7 +42,7 @@ func TestJoinCommandForExistingChannel(t *testing.T) { channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -70,7 +70,7 @@ func TestJoinCommandWithTilde(t *testing.T) { channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -94,7 +94,7 @@ func TestJoinCommandPermissions(t *testing.T) { channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -129,7 +129,7 @@ func TestJoinCommandPermissions(t *testing.T) { channel3, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) diff --git a/app/slashcommands/command_leave.go b/app/slashcommands/command_leave.go index b3c884dd3e..39c696d41a 100644 --- a/app/slashcommands/command_leave.go +++ b/app/slashcommands/command_leave.go @@ -38,20 +38,20 @@ func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.Comm var channel *model.Channel var noChannelErr *model.AppError if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } team, err := a.GetTeam(args.TeamId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } err = a.LeaveChannel(c, args.ChannelId, args.UserId) if err != nil { - if channel.Name == model.DEFAULT_CHANNEL { - return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if channel.Name == model.DefaultChannelName { + return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } member, err := a.GetTeamMember(team.Id, args.UserId) @@ -61,20 +61,20 @@ func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.Comm user, err := a.GetUser(args.UserId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if user.IsGuest() { members, err := a.GetChannelMembersForUser(team.Id, args.UserId) if err != nil || len(*members) == 0 { - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } channel, err := a.GetChannel((*members)[0].ChannelId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channel.Name} } - return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + model.DEFAULT_CHANNEL} + return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + model.DefaultChannelName} } diff --git a/app/slashcommands/command_leave_test.go b/app/slashcommands/command_leave_test.go index cf824bab8b..4b30d72058 100644 --- a/app/slashcommands/command_leave_test.go +++ b/app/slashcommands/command_leave_test.go @@ -22,7 +22,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { publicChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -30,12 +30,12 @@ func TestLeaveProviderDoCommand(t *testing.T) { privateChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) - defaultChannel, err := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false) + defaultChannel, err := th.App.GetChannelByName(model.DefaultChannelName, th.BasicTeam.Id, false) require.Nil(t, err) guest := th.createGuest() @@ -54,7 +54,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { } actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) - assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType) + assert.Equal(t, model.CommandResponseTypeEphemeral, actual.ResponseType) }) t.Run("Should error when no Team ID in args", func(t *testing.T) { @@ -65,7 +65,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { } actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) - assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType) + assert.Equal(t, model.CommandResponseTypeEphemeral, actual.ResponseType) }) t.Run("Leave a public channel", func(t *testing.T) { @@ -78,7 +78,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { } actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "", actual.Text) - assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+model.DEFAULT_CHANNEL, actual.GotoLocation) + assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+model.DefaultChannelName, actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) _, err = th.App.GetChannelMember(context.Background(), publicChannel.Id, th.BasicUser.Id) diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index daea6c5039..59b670b7ff 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -168,7 +168,7 @@ func (lt *LoadTestProvider) doCommand(a *app.App, c *request.Context, args *mode } func (*LoadTestProvider) HelpCommand(args *model.CommandArgs, message string) *model.CommandResponse { - return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: usage, ResponseType: model.CommandResponseTypeEphemeral} } func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { @@ -213,11 +213,11 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *mode if doTeams { if err := CreateBasicUser(a, client); err != nil { - return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err } _, resp := client.Login(BTestUserEmail, BTestUserPassword) if resp.Error != nil { - return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error + return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error } environment, err := CreateTestEnvironmentWithTeams( a, @@ -229,7 +229,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *mode utils.Range{Begin: numPosts, End: numPosts}, doFuzz) if err != nil { - return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err } mlog.Info("Testing environment created") @@ -240,7 +240,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *mode } else { team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { - return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err } CreateTestEnvironmentInTeam( @@ -254,25 +254,25 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *mode doFuzz) } - return &model.CommandResponse{Text: "Created environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Created environment", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) ActivateUserCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { user_id := strings.TrimSpace(strings.TrimPrefix(message, "activate_user")) if err := a.UpdateUserActive(c, user_id, true); err != nil { - return &model.CommandResponse{Text: "Failed to activate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to activate user", ResponseType: model.CommandResponseTypeEphemeral}, err } - return &model.CommandResponse{Text: "Activated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Activated user", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) DeActivateUserCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { user_id := strings.TrimSpace(strings.TrimPrefix(message, "deactivate_user")) if err := a.UpdateUserActive(c, user_id, false); err != nil { - return &model.CommandResponse{Text: "Failed to deactivate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to deactivate user", ResponseType: model.CommandResponseTypeEphemeral}, err } - return &model.CommandResponse{Text: "DeActivated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "DeActivated user", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) UsersCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { @@ -291,17 +291,17 @@ func (*LoadTestProvider) UsersCommand(a *app.App, c *request.Context, args *mode team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { - return &model.CommandResponse{Text: "Failed to add users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to add users", ResponseType: model.CommandResponseTypeEphemeral}, err } client := model.NewAPIv4Client(args.SiteURL) userCreator := NewAutoUserCreator(a, client, team) userCreator.Fuzzy = doFuzz if _, err := userCreator.CreateTestUsers(c, usersr); err != nil { - return &model.CommandResponse{Text: "Failed to add users: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to add users: " + err.Error(), ResponseType: model.CommandResponseTypeEphemeral}, err } - return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Added users", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) ChannelsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { @@ -320,16 +320,16 @@ func (*LoadTestProvider) ChannelsCommand(a *app.App, c *request.Context, args *m team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { - return &model.CommandResponse{Text: "Failed to add channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to add channels", ResponseType: model.CommandResponseTypeEphemeral}, err } channelCreator := NewAutoChannelCreator(a, team, args.UserId) channelCreator.Fuzzy = doFuzz if _, err := channelCreator.CreateTestChannels(c, channelsr); err != nil { - return &model.CommandResponse{Text: "Failed to create test channels: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to create test channels: " + err.Error(), ResponseType: model.CommandResponseTypeEphemeral}, err } - return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Added channels", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) ThreadedPostCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { @@ -349,13 +349,13 @@ func (*LoadTestProvider) ThreadedPostCommand(a *app.App, c *request.Context, arg testPoster.Users = usernames rpost, err2 := testPoster.CreateRandomPost(c) if err2 != nil { - return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err2 + return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.CommandResponseTypeEphemeral}, err2 } for i := 0; i < 1000; i++ { testPoster.CreateRandomPostNested(c, rpost.Id, rpost.Id) } - return &model.CommandResponse{Text: "Added threaded post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Added threaded post", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) PostsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { @@ -401,12 +401,12 @@ func (*LoadTestProvider) PostsCommand(a *app.App, c *request.Context, args *mode testPoster.HasImage = (i < numImages) _, err := testPoster.CreateRandomPost(c) if err != nil { - return &model.CommandResponse{Text: "Failed to add posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to add posts", ResponseType: model.CommandResponseTypeEphemeral}, err } } - return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Added posts", ResponseType: model.CommandResponseTypeEphemeral}, nil } func getMatch(re *regexp.Regexp, text string) string { @@ -420,32 +420,32 @@ func getMatch(re *regexp.Regexp, text string) string { func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { textMessage := getMatch(messageRE, message) if textMessage == "" { - return &model.CommandResponse{Text: "No message to post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "No message to post", ResponseType: model.CommandResponseTypeEphemeral}, nil } teamName := getMatch(teamRE, message) team, err := a.GetTeamByName(teamName) if err != nil { - return &model.CommandResponse{Text: "Failed to get a team", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to get a team", ResponseType: model.CommandResponseTypeEphemeral}, err } channelName := getMatch(channelRE, message) channel, err := a.GetChannelByName(channelName, team.Id, true) if err != nil { - return &model.CommandResponse{Text: "Failed to get a channel", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to get a channel", ResponseType: model.CommandResponseTypeEphemeral}, err } passwd := getMatch(passwdRE, message) username := getMatch(userRE, message) user, err := a.GetUserByUsername(username) if err != nil { - return &model.CommandResponse{Text: "Failed to get a user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Failed to get a user", ResponseType: model.CommandResponseTypeEphemeral}, err } client := model.NewAPIv4Client(args.SiteURL) _, resp := client.LoginById(user.Id, passwd) if resp.Error != nil { - return &model.CommandResponse{Text: "Failed to login a user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error + return &model.CommandResponse{Text: "Failed to login a user", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error } post := &model.Post{ @@ -454,16 +454,16 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag } _, resp = client.CreatePost(post) if resp.Error != nil { - return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error + return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error } - return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "url")) if url == "" { - return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.CommandResponseTypeEphemeral}, nil } // provide a shortcut to easily access tests stored in doc/developer/tests @@ -477,7 +477,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model. r, err := http.Get(url) if err != nil { - return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.CommandResponseTypeEphemeral}, err } defer func() { io.Copy(ioutil.Discard, r.Body) @@ -485,7 +485,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model. }() if r.StatusCode > 400 { - return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, errors.Errorf("unexpected status code %d", r.StatusCode) + return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.CommandResponseTypeEphemeral}, errors.Errorf("unexpected status code %d", r.StatusCode) } bytes := make([]byte, 4000) @@ -494,7 +494,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model. for { length, err := r.Body.Read(bytes) if err != nil && err != io.EOF { - return &model.CommandResponse{Text: "Encountered error reading file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Encountered error reading file", ResponseType: model.CommandResponseTypeEphemeral}, err } if length == 0 { @@ -507,17 +507,17 @@ func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model. post.UserId = args.UserId if _, err := a.CreatePostMissingChannel(c, post, false); err != nil { - return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.CommandResponseTypeEphemeral}, err } } - return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Loaded data", ResponseType: model.CommandResponseTypeEphemeral}, nil } func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "json")) if url == "" { - return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.CommandResponseTypeEphemeral}, nil } // provide a shortcut to easily access tests stored in doc/developer/tests @@ -531,11 +531,11 @@ func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model r, err := http.Get(url) if err != nil { - return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.CommandResponseTypeEphemeral}, err } if r.StatusCode > 400 { - return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, errors.Errorf("unexpected status code %d", r.StatusCode) + return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.CommandResponseTypeEphemeral}, errors.Errorf("unexpected status code %d", r.StatusCode) } defer func() { io.Copy(ioutil.Discard, r.Body) @@ -544,7 +544,7 @@ func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model post := model.PostFromJson(r.Body) if post == nil { - return &model.CommandResponse{Text: "Unable to decode post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, errors.Errorf("could not decode post from json") + return &model.CommandResponse{Text: "Unable to decode post", ResponseType: model.CommandResponseTypeEphemeral}, errors.Errorf("could not decode post from json") } post.ChannelId = args.ChannelId post.UserId = args.UserId @@ -553,10 +553,10 @@ func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model } if _, err := a.CreatePostMissingChannel(c, post, false); err != nil { - return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err + return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.CommandResponseTypeEphemeral}, err } - return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil + return &model.CommandResponse{Text: "Loaded data", ResponseType: model.CommandResponseTypeEphemeral}, nil } func parseRange(command string, cmd string) (utils.Range, bool) { diff --git a/app/slashcommands/command_me.go b/app/slashcommands/command_me.go index a1d597bfbf..eab9e20749 100644 --- a/app/slashcommands/command_me.go +++ b/app/slashcommands/command_me.go @@ -37,8 +37,8 @@ func (*MeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command { func (*MeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, - Type: model.POST_ME, + ResponseType: model.CommandResponseTypeInChannel, + Type: model.PostTypeMe, Text: "*" + message + "*", } } diff --git a/app/slashcommands/command_me_test.go b/app/slashcommands/command_me_test.go index 71ebbed187..1c19a358a5 100644 --- a/app/slashcommands/command_me_test.go +++ b/app/slashcommands/command_me_test.go @@ -21,7 +21,7 @@ func TestMeProviderDoCommand(t *testing.T) { resp := mp.DoCommand(th.App, th.Context, &model.CommandArgs{}, msg) - assert.Equal(t, model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, resp.ResponseType) - assert.Equal(t, model.POST_ME, resp.Type) + assert.Equal(t, model.CommandResponseTypeInChannel, resp.ResponseType) + assert.Equal(t, model.PostTypeMe, resp.Type) assert.Equal(t, "*"+msg+"*", resp.Text) } diff --git a/app/slashcommands/command_msg.go b/app/slashcommands/command_msg.go index b4d3b01e32..b9345a7b43 100644 --- a/app/slashcommands/command_msg.go +++ b/app/slashcommands/command_msg.go @@ -55,20 +55,20 @@ func (*msgProvider) DoCommand(a *app.App, c *request.Context, args *model.Comman userProfile, nErr := a.Srv().Store.User().GetByUsername(targetUsername) if nErr != nil { mlog.Error(nErr.Error()) - return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if userProfile.Id == args.UserId { - return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } canSee, err := a.UserCanSeeOtherUser(args.UserId, userProfile.Id) if err != nil { mlog.Error(err.Error()) - return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } if !canSee { - return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } // Find the channel based on this user @@ -78,19 +78,19 @@ func (*msgProvider) DoCommand(a *app.App, c *request.Context, args *model.Comman if channel, channelErr := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil { var nfErr *store.ErrNotFound if errors.As(channelErr, &nfErr) { - if !a.HasPermissionTo(args.UserId, model.PERMISSION_CREATE_DIRECT_CHANNEL) { - return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if !a.HasPermissionTo(args.UserId, model.PermissionCreateDirectChannel) { + return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } var directChannel *model.Channel if directChannel, err = a.GetOrCreateDirectChannel(c, args.UserId, userProfile.Id); err != nil { mlog.Error(err.Error()) - return &model.CommandResponse{Text: args.T(err.Id), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T(err.Id), ResponseType: model.CommandResponseTypeEphemeral} } targetChannelId = directChannel.Id } else { mlog.Error(channelErr.Error()) - return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } else { targetChannelId = channel.Id @@ -102,14 +102,14 @@ func (*msgProvider) DoCommand(a *app.App, c *request.Context, args *model.Comman post.ChannelId = targetChannelId post.UserId = args.UserId if _, err = a.CreatePostMissingChannel(c, post, true); err != nil { - return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } team, err := a.GetTeam(args.TeamId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channelName, Text: "", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channelName, Text: "", ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_msg_test.go b/app/slashcommands/command_msg_test.go index 175e26b66c..05e21ba9c9 100644 --- a/app/slashcommands/command_msg_test.go +++ b/app/slashcommands/command_msg_test.go @@ -20,7 +20,7 @@ func TestMsgProvider(t *testing.T) { th.linkUserToTeam(th.BasicUser, team) cmd := &msgProvider{} - th.removePermissionFromRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) + th.removePermissionFromRole(model.PermissionCreateDirectChannel.Id, model.SystemUserRoleId) // Check without permission to create a DM channel. resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ @@ -34,7 +34,7 @@ func TestMsgProvider(t *testing.T) { assert.Equal(t, "api.command_msg.permission.app_error", resp.Text) assert.Equal(t, "", resp.GotoLocation) - th.addPermissionToRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) + th.addPermissionToRole(model.PermissionCreateDirectChannel.Id, model.SystemUserRoleId) // Check with permission to create a DM channel. resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index e15fe13d52..e681ed2a91 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -42,7 +42,7 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma var noChannelErr *model.AppError if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { - return &model.CommandResponse{Text: args.T("api.command_mute.no_channel.error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_mute.no_channel.error"), ResponseType: model.CommandResponseTypeEphemeral} } channelName := "" @@ -58,25 +58,25 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) if channel == nil { - return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} } } channelMember, err := a.ToggleMuteChannel(channel.Id, args.UserId) if err != nil { - return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} } // Direct and Group messages won't have a nice channel title, omit it - if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { - if channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_NOTIFY_MENTION { - return &model.CommandResponse{Text: args.T("api.command_mute.success_mute_direct_msg"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup { + if channelMember.NotifyProps[model.MarkUnreadNotifyProp] == model.ChannelNotifyMention { + return &model.CommandResponse{Text: args.T("api.command_mute.success_mute_direct_msg"), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute_direct_msg"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute_direct_msg"), ResponseType: model.CommandResponseTypeEphemeral} } - if channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_NOTIFY_MENTION { - return &model.CommandResponse{Text: args.T("api.command_mute.success_mute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + if channelMember.NotifyProps[model.MarkUnreadNotifyProp] == model.ChannelNotifyMention { + return &model.CommandResponse{Text: args.T("api.command_mute.success_mute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} } - return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} + return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_mute_test.go b/app/slashcommands/command_mute_test.go index f0b9b053cf..b7a6a3f0f6 100644 --- a/app/slashcommands/command_mute_test.go +++ b/app/slashcommands/command_mute_test.go @@ -28,8 +28,8 @@ func TestMuteCommandNoChannel(t *testing.T) { assert.Nil(t, channel1MError, "User is not a member of channel 1") assert.NotEqual( t, - channel1M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP], - model.CHANNEL_NOTIFY_MENTION, + channel1M.NotifyProps[model.MarkUnreadNotifyProp], + model.ChannelNotifyMention, "Channel shouldn't be muted on initial setup", ) @@ -48,7 +48,7 @@ func TestMuteCommandNoArgs(t *testing.T) { channel1 := th.BasicChannel channel1M, _ := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel1M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyAll, channel1M.NotifyProps[model.MarkUnreadNotifyProp]) cmd := &MuteProvider{} @@ -83,14 +83,14 @@ func TestMuteCommandSpecificChannel(t *testing.T) { channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, true) channel2M, _ := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) cmd := &MuteProvider{} @@ -102,7 +102,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { }, channel2.Name) assert.Equal(t, "api.command_mute.success_mute", resp.Text) channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyMention, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) // Now unmute the channel resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ @@ -113,7 +113,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { assert.Equal(t, "api.command_mute.success_unmute", resp.Text) channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) } func TestMuteCommandNotMember(t *testing.T) { @@ -128,7 +128,7 @@ func TestMuteCommandNotMember(t *testing.T) { channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -176,7 +176,7 @@ func TestMuteCommandDMChannel(t *testing.T) { channel2, _ := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) channel2M, _ := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) cmd := &MuteProvider{} @@ -189,7 +189,7 @@ func TestMuteCommandDMChannel(t *testing.T) { assert.Equal(t, "api.command_mute.success_mute_direct_msg", resp.Text) time.Sleep(time.Millisecond) channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyMention, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) // Now unmute the channel resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ @@ -201,5 +201,5 @@ func TestMuteCommandDMChannel(t *testing.T) { assert.Equal(t, "api.command_mute.success_unmute_direct_msg", resp.Text) time.Sleep(time.Millisecond) channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) - assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) + assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) } diff --git a/app/slashcommands/command_offline.go b/app/slashcommands/command_offline.go index 313e4dd752..bf56721328 100644 --- a/app/slashcommands/command_offline.go +++ b/app/slashcommands/command_offline.go @@ -37,5 +37,5 @@ func (*OfflineProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comm func (*OfflineProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusOffline(args.UserId, true) - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_offline.success")} } diff --git a/app/slashcommands/command_online.go b/app/slashcommands/command_online.go index c0797454ce..618520811d 100644 --- a/app/slashcommands/command_online.go +++ b/app/slashcommands/command_online.go @@ -37,5 +37,5 @@ func (*OnlineProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma func (*OnlineProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusOnline(args.UserId, true) - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_online.success")} } diff --git a/app/slashcommands/command_remote.go b/app/slashcommands/command_remote.go index 646c59ee42..4655cca82e 100644 --- a/app/slashcommands/command_remote.go +++ b/app/slashcommands/command_remote.go @@ -70,7 +70,7 @@ func (rp *RemoteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Co } func (rp *RemoteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - if !a.HasPermissionTo(args.UserId, model.PERMISSION_MANAGE_SECURE_CONNECTIONS) { + if !a.HasPermissionTo(args.UserId, model.PermissionManageSecureConnections) { return responsef(args.T("api.command_remote.permission_required", map[string]interface{}{"Permission": "manage_secure_connections"})) } @@ -95,7 +95,7 @@ func (rp *RemoteProvider) DoCommand(a *app.App, c *request.Context, args *model. } func (rp *RemoteProvider) GetAutoCompleteListItems(a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) ([]model.AutocompleteListItem, error) { - if !a.HasPermissionTo(commandArgs.UserId, model.PERMISSION_MANAGE_SECURE_CONNECTIONS) { + if !a.HasPermissionTo(commandArgs.UserId, model.PermissionManageSecureConnections) { return nil, errors.New("You require `manage_secure_connections` permission to manage secure connections.") } diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index 96a5cfb6fe..ceb394a4f8 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -71,36 +71,36 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_remove.channel.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } switch channel.Type { - case model.CHANNEL_OPEN: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { + case model.ChannelTypeOpen: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_remove.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } - case model.CHANNEL_PRIVATE: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { + case model.ChannelTypePrivate: + if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_remove.permission.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } default: return &model.CommandResponse{ Text: args.T("api.command_remove.direct_group.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } if message == "" { return &model.CommandResponse{ Text: args.T("api.command_remove.message.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -114,13 +114,13 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message mlog.Error(nErr.Error()) return &model.CommandResponse{ Text: args.T("api.command_remove.missing.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } if userProfile.DeleteAt != 0 { return &model.CommandResponse{ Text: args.T("api.command_remove.missing.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -131,7 +131,7 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message Text: args.T("api.command_remove.user_not_in_channel", map[string]interface{}{ "Username": userProfile.GetDisplayName(nameFormat), }), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } @@ -141,12 +141,12 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message text = args.T("api.command_remove.group_constrained_user_denied") } else { text = args.T(err.Id, map[string]interface{}{ - "Channel": model.DEFAULT_CHANNEL, + "Channel": model.DefaultChannelName, }) } return &model.CommandResponse{ Text: text, - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_remove_test.go b/app/slashcommands/command_remove_test.go index 862fa804c4..7c28be69b9 100644 --- a/app/slashcommands/command_remove_test.go +++ b/app/slashcommands/command_remove_test.go @@ -20,7 +20,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { publicChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) @@ -28,7 +28,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { privateChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, }, false) diff --git a/app/slashcommands/command_search.go b/app/slashcommands/command_search.go index 174780e982..2b5c142223 100644 --- a/app/slashcommands/command_search.go +++ b/app/slashcommands/command_search.go @@ -39,6 +39,6 @@ func (search *SearchProvider) DoCommand(a *app.App, c *request.Context, args *mo // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_search.unsupported.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_settings.go b/app/slashcommands/command_settings.go index 80782a2be7..7d33bc81e8 100644 --- a/app/slashcommands/command_settings.go +++ b/app/slashcommands/command_settings.go @@ -39,6 +39,6 @@ func (settings *SettingsProvider) DoCommand(a *app.App, c *request.Context, args // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_settings.unsupported.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_share.go b/app/slashcommands/command_share.go index 204394eebd..18ada56b22 100644 --- a/app/slashcommands/command_share.go +++ b/app/slashcommands/command_share.go @@ -121,7 +121,7 @@ func (sp *ShareProvider) getAutoCompleteUnInviteRemote(a *app.App, _ *model.Comm } func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - if !a.HasPermissionTo(args.UserId, model.PERMISSION_MANAGE_SHARED_CHANNELS) { + if !a.HasPermissionTo(args.UserId, model.PermissionManageSharedChannels) { return responsef(args.T("api.command_share.permission_required", map[string]interface{}{"Permission": "manage_shared_channels"})) } @@ -323,7 +323,7 @@ func (sp *ShareProvider) doStatus(a *app.App, args *model.CommandArgs, _ map[str } func notifyClientsForChannelUpdate(a *app.App, sharedChannel *model.SharedChannel) { - messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CONVERTED, sharedChannel.TeamId, "", "", nil) + messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelConverted, sharedChannel.TeamId, "", "", nil) messageWs.Add("channel_id", sharedChannel.ChannelId) a.Publish(messageWs) } diff --git a/app/slashcommands/command_share_test.go b/app/slashcommands/command_share_test.go index 43e7eaa969..89d9a91657 100644 --- a/app/slashcommands/command_share_test.go +++ b/app/slashcommands/command_share_test.go @@ -24,7 +24,7 @@ func TestShareProviderDoCommand(t *testing.T) { th := setup(t).initBasic() defer th.tearDown() - th.addPermissionToRole(model.PERMISSION_MANAGE_SHARED_CHANNELS.Id, th.BasicUser.Roles) + th.addPermissionToRole(model.PermissionManageSharedChannels.Id, th.BasicUser.Roles) mockSyncService := app.NewMockSharedChannelService(nil) th.Server.SetSharedChannelSyncService(mockSyncService) @@ -51,7 +51,7 @@ func TestShareProviderDoCommand(t *testing.T) { channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool { event := model.WebSocketEventFromJson(strings.NewReader(msg.Data)) - return event != nil && event.EventType() == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED + return event != nil && event.EventType() == model.WebsocketEventChannelConverted }) assert.Len(t, channelConvertedMessages, 1) }) @@ -60,7 +60,7 @@ func TestShareProviderDoCommand(t *testing.T) { th := setup(t).initBasic() defer th.tearDown() - th.addPermissionToRole(model.PERMISSION_MANAGE_SHARED_CHANNELS.Id, th.BasicUser.Roles) + th.addPermissionToRole(model.PermissionManageSharedChannels.Id, th.BasicUser.Roles) mockSyncService := app.NewMockSharedChannelService(nil) th.Server.SetSharedChannelSyncService(mockSyncService) @@ -86,7 +86,7 @@ func TestShareProviderDoCommand(t *testing.T) { channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool { event := model.WebSocketEventFromJson(strings.NewReader(msg.Data)) - return event != nil && event.EventType() == model.WEBSOCKET_EVENT_CHANNEL_CONVERTED + return event != nil && event.EventType() == model.WebsocketEventChannelConverted }) require.Len(t, channelConvertedMessages, 1) }) diff --git a/app/slashcommands/command_shortcuts.go b/app/slashcommands/command_shortcuts.go index 30fa1661d8..dd15b960d5 100644 --- a/app/slashcommands/command_shortcuts.go +++ b/app/slashcommands/command_shortcuts.go @@ -39,6 +39,6 @@ func (*ShortcutsProvider) DoCommand(a *app.App, c *request.Context, args *model. // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_shortcuts.unsupported.app_error"), - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, } } diff --git a/app/slashcommands/command_shrug.go b/app/slashcommands/command_shrug.go index 54a07ca908..10430d5951 100644 --- a/app/slashcommands/command_shrug.go +++ b/app/slashcommands/command_shrug.go @@ -41,5 +41,5 @@ func (*ShrugProvider) DoCommand(a *app.App, c *request.Context, args *model.Comm rmsg = message + " " + rmsg } - return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: rmsg} + return &model.CommandResponse{ResponseType: model.CommandResponseTypeInChannel, Text: rmsg} } diff --git a/app/slashcommands/command_test.go b/app/slashcommands/command_test.go index 3fedcc4346..b5feced842 100644 --- a/app/slashcommands/command_test.go +++ b/app/slashcommands/command_test.go @@ -41,7 +41,7 @@ func TestMoveCommand(t *testing.T) { command := &model.Command{} command.CreatorId = model.NewId() - command.Method = model.COMMAND_METHOD_POST + command.Method = model.CommandMethodPost command.TeamId = sourceTeam.Id command.URL = "http://nowhere.com/" command.Trigger = "trigger1" @@ -74,7 +74,7 @@ func TestCreateCommandPost(t *testing.T) { post := &model.Post{ ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, - Type: model.POST_SYSTEM_GENERIC, + Type: model.PostTypeSystemGeneric, } resp := &model.CommandResponse{ @@ -149,8 +149,8 @@ func TestHandleCommandResponsePost(t *testing.T) { } resp := &model.CommandResponse{ - Type: model.POST_DEFAULT, - ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, + Type: model.PostTypeDefault, + ResponseType: model.CommandResponseTypeInChannel, Props: model.StringInterface{"some_key": "some value"}, Text: "some message", } @@ -306,7 +306,7 @@ func TestHandleCommandResponse(t *testing.T) { resp := &model.CommandResponse{ Text: "message 1", - Type: model.POST_SYSTEM_GENERIC, + Type: model.PostTypeSystemGeneric, } builtIn := true @@ -329,7 +329,7 @@ func TestHandleCommandResponse(t *testing.T) { Text: "message 2", }, { - Type: model.POST_SYSTEM_GENERIC, + Type: model.PostTypeSystemGeneric, Text: "message 3", }, }, diff --git a/app/slashcommands/helper_test.go b/app/slashcommands/helper_test.go index 7d1751f6de..2af5049b13 100644 --- a/app/slashcommands/helper_test.go +++ b/app/slashcommands/helper_test.go @@ -152,7 +152,7 @@ func (th *TestHelper) initBasic() *TestHelper { // create users once and cache them because password hashing is slow initBasicOnce.Do(func() { th.SystemAdminUser = th.createUser() - th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id) userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy() @@ -185,7 +185,7 @@ func (th *TestHelper) createTeam() *model.Team { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } utils.DisableDebugLogForTest() @@ -240,11 +240,11 @@ func WithShared(v bool) ChannelOption { } func (th *TestHelper) CreateChannel(team *model.Team, options ...ChannelOption) *model.Channel { - return th.createChannel(team, model.CHANNEL_OPEN, options...) + return th.createChannel(team, model.ChannelTypeOpen, options...) } func (th *TestHelper) createPrivateChannel(team *model.Team) *model.Channel { - return th.createChannel(team, model.CHANNEL_PRIVATE) + return th.createChannel(team, model.ChannelTypePrivate) } func (th *TestHelper) createChannel(team *model.Team, channelType string, options ...ChannelOption) *model.Channel { diff --git a/app/slashcommands/util.go b/app/slashcommands/util.go index e61bb142a1..5d4268a22c 100644 --- a/app/slashcommands/util.go +++ b/app/slashcommands/util.go @@ -19,9 +19,9 @@ const ( // responsef creates an ephemeral command response using printf syntax. func responsef(format string, args ...interface{}) *model.CommandResponse { return &model.CommandResponse{ - ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, + ResponseType: model.CommandResponseTypeEphemeral, Text: fmt.Sprintf(format, args...), - Type: model.POST_DEFAULT, + Type: model.PostTypeDefault, } } diff --git a/app/status.go b/app/status.go index 0c07c70993..c7beb5153e 100644 --- a/app/status.go +++ b/app/status.go @@ -22,8 +22,8 @@ func (a *App) AddStatusCache(status *model.Status) { if a.Cluster() != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_UPDATE_STATUS, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventUpdateStatus, + SendType: model.ClusterSendBestEffort, Data: status.ToClusterJson(), } a.Cluster().SendClusterMessage(msg) @@ -87,7 +87,7 @@ func (a *App) GetStatusesByIds(userIDs []string) (map[string]interface{}, *model // For the case where the user does not have a row in the Status table and cache for _, userID := range missingUserIds { if _, ok := statusMap[userID]; !ok { - statusMap[userID] = model.STATUS_OFFLINE + statusMap[userID] = model.StatusOffline } } @@ -176,21 +176,21 @@ func (a *App) SetStatusOnline(userID string, manual bool) { broadcast := false - var oldStatus string = model.STATUS_OFFLINE + var oldStatus string = model.StatusOffline var oldTime int64 var oldManual bool var status *model.Status var err *model.AppError if status, err = a.GetStatus(userID); err != nil { - status = &model.Status{UserId: userID, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + status = &model.Status{UserId: userID, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} broadcast = true } else { if status.Manual && !manual { return // manually set status always overrides non-manual one } - if status.Status != model.STATUS_ONLINE { + if status.Status != model.StatusOnline { broadcast = true } @@ -198,7 +198,7 @@ func (a *App) SetStatusOnline(userID string, manual bool) { oldTime = status.LastActivityAt oldManual = status.Manual - status.Status = model.STATUS_ONLINE + status.Status = model.StatusOnline status.Manual = false // for "online" there's no manual setting status.LastActivityAt = model.GetMillis() } @@ -207,7 +207,7 @@ func (a *App) SetStatusOnline(userID string, manual bool) { // Only update the database if the status has changed, the status has been manually set, // or enough time has passed since the previous action - if status.Status != oldStatus || status.Manual != oldManual || status.LastActivityAt-oldTime > model.STATUS_MIN_UPDATE_TIME { + if status.Status != oldStatus || status.Manual != oldManual || status.LastActivityAt-oldTime > model.StatusMinUpdateTime { if broadcast { if err := a.Srv().Store.Status().SaveOrUpdate(status); err != nil { mlog.Warn("Failed to save status", mlog.String("user_id", userID), mlog.Err(err), mlog.String("user_id", userID)) @@ -229,7 +229,7 @@ func (a *App) BroadcastStatus(status *model.Status) { // this is considered a non-critical service and will be disabled when server busy. return } - event := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_STATUS_CHANGE, "", "", status.UserId, nil) + event := model.NewWebSocketEvent(model.WebsocketEventStatusChange, "", "", status.UserId, nil) event.Add("status", status.Status) event.Add("user_id", status.UserId) a.Publish(event) @@ -245,7 +245,7 @@ func (a *App) SetStatusOffline(userID string, manual bool) { return // manually set status always overrides non-manual one } - status = &model.Status{UserId: userID, Status: model.STATUS_OFFLINE, Manual: manual, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + status = &model.Status{UserId: userID, Status: model.StatusOffline, Manual: manual, LastActivityAt: model.GetMillis(), ActiveChannel: ""} a.SaveAndBroadcastStatus(status) } @@ -258,7 +258,7 @@ func (a *App) SetStatusAwayIfNeeded(userID string, manual bool) { status, err := a.GetStatus(userID) if err != nil { - status = &model.Status{UserId: userID, Status: model.STATUS_OFFLINE, Manual: manual, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: userID, Status: model.StatusOffline, Manual: manual, LastActivityAt: 0, ActiveChannel: ""} } if !manual && status.Manual { @@ -266,7 +266,7 @@ func (a *App) SetStatusAwayIfNeeded(userID string, manual bool) { } if !manual { - if status.Status == model.STATUS_AWAY { + if status.Status == model.StatusAway { return } @@ -275,7 +275,7 @@ func (a *App) SetStatusAwayIfNeeded(userID string, manual bool) { } } - status.Status = model.STATUS_AWAY + status.Status = model.StatusAway status.Manual = manual status.ActiveChannel = "" @@ -292,11 +292,11 @@ func (a *App) SetStatusDoNotDisturbTimed(userId string, endtime int64) { status, err := a.GetStatus(userId) if err != nil { - status = &model.Status{UserId: userId, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: userId, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } status.PrevStatus = status.Status - status.Status = model.STATUS_DND + status.Status = model.StatusDnd status.Manual = true status.DNDEndTime = endtime @@ -312,10 +312,10 @@ func (a *App) SetStatusDoNotDisturb(userID string) { status, err := a.GetStatus(userID) if err != nil { - status = &model.Status{UserId: userID, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: userID, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } - status.Status = model.STATUS_DND + status.Status = model.StatusDnd status.Manual = true a.SaveAndBroadcastStatus(status) @@ -339,10 +339,10 @@ func (a *App) SetStatusOutOfOffice(userID string) { status, err := a.GetStatus(userID) if err != nil { - status = &model.Status{UserId: userID, Status: model.STATUS_OUT_OF_OFFICE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status = &model.Status{UserId: userID, Status: model.StatusOutOfOffice, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } - status.Status = model.STATUS_OUT_OF_OFFICE + status.Status = model.StatusOutOfOffice status.Manual = true a.SaveAndBroadcastStatus(status) @@ -439,7 +439,7 @@ func (a *App) RemoveCustomStatus(userID string) *model.AppError { func (a *App) addRecentCustomStatus(userID string, status *model.CustomStatus) *model.AppError { var newRCS *model.RecentCustomStatuses - pref, err := a.GetPreferenceByCategoryAndNameForUser(userID, model.PREFERENCE_CATEGORY_CUSTOM_STATUS, model.PREFERENCE_NAME_RECENT_CUSTOM_STATUSES) + pref, err := a.GetPreferenceByCategoryAndNameForUser(userID, model.PreferenceCategoryCustomStatus, model.PreferenceNameRecentCustomStatuses) if err != nil || pref.Value == "" { newRCS = &model.RecentCustomStatuses{*status} } else { @@ -449,8 +449,8 @@ func (a *App) addRecentCustomStatus(userID string, status *model.CustomStatus) * pref = &model.Preference{ UserId: userID, - Category: model.PREFERENCE_CATEGORY_CUSTOM_STATUS, - Name: model.PREFERENCE_NAME_RECENT_CUSTOM_STATUSES, + Category: model.PreferenceCategoryCustomStatus, + Name: model.PreferenceNameRecentCustomStatuses, Value: newRCS.ToJson(), } if err := a.UpdatePreferences(userID, model.Preferences{*pref}); err != nil { @@ -461,7 +461,7 @@ func (a *App) addRecentCustomStatus(userID string, status *model.CustomStatus) * } func (a *App) RemoveRecentCustomStatus(userID string, status *model.CustomStatus) *model.AppError { - pref, err := a.GetPreferenceByCategoryAndNameForUser(userID, model.PREFERENCE_CATEGORY_CUSTOM_STATUS, model.PREFERENCE_NAME_RECENT_CUSTOM_STATUSES) + pref, err := a.GetPreferenceByCategoryAndNameForUser(userID, model.PreferenceCategoryCustomStatus, model.PreferenceNameRecentCustomStatuses) if err != nil { return err } diff --git a/app/status_test.go b/app/status_test.go index 994d1efd29..589e5b81d1 100644 --- a/app/status_test.go +++ b/app/status_test.go @@ -18,10 +18,10 @@ func TestSaveStatus(t *testing.T) { user := th.BasicUser for _, statusString := range []string{ - model.STATUS_ONLINE, - model.STATUS_AWAY, - model.STATUS_DND, - model.STATUS_OFFLINE, + model.StatusOnline, + model.StatusAway, + model.StatusDnd, + model.StatusOffline, } { t.Run(statusString, func(t *testing.T) { status := &model.Status{ diff --git a/app/syncables.go b/app/syncables.go index 4eaa72befd..eab37e3b03 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -236,7 +236,7 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca func (a *App) SyncRolesAndMembership(c *request.Context, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { a.SyncSyncableRoles(syncableID, syncableType) - lastJob, _ := a.Srv().Store.Job().GetNewestJobByStatusAndType(model.JOB_STATUS_SUCCESS, model.JOB_TYPE_LDAP_SYNC) + lastJob, _ := a.Srv().Store.Job().GetNewestJobByStatusAndType(model.JobStatusSuccess, model.JobTypeLdapSync) var since int64 if lastJob != nil { since = lastJob.StartAt diff --git a/app/syncables_test.go b/app/syncables_test.go index f67fd20185..1000d7c55c 100644 --- a/app/syncables_test.go +++ b/app/syncables_test.go @@ -21,7 +21,7 @@ func TestCreateDefaultMemberships(t *testing.T) { DisplayName: "Singers", Name: "zz" + model.NewId(), Email: "singers@test.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) if err != nil { t.Errorf("test team not created: %s", err.Error()) @@ -31,7 +31,7 @@ func TestCreateDefaultMemberships(t *testing.T) { DisplayName: "Nerds", Name: "zz" + model.NewId(), Email: "nerds@test.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, }) if err != nil { t.Errorf("test team not created: %s", err.Error()) @@ -41,7 +41,7 @@ func TestCreateDefaultMemberships(t *testing.T) { TeamId: singersTeam.Id, DisplayName: "Practices", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, false) if err != nil { t.Errorf("test channel not created: %s", err.Error()) @@ -51,7 +51,7 @@ func TestCreateDefaultMemberships(t *testing.T) { TeamId: singersTeam.Id, DisplayName: "Experiments", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, false) if err != nil { t.Errorf("test channel not created: %s", err.Error()) @@ -347,7 +347,7 @@ func TestCreateDefaultMemberships(t *testing.T) { Name: "restricted" + model.NewId(), Email: "restricted@mattermost.org", AllowedDomains: "mattermost.org", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err) _, err = th.App.UpsertGroupSyncable(model.NewGroupTeam(scienceGroup.Id, restrictedTeam.Id, true)) @@ -357,7 +357,7 @@ func TestCreateDefaultMemberships(t *testing.T) { TeamId: restrictedTeam.Id, DisplayName: "Restricted", Name: "restricted" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, false) require.Nil(t, err) _, err = th.App.UpsertGroupSyncable(model.NewGroupChannel(scienceGroup.Id, restrictedChannel.Id, true)) diff --git a/app/team.go b/app/team.go index 5a8b64b548..a47a99d63d 100644 --- a/app/team.go +++ b/app/team.go @@ -161,7 +161,7 @@ func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { return team, err } - a.sendTeamEvent(oldTeam, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(oldTeam, model.WebsocketEventUpdateTeam) return oldTeam, nil } @@ -236,7 +236,7 @@ func (a *App) UpdateTeamScheme(team *model.Team) (*model.Team, *model.AppError) a.ClearTeamMembersCache(team.Id) - a.sendTeamEvent(oldTeam, model.WEBSOCKET_EVENT_UPDATE_TEAM_SCHEME) + a.sendTeamEvent(oldTeam, model.WebsocketEventUpdateTeamScheme) return oldTeam, nil } @@ -248,7 +248,7 @@ func (a *App) UpdateTeamPrivacy(teamID string, teamType string, allowOpenInvite } // Force a regeneration of the invite token if changing a team to restricted. - if (allowOpenInvite != oldTeam.AllowOpenInvite || teamType != oldTeam.Type) && (!allowOpenInvite || teamType == model.TEAM_INVITE) { + if (allowOpenInvite != oldTeam.AllowOpenInvite || teamType != oldTeam.Type) && (!allowOpenInvite || teamType == model.TeamInvite) { oldTeam.InviteId = model.NewId() } @@ -269,7 +269,7 @@ func (a *App) UpdateTeamPrivacy(teamID string, teamType string, allowOpenInvite } } - a.sendTeamEvent(oldTeam, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(oldTeam, model.WebsocketEventUpdateTeam) return nil } @@ -294,7 +294,7 @@ func (a *App) PatchTeam(teamID string, patch *model.TeamPatch) (*model.Team, *mo return team, err } - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventUpdateTeam) return team, nil } @@ -321,7 +321,7 @@ func (a *App) RegenerateTeamInviteId(teamID string) (*model.Team, *model.AppErro } } - a.sendTeamEvent(updatedTeam, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(updatedTeam, model.WebsocketEventUpdateTeam) return updatedTeam, nil } @@ -332,7 +332,7 @@ func (a *App) sendTeamEvent(team *model.Team, event string) { sanitizedTeam.Sanitize() teamID := "" // no filtering by teamID by default - if event == model.WEBSOCKET_EVENT_UPDATE_TEAM { + if event == model.WebsocketEventUpdateTeam { // in case of update_team event - we send the message only to members of that team teamID = team.Id } @@ -355,7 +355,7 @@ func (a *App) GetSchemeRolesForTeam(teamID string) (string, string, string, *mod return scheme.DefaultTeamGuestRole, scheme.DefaultTeamUserRole, scheme.DefaultTeamAdminRole, nil } - return model.TEAM_GUEST_ROLE_ID, model.TEAM_USER_ROLE_ID, model.TEAM_ADMIN_ROLE_ID, nil + return model.TeamGuestRoleId, model.TeamUserRoleId, model.TeamAdminRoleId, nil } func (a *App) UpdateTeamMemberRoles(teamID string, userID string, newRoles string) (*model.TeamMember, *model.AppError) { @@ -456,7 +456,7 @@ func (a *App) UpdateTeamMemberSchemeRoles(teamID string, userID string, isScheme // If the migration is not completed, we also need to check the default team_admin/team_user roles are not present in the roles field. if err = a.IsPhase2MigrationCompleted(); err != nil { - member.ExplicitRoles = RemoveRoles([]string{model.TEAM_GUEST_ROLE_ID, model.TEAM_USER_ROLE_ID, model.TEAM_ADMIN_ROLE_ID}, member.ExplicitRoles) + member.ExplicitRoles = RemoveRoles([]string{model.TeamGuestRoleId, model.TeamUserRoleId, model.TeamAdminRoleId}, member.ExplicitRoles) } member, nErr := a.Srv().Store.Team().UpdateMember(member) @@ -478,7 +478,7 @@ func (a *App) UpdateTeamMemberSchemeRoles(teamID string, userID string, isScheme } func (a *App) sendUpdatedMemberRoleEvent(userID string, member *model.TeamMember) { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_MEMBERROLE_UPDATED, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventMemberroleUpdated, "", "", userID, nil) message.Add("member", member.ToJson()) a.Publish(message) } @@ -820,7 +820,7 @@ func (a *App) JoinUserToTeam(c *request.Context, team *model.Team, user *model.U a.InvalidateCacheForUser(user.Id) a.invalidateCacheForUserTeams(user.Id) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, "", "", user.Id, nil) + message := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, "", "", user.Id, nil) message.Add("team_id", team.Id) message.Add("user_id", user.Id) a.Publish(message) @@ -1030,7 +1030,7 @@ func (a *App) AddTeamMember(c *request.Context, teamID, userID string) (*model.T return nil, err } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, "", "", userID, nil) message.Add("team_id", teamID) message.Add("user_id", userID) a.Publish(message) @@ -1059,7 +1059,7 @@ func (a *App) AddTeamMembers(c *request.Context, teamID string, userIDs []string Member: teamMember, }) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, "", "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, "", "", userID, nil) message.Add("team_id", teamID) message.Add("user_id", userID) a.Publish(message) @@ -1108,7 +1108,7 @@ func (a *App) GetTeamUnread(teamID, userID string) (*model.TeamUnread, *model.Ap teamUnread.MentionCount += cu.MentionCount teamUnread.MentionCountRoot += cu.MentionCountRoot - if cu.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.CHANNEL_MARK_UNREAD_MENTION { + if cu.NotifyProps[model.MarkUnreadNotifyProp] != model.ChannelMarkUnreadMention { teamUnread.MsgCount += cu.MsgCount teamUnread.MsgCountRoot += cu.MsgCountRoot } @@ -1165,7 +1165,7 @@ func (a *App) RemoveUserFromTeam(c *request.Context, teamID string, userID strin func (a *App) RemoveTeamMemberFromTeam(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError { // Send the websocket message before we actually do the remove so the user being removed gets it. - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LEAVE_TEAM, teamMember.TeamId, "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventLeaveTeam, teamMember.TeamId, "", "", nil) message.Add("user_id", teamMember.UserId) message.Add("team_id", teamMember.TeamId) a.Publish(message) @@ -1256,7 +1256,7 @@ func (a *App) LeaveTeam(c *request.Context, team *model.Team, user *model.User, } } - channel, nErr := a.Srv().Store.Channel().GetByName(team.Id, model.DEFAULT_CHANNEL, false) + channel, nErr := a.Srv().Store.Channel().GetByName(team.Id, model.DefaultChannelName, false) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -1290,7 +1290,7 @@ func (a *App) postLeaveTeamMessage(c *request.Context, user *model.User, channel post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.leave.left"), user.Username), - Type: model.POST_LEAVE_TEAM, + Type: model.PostTypeLeaveTeam, UserId: user.Id, Props: model.StringInterface{ "username": user.Username, @@ -1308,7 +1308,7 @@ func (a *App) postRemoveFromTeamMessage(c *request.Context, user *model.User, ch post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.remove_user_from_team.removed"), user.Username), - Type: model.POST_REMOVE_FROM_TEAM, + Type: model.PostTypeRemoveFromTeam, UserId: user.Id, Props: model.StringInterface{ "username": user.Username, @@ -1667,7 +1667,7 @@ func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userID string) ([]*mod tu.MentionCount += cu.MentionCount tu.MentionCountRoot += cu.MentionCountRoot - if cu.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.CHANNEL_MARK_UNREAD_MENTION { + if cu.NotifyProps[model.MarkUnreadNotifyProp] != model.ChannelMarkUnreadMention { tu.MsgCount += cu.MsgCount tu.MsgCountRoot += cu.MsgCountRoot } @@ -1744,7 +1744,7 @@ func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { return model.NewAppError("PermanentDeleteTeam", "app.team.permanent_delete.app_error", nil, err.Error(), http.StatusInternalServerError) } - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_DELETE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventDeleteTeam) return nil } @@ -1770,7 +1770,7 @@ func (a *App) SoftDeleteTeam(teamID string) *model.AppError { } } - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_DELETE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventDeleteTeam) return nil } @@ -1796,7 +1796,7 @@ func (a *App) RestoreTeam(teamID string) *model.AppError { } } - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_RESTORE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventRestoreTeam) return nil } @@ -1868,11 +1868,11 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { } func (a *App) SanitizeTeam(session model.Session, team *model.Team) *model.Team { - if a.SessionHasPermissionToTeam(session, team.Id, model.PERMISSION_MANAGE_TEAM) { + if a.SessionHasPermissionToTeam(session, team.Id, model.PermissionManageTeam) { return team } - if a.SessionHasPermissionToTeam(session, team.Id, model.PERMISSION_INVITE_USER) { + if a.SessionHasPermissionToTeam(session, team.Id, model.PermissionInviteUser) { inviteId := team.InviteId team.Sanitize() team.InviteId = inviteId @@ -1969,7 +1969,7 @@ func (a *App) SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppEr // manually set time to avoid possible cluster inconsistencies team.LastTeamIconUpdate = curTime - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventUpdateTeam) return nil } @@ -1986,7 +1986,7 @@ func (a *App) RemoveTeamIcon(teamID string) *model.AppError { team.LastTeamIconUpdate = 0 - a.sendTeamEvent(team, model.WEBSOCKET_EVENT_UPDATE_TEAM) + a.sendTeamEvent(team, model.WebsocketEventUpdateTeam) return nil } @@ -2015,7 +2015,7 @@ func (a *App) ClearTeamMembersCache(teamID string) { for _, teamMember := range teamMembers { a.ClearSessionCacheForUser(teamMember.UserId) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_MEMBERROLE_UPDATED, "", "", teamMember.UserId, nil) + message := model.NewWebSocketEvent(model.WebsocketEventMemberroleUpdated, "", "", teamMember.UserId, nil) message.Add("member", teamMember.ToJson()) a.Publish(message) } diff --git a/app/team_test.go b/app/team_test.go index a8112f527c..67f3d9e7bf 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -27,7 +27,7 @@ func TestCreateTeam(t *testing.T) { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } _, err := th.App.CreateTeam(th.Context, team) @@ -46,7 +46,7 @@ func TestCreateTeamWithUser(t *testing.T) { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } _, err := th.App.CreateTeamWithUser(th.Context, team, th.BasicUser.Id) @@ -466,7 +466,7 @@ func TestPermanentDeleteTeam(t *testing.T) { DisplayName: "deletion-test", Name: "deletion-test", Email: "foo@foo.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.Nil(t, err, "Should create a team") @@ -479,7 +479,7 @@ func TestPermanentDeleteTeam(t *testing.T) { TeamId: team.Id, Trigger: "foo", URL: "http://foo", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, }) require.Nil(t, err, "Should create a command") defer th.App.DeleteCommand(command.Id) @@ -533,12 +533,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("not a user of the team", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: model.NewId(), - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }, } @@ -551,12 +551,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("user of the team", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: team.Id, - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }, } @@ -569,12 +569,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("team admin", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: team.Id, - Roles: model.TEAM_USER_ROLE_ID + " " + model.TEAM_ADMIN_ROLE_ID, + Roles: model.TeamUserRoleId + " " + model.TeamAdminRoleId, }, }, } @@ -587,12 +587,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("team admin of another team", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: model.NewId(), - Roles: model.TEAM_USER_ROLE_ID + " " + model.TEAM_ADMIN_ROLE_ID, + Roles: model.TeamUserRoleId + " " + model.TeamAdminRoleId, }, }, } @@ -605,12 +605,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("system admin, not a user of team", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: model.NewId(), - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }, } @@ -623,12 +623,12 @@ func TestSanitizeTeam(t *testing.T) { t.Run("system admin, user of team", func(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: team.Id, - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }, } @@ -659,17 +659,17 @@ func TestSanitizeTeams(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: teams[0].Id, - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, { UserId: userID, TeamId: teams[1].Id, - Roles: model.TEAM_USER_ROLE_ID + " " + model.TEAM_ADMIN_ROLE_ID, + Roles: model.TeamUserRoleId + " " + model.TeamAdminRoleId, }, }, } @@ -696,12 +696,12 @@ func TestSanitizeTeams(t *testing.T) { userID := model.NewId() session := model.Session{ - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, TeamMembers: []*model.TeamMember{ { UserId: userID, TeamId: teams[0].Id, - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }, } @@ -721,7 +721,7 @@ func TestJoinUserToTeam(t *testing.T) { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } _, err := th.App.CreateTeam(th.Context, team) diff --git a/app/user.go b/app/user.go index 66c3966742..7ff114fa4d 100644 --- a/app/user.go +++ b/app/user.go @@ -258,7 +258,7 @@ func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool a.sendUpdatedUserEvent(*nUser) } - pref := model.Preference{UserId: ruser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: ruser.Id, Value: "0"} + pref := model.Preference{UserId: ruser.Id, Category: model.PreferenceCategoryTutorialSteps, Name: ruser.Id, Value: "0"} if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil { mlog.Warn("Encountered error saving tutorial preference", mlog.Err(err)) } @@ -266,7 +266,7 @@ func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool go a.UpdateViewedProductNoticesForNewUser(ruser.Id) // This message goes to everyone, so the teamID, channelID and userID are irrelevant - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_NEW_USER, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventNewUser, "", "", "", nil) message.Add("user_id", ruser.Id) a.Publish(message) @@ -317,7 +317,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re userByEmail, _ := a.srv.userService.GetUserByEmail(user.Email) if userByEmail != nil { if userByEmail.AuthService == "" { - return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.USER_AUTH_SERVICE_EMAIL}, "email="+user.Email, http.StatusBadRequest) + return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) } if provider.IsSameUser(userByEmail, user) { if _, err := a.Srv().Store.User().UpdateAuthData(userByEmail.Id, user.AuthService, user.AuthData, "", false); err != nil { @@ -661,7 +661,7 @@ func (a *App) ActivateMfa(userID, token string) *model.AppError { return appErr } - if user.AuthService != "" && user.AuthService != model.USER_AUTH_SERVICE_LDAP { + if user.AuthService != "" && user.AuthService != model.UserAuthServiceLdap { return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest) } @@ -735,7 +735,7 @@ func (a *App) SetDefaultProfileImage(user *model.User) *model.AppError { options := a.Config().GetSanitizeOptions() updatedUser.SanitizeProfile(options) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserUpdated, "", "", "", nil) message.Add("user", updatedUser) a.Publish(message) @@ -926,7 +926,7 @@ func (a *App) DeactivateGuests(c *request.Context) *model.AppError { a.Srv().Store.Channel().ClearCaches() a.Srv().Store.User().ClearCaches() - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_GUESTS_DEACTIVATED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventGuestsDeactivated, "", "", "", nil) a.Publish(message) return nil @@ -1016,13 +1016,13 @@ func (a *App) UpdateUserAuth(userID string, userAuth *model.UserAuth) (*model.Us func (a *App) sendUpdatedUserEvent(user model.User) { adminCopyOfUser := user.DeepCopy() a.SanitizeProfile(adminCopyOfUser, true) - adminMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil) + adminMessage := model.NewWebSocketEvent(model.WebsocketEventUserUpdated, "", "", "", nil) adminMessage.Add("user", adminCopyOfUser) adminMessage.GetBroadcast().ContainsSensitiveData = true a.Publish(adminMessage) a.SanitizeProfile(&user, false) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserUpdated, "", "", "", nil) message.Add("user", &user) message.GetBroadcast().ContainsSanitizedData = true a.Publish(message) @@ -1409,7 +1409,7 @@ func (a *App) UpdateUserRolesWithUser(user *model.User, newRoles string, sendWeb a.ClearSessionCacheForUser(user.Id) if sendWebSocketEvent { - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ROLE_UPDATED, "", "", user.Id, nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserRoleUpdated, "", "", user.Id, nil) message.Add("user_id", user.Id) message.Add("roles", newRoles) a.Publish(message) @@ -1420,7 +1420,7 @@ func (a *App) UpdateUserRolesWithUser(user *model.User, newRoles string, sendWeb func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.AppError { mlog.Warn("Attempting to permanently delete account", mlog.String("user_id", user.Id), mlog.String("user_email", user.Email)) - if user.IsInRole(model.SYSTEM_ADMIN_ROLE_ID) { + if user.IsInRole(model.SystemAdminRoleId) { mlog.Warn("You are deleting a user that is a system administrator. You may need to set another account as the system administrator using the command line tools.", mlog.String("user_email", user.Email)) } @@ -1808,7 +1808,7 @@ func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model return autocomplete, nil } -func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string, tokenUser *model.User) *model.AppError { +func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError { oauthUser, err1 := provider.GetUserFromJson(userData, tokenUser) if err1 != nil { return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]interface{}{"Service": service}, err1.Error(), http.StatusBadRequest) @@ -1977,7 +1977,7 @@ func (a *App) userBelongsToChannels(userID string, channelIDs []string) (bool, * } func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestrictions, *model.AppError) { - if a.HasPermissionTo(userID, model.PERMISSION_VIEW_MEMBERS) { + if a.HasPermissionTo(userID, model.PermissionViewMembers) { return nil, nil } @@ -1988,7 +1988,7 @@ func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestricti teamIDsWithPermission := []string{} for _, teamID := range teamIDs { - if a.HasPermissionToTeam(userID, teamID, model.PERMISSION_VIEW_MEMBERS) { + if a.HasPermissionToTeam(userID, teamID, model.PermissionViewMembers) { teamIDsWithPermission = append(teamIDsWithPermission, teamID) } } @@ -2052,7 +2052,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor for _, member := range *channelMembers { a.invalidateCacheForChannelMembers(member.ChannelId) - evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", user.Id, nil) + evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", user.Id, nil) evt.Add("channelMember", member.ToJson()) a.Publish(evt) } @@ -2093,7 +2093,7 @@ func (a *App) DemoteUserToGuest(user *model.User) *model.AppError { for _, member := range *channelMembers { a.invalidateCacheForChannelMembers(member.ChannelId) - evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", user.Id, nil) + evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", user.Id, nil) evt.Add("channelMember", member.ToJson()) a.Publish(evt) } @@ -2107,7 +2107,7 @@ func (a *App) PublishUserTyping(userID, channelID, parentId string) *model.AppEr omitUsers := make(map[string]bool, 1) omitUsers[userID] = true - event := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_TYPING, "", channelID, "", omitUsers) + event := model.NewWebSocketEvent(model.WebsocketEventTyping, "", channelID, "", omitUsers) event.Add("parent_id", parentId) event.Add("user_id", userID) a.Publish(event) @@ -2128,7 +2128,7 @@ func (a *App) invalidateUserCacheAndPublish(userID string) { options := a.Config().GetSanitizeOptions() user.SanitizeProfile(options) - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil) + message := model.NewWebSocketEvent(model.WebsocketEventUserUpdated, "", "", "", nil) message.Add("user", user) a.Publish(message) } @@ -2158,10 +2158,10 @@ func (a *App) ConvertBotToUser(bot *model.Bot, userPatch *model.UserPatch, sysad } } - if sysadmin && !user.IsInRole(model.SYSTEM_ADMIN_ROLE_ID) { + if sysadmin && !user.IsInRole(model.SystemAdminRoleId) { _, appErr := a.UpdateUserRoles( user.Id, - fmt.Sprintf("%s %s", user.Roles, model.SYSTEM_ADMIN_ROLE_ID), + fmt.Sprintf("%s %s", user.Roles, model.SystemAdminRoleId), false) if appErr != nil { return nil, appErr @@ -2229,7 +2229,7 @@ func (a *App) UpdateThreadsReadForUser(userID, teamID string) *model.AppError { if nErr != nil { return model.NewAppError("UpdateThreadsReadForUser", "app.user.update_threads_read_for_user.app_error", nil, nErr.Error(), http.StatusInternalServerError) } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_READ_CHANGED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadReadChanged, teamID, "", userID, nil) a.Publish(message) return nil } @@ -2254,7 +2254,7 @@ func (a *App) UpdateThreadFollowForUser(userID, teamID, threadID string, state b if thread != nil { replyCount = thread.ReplyCount } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_FOLLOW_CHANGED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadFollowChanged, teamID, "", userID, nil) message.Add("thread_id", threadID) message.Add("state", state) message.Add("reply_count", replyCount) @@ -2301,7 +2301,7 @@ func (a *App) UpdateThreadReadForUser(userID, teamID, threadID string, timestamp return nil, err } - message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_READ_CHANGED, teamID, "", userID, nil) + message := model.NewWebSocketEvent(model.WebsocketEventThreadReadChanged, teamID, "", userID, nil) message.Add("thread_id", threadID) message.Add("timestamp", timestamp) message.Add("unread_mentions", membership.UnreadMentions) diff --git a/app/user_test.go b/app/user_test.go index 5367c72d63..3e03146747 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -38,7 +38,7 @@ func TestCreateOAuthUser(t *testing.T) { glUser := oauthgitlab.GitLabUser{Id: 42, Username: "o" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", Name: "Joram Wilander"} json := glUser.ToJson() - user, err := th.App.CreateOAuthUser(th.Context, model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id, nil) + user, err := th.App.CreateOAuthUser(th.Context, model.UserAuthServiceGitlab, strings.NewReader(json), th.BasicTeam.Id, nil) require.Nil(t, err) require.Equal(t, glUser.Username, user.Username, "usernames didn't match") @@ -55,18 +55,18 @@ func TestCreateOAuthUser(t *testing.T) { // mock oAuth Provider, return data mockUser := &model.User{Id: "abcdef", AuthData: model.NewString("e7110007-64be-43d8-9840-4a7e9c26b710"), Email: dbUser.Email} - providerMock := &mocks.OauthProvider{} + providerMock := &mocks.OAuthProvider{} providerMock.On("IsSameUser", mock.Anything, mock.Anything).Return(true) providerMock.On("GetUserFromJson", mock.Anything, mock.Anything).Return(mockUser, nil) - einterfaces.RegisterOauthProvider(model.SERVICE_OFFICE365, providerMock) + einterfaces.RegisterOAuthProvider(model.ServiceOffice365, providerMock) // Update user to be OAuth, formatting to match Office365 OAuth data - s, er2 := th.App.Srv().Store.User().UpdateAuthData(dbUser.Id, model.SERVICE_OFFICE365, model.NewString("e711000764be43d898404a7e9c26b710"), "", false) + s, er2 := th.App.Srv().Store.User().UpdateAuthData(dbUser.Id, model.ServiceOffice365, model.NewString("e711000764be43d898404a7e9c26b710"), "", false) assert.NoError(t, er2) assert.Equal(t, dbUser.Id, s) // data passed doesn't matter as return is mocked - _, err := th.App.CreateOAuthUser(th.Context, model.SERVICE_OFFICE365, strings.NewReader("{}"), th.BasicTeam.Id, nil) + _, err := th.App.CreateOAuthUser(th.Context, model.ServiceOffice365, strings.NewReader("{}"), th.BasicTeam.Id, nil) assert.Nil(t, err) u, er := th.App.Srv().Store.User().GetByEmail(dbUser.Email) assert.NoError(t, er) @@ -76,7 +76,7 @@ func TestCreateOAuthUser(t *testing.T) { t.Run("user creation disabled", func(t *testing.T) { *th.App.Config().TeamSettings.EnableUserCreation = false - _, err := th.App.CreateOAuthUser(th.Context, model.USER_AUTH_SERVICE_GITLAB, strings.NewReader("{}"), th.BasicTeam.Id, nil) + _, err := th.App.CreateOAuthUser(th.Context, model.UserAuthServiceGitlab, strings.NewReader("{}"), th.BasicTeam.Id, nil) require.NotNil(t, err, "should have failed - user creation disabled") }) } @@ -249,7 +249,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true }) - gitlabProvider := einterfaces.GetOauthProvider("gitlab") + gitlabProvider := einterfaces.GetOAuthProvider("gitlab") username := "user" + id username2 := "user" + id2 @@ -568,7 +568,7 @@ func TestGetUsersByStatus(t *testing.T) { channel, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, CreatorId: model.NewId(), }, false) @@ -598,14 +598,14 @@ func TestGetUsersByStatus(t *testing.T) { } // Creating these out of order in case that affects results - awayUser1 := createUserWithStatus("away1", model.STATUS_AWAY) - awayUser2 := createUserWithStatus("away2", model.STATUS_AWAY) - dndUser1 := createUserWithStatus("dnd1", model.STATUS_DND) - dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND) - offlineUser1 := createUserWithStatus("offline1", model.STATUS_OFFLINE) - offlineUser2 := createUserWithStatus("offline2", model.STATUS_OFFLINE) - onlineUser1 := createUserWithStatus("online1", model.STATUS_ONLINE) - onlineUser2 := createUserWithStatus("online2", model.STATUS_ONLINE) + awayUser1 := createUserWithStatus("away1", model.StatusAway) + awayUser2 := createUserWithStatus("away2", model.StatusAway) + dndUser1 := createUserWithStatus("dnd1", model.StatusDnd) + dndUser2 := createUserWithStatus("dnd2", model.StatusDnd) + offlineUser1 := createUserWithStatus("offline1", model.StatusOffline) + offlineUser2 := createUserWithStatus("offline2", model.StatusOffline) + onlineUser1 := createUserWithStatus("online1", model.StatusOnline) + onlineUser2 := createUserWithStatus("online2", model.StatusOnline) t.Run("sorting by status then alphabetical", func(t *testing.T) { usersByStatus, err := th.App.GetUsersInChannelPageByStatus(&model.UserGetOptions{ @@ -1036,15 +1036,15 @@ func TestGetViewUsersRestrictions(t *testing.T) { }) t.Run("VIEW_MEMBERS permission granted at team level", func(t *testing.T) { - systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId) require.Nil(t, err) - teamUserRole, err := th.App.GetRoleByName(context.Background(), model.TEAM_USER_ROLE_ID) + teamUserRole, err := th.App.GetRoleByName(context.Background(), model.TeamUserRoleId) require.Nil(t, err) - require.Nil(t, removePermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id)) - defer addPermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id) - require.Nil(t, addPermission(teamUserRole, model.PERMISSION_VIEW_MEMBERS.Id)) - defer removePermission(teamUserRole, model.PERMISSION_VIEW_MEMBERS.Id) + require.Nil(t, removePermission(systemUserRole, model.PermissionViewMembers.Id)) + defer addPermission(systemUserRole, model.PermissionViewMembers.Id) + require.Nil(t, addPermission(teamUserRole, model.PermissionViewMembers.Id)) + defer removePermission(teamUserRole, model.PermissionViewMembers.Id) restrictions, err := th.App.GetViewUsersRestrictions(user1.Id) require.Nil(t, err) @@ -1057,10 +1057,10 @@ func TestGetViewUsersRestrictions(t *testing.T) { }) t.Run("VIEW_MEMBERS permission not granted at any level", func(t *testing.T) { - systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId) require.Nil(t, err) - require.Nil(t, removePermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id)) - defer addPermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id) + require.Nil(t, removePermission(systemUserRole, model.PermissionViewMembers.Id)) + defer addPermission(systemUserRole, model.PermissionViewMembers.Id) restrictions, err := th.App.GetViewUsersRestrictions(user1.Id) require.Nil(t, err) @@ -1072,15 +1072,15 @@ func TestGetViewUsersRestrictions(t *testing.T) { }) t.Run("VIEW_MEMBERS permission for some teams but not for others", func(t *testing.T) { - systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + systemUserRole, err := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId) require.Nil(t, err) - teamAdminRole, err := th.App.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID) + teamAdminRole, err := th.App.GetRoleByName(context.Background(), model.TeamAdminRoleId) require.Nil(t, err) - require.Nil(t, removePermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id)) - defer addPermission(systemUserRole, model.PERMISSION_VIEW_MEMBERS.Id) - require.Nil(t, addPermission(teamAdminRole, model.PERMISSION_VIEW_MEMBERS.Id)) - defer removePermission(teamAdminRole, model.PERMISSION_VIEW_MEMBERS.Id) + require.Nil(t, removePermission(systemUserRole, model.PermissionViewMembers.Id)) + defer addPermission(systemUserRole, model.PermissionViewMembers.Id) + require.Nil(t, addPermission(teamAdminRole, model.PermissionViewMembers.Id)) + defer removePermission(teamAdminRole, model.PermissionViewMembers.Id) restrictions, err := th.App.GetViewUsersRestrictions(user1.Id) require.Nil(t, err) @@ -1444,12 +1444,12 @@ func TestUpdateUserRolesWithUser(t *testing.T) { // Create normal user. user := th.CreateUser() - assert.Equal(t, user.Roles, model.SYSTEM_USER_ROLE_ID) + assert.Equal(t, user.Roles, model.SystemUserRoleId) // Upgrade to sysadmin. - user, err := th.App.UpdateUserRolesWithUser(user, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + user, err := th.App.UpdateUserRolesWithUser(user, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) require.Nil(t, err) - assert.Equal(t, user.Roles, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID) + assert.Equal(t, user.Roles, model.SystemUserRoleId+" "+model.SystemAdminRoleId) // Test bad role. _, err = th.App.UpdateUserRolesWithUser(user, "does not exist", false) @@ -1512,7 +1512,7 @@ func TestUpdateThreadReadForUser(t *testing.T) { defer th.TearDown() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ThreadAutoFollow = true - *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON + *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn }) t.Run("Ensure thread membership is created and followed", func(t *testing.T) { diff --git a/app/web_conn.go b/app/web_conn.go index 815100c4ca..3a6fecb63d 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -272,7 +272,7 @@ func (wc *WebConn) readPump() { defer func() { wc.WebSocket.Close() }() - wc.WebSocket.SetReadLimit(model.SOCKET_MAX_MESSAGE_SIZE_KB) + wc.WebSocket.SetReadLimit(model.SocketMaxMessageSizeKb) wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)) wc.WebSocket.SetPongHandler(func(string) error { wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)) @@ -357,9 +357,9 @@ func (wc *WebConn) writePump() { if len(wc.send) >= sendSlowWarn { // When the pump starts to get slow we'll drop non-critical messages switch msg.EventType() { - case model.WEBSOCKET_EVENT_TYPING, - model.WEBSOCKET_EVENT_STATUS_CHANGE, - model.WEBSOCKET_EVENT_CHANNEL_VIEWED: + case model.WebsocketEventTyping, + model.WebsocketEventStatusChange, + model.WebsocketEventChannelViewed: mlog.Warn( "websocket.slow: dropping message", mlog.String("user_id", wc.UserId), @@ -582,7 +582,7 @@ func (wc *WebConn) IsAuthenticated() bool { } func (wc *WebConn) createHelloMessage() *model.WebSocketEvent { - msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", wc.UserId, nil) + msg := model.NewWebSocketEvent(model.WebsocketEventHello, "", "", wc.UserId, nil) msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), @@ -596,14 +596,14 @@ func (wc *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { var canSee bool switch msg.EventType() { - case model.WEBSOCKET_EVENT_USER_UPDATED: + case model.WebsocketEventUserUpdated: user, ok := msg.GetData()["user"].(*model.User) if !ok { mlog.Debug("webhub.shouldSendEvent: user not found in message", mlog.Any("user", msg.GetData()["user"])) return false } userID = user.Id - case model.WEBSOCKET_EVENT_NEW_USER: + case model.WebsocketEventNewUser: userID = msg.GetData()["user_id"].(string) default: return true @@ -629,7 +629,7 @@ func (wc *WebConn) shouldSendEvent(msg *model.WebSocketEvent) bool { // see sensitive data. Prevents admin clients from receiving events with bad data var hasReadPrivateDataPermission *bool if msg.GetBroadcast().ContainsSanitizedData { - hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) + hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) if *hasReadPrivateDataPermission { return false @@ -639,7 +639,7 @@ func (wc *WebConn) shouldSendEvent(msg *model.WebSocketEvent) bool { // If the event contains sensitive data, only send to users with permission to see it if msg.GetBroadcast().ContainsSensitiveData { if hasReadPrivateDataPermission == nil { - hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) + hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) } if !*hasReadPrivateDataPermission { @@ -687,7 +687,7 @@ func (wc *WebConn) shouldSendEvent(msg *model.WebSocketEvent) bool { return wc.isMemberOfTeam(msg.GetBroadcast().TeamId) } - if wc.GetSession().Props[model.SESSION_PROP_IS_GUEST] == "true" { + if wc.GetSession().Props[model.SessionPropIsGuest] == "true" { return wc.shouldSendEventToGuest(msg) } diff --git a/app/web_conn_test.go b/app/web_conn_test.go index b49889e50d..2dfa715ad4 100644 --- a/app/web_conn_test.go +++ b/app/web_conn_test.go @@ -25,7 +25,7 @@ func TestWebConnShouldSendEvent(t *testing.T) { { UserId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, - Roles: model.TEAM_USER_ROLE_ID, + Roles: model.TeamUserRoleId, }, }}) require.Nil(t, err) @@ -44,7 +44,7 @@ func TestWebConnShouldSendEvent(t *testing.T) { { UserId: th.BasicUser2.Id, TeamId: th.BasicTeam.Id, - Roles: model.TEAM_ADMIN_ROLE_ID, + Roles: model.TeamAdminRoleId, }, }}) require.Nil(t, err) @@ -96,11 +96,11 @@ func TestWebConnShouldSendEvent(t *testing.T) { assert.Equal(t, c.AdminExpected, adminUserWc.shouldSendEvent(event), c.Description) } - event2 := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_UPDATE_TEAM, th.BasicTeam.Id, "", "", nil) + event2 := model.NewWebSocketEvent(model.WebsocketEventUpdateTeam, th.BasicTeam.Id, "", "", nil) assert.True(t, basicUserWc.shouldSendEvent(event2)) assert.True(t, basicUser2Wc.shouldSendEvent(event2)) - event3 := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_UPDATE_TEAM, "wrongId", "", "", nil) + event3 := model.NewWebSocketEvent(model.WebsocketEventUpdateTeam, "wrongId", "", "", nil) assert.False(t, basicUserWc.shouldSendEvent(event3)) } diff --git a/app/web_hub.go b/app/web_hub.go index 713d410690..b714f2d95f 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -169,17 +169,17 @@ func (s *Server) Publish(message *model.WebSocketEvent) { if s.Cluster != nil { cm := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_PUBLISH, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventPublish, + SendType: model.ClusterSendBestEffort, Data: message.ToJson(), } - if message.EventType() == model.WEBSOCKET_EVENT_POSTED || - message.EventType() == model.WEBSOCKET_EVENT_POST_EDITED || - message.EventType() == model.WEBSOCKET_EVENT_DIRECT_ADDED || - message.EventType() == model.WEBSOCKET_EVENT_GROUP_ADDED || - message.EventType() == model.WEBSOCKET_EVENT_ADDED_TO_TEAM { - cm.SendType = model.CLUSTER_SEND_RELIABLE + if message.EventType() == model.WebsocketEventPosted || + message.EventType() == model.WebsocketEventPostEdited || + message.EventType() == model.WebsocketEventDirectAdded || + message.EventType() == model.WebsocketEventGroupAdded || + message.EventType() == model.WebsocketEventAddedToTeam { + cm.SendType = model.ClusterSendReliable } s.Cluster.SendClusterMessage(cm) @@ -212,8 +212,8 @@ func (a *App) invalidateCacheForChannel(channel *model.Channel) { if a.Cluster() != nil { nameMsg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventInvalidateCacheForChannelByName, + SendType: model.ClusterSendBestEffort, Props: make(map[string]string), } @@ -239,8 +239,8 @@ func (a *App) invalidateCacheForChannelMembersNotifyProps(channelID string) { if a.Cluster() != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, + SendType: model.ClusterSendBestEffort, Data: channelID, } a.Cluster().SendClusterMessage(msg) @@ -264,8 +264,8 @@ func (a *App) invalidateCacheForUserTeams(userID string) { if a.Cluster() != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventInvalidateCacheForUserTeams, + SendType: model.ClusterSendBestEffort, Data: userID, } a.Cluster().SendClusterMessage(msg) diff --git a/app/web_hub_test.go b/app/web_hub_test.go index a5ec5e8d7a..d15b758f51 100644 --- a/app/web_hub_test.go +++ b/app/web_hub_test.go @@ -149,7 +149,7 @@ func TestHubSessionRevokeRace(t *testing.T) { mockSessionStore.On("Remove", "id1").Return(nil) mockStatusStore := mocks.StatusStore{} - mockStatusStore.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil) + mockStatusStore.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) mockStatusStore.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) mockStatusStore.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) diff --git a/app/webhook.go b/app/webhook.go index 6e3300be20..729a5f5286 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -31,7 +31,7 @@ func (a *App) handleWebhookEvents(c *request.Context, post *model.Post, team *mo return nil } - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { return nil } @@ -116,7 +116,7 @@ func (a *App) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookP if webhookResp != nil && (webhookResp.Text != nil || len(webhookResp.Attachments) > 0) { postRootId := "" - if webhookResp.ResponseType == model.OUTGOING_HOOK_RESPONSE_TYPE_COMMENT { + if webhookResp.ResponseType == model.OutgoingHookResponseTypeComment { postRootId = post.Id } if len(webhookResp.Props) == 0 { @@ -180,8 +180,8 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. } } - if utf8.RuneCountInString(model.StringInterfaceToJson(base.GetProps())) > model.POST_PROPS_MAX_USER_RUNES { - return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.POST_PROPS_MAX_USER_RUNES}, "", http.StatusBadRequest) + if utf8.RuneCountInString(model.StringInterfaceToJson(base.GetProps())) > model.PostPropsMaxUserRunes { + return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) } for utf8.RuneCountInString(remainingText) > maxPostSize { @@ -216,7 +216,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. newPropsString := model.StringInterfaceToJson(newProps) runeCount := utf8.RuneCountInString(newPropsString) - if runeCount <= model.POST_PROPS_MAX_USER_RUNES { + if runeCount <= model.PostPropsMaxUserRunes { lastSplit.SetProps(newProps) break } @@ -227,10 +227,10 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. continue } - truncationNeeded := runeCount - model.POST_PROPS_MAX_USER_RUNES + truncationNeeded := runeCount - model.PostPropsMaxUserRunes textRuneCount := utf8.RuneCountInString(attachment.Text) if textRuneCount < truncationNeeded { - return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.POST_PROPS_MAX_USER_RUNES}, "", http.StatusBadRequest) + return nil, model.NewAppError("SplitWebhookPost", "web.incoming_webhook.split_props_length.app_error", map[string]interface{}{"Max": model.PostPropsMaxUserRunes}, "", http.StatusBadRequest) } x := 0 for index := range attachment.Text { @@ -256,7 +256,7 @@ func (a *App) CreateWebhookPost(c *request.Context, userID string, channel *mode post := &model.Post{UserId: userID, ChannelId: channel.Id, Message: text, Type: postType, RootId: postRootId} post.AddProp("from_webhook", "true") - if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) { + if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) { err := model.NewAppError("CreateWebhookPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest) return nil, err } @@ -269,7 +269,7 @@ func (a *App) CreateWebhookPost(c *request.Context, userID string, channel *mode if overrideUsername != "" { post.AddProp("override_username", overrideUsername) } else { - post.AddProp("override_username", model.DEFAULT_WEBHOOK_USERNAME) + post.AddProp("override_username", model.DefaultWebhookUsername) } } @@ -459,11 +459,11 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } } - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { return nil, model.NewAppError("CreateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusForbidden) } - if channel.Type != model.CHANNEL_OPEN || channel.TeamId != hook.TeamId { + if channel.Type != model.ChannelTypeOpen || channel.TeamId != hook.TeamId { return nil, model.NewAppError("CreateOutgoingWebhook", "api.webhook.create_outgoing.permissions.app_error", nil, "", http.StatusForbidden) } } else if len(hook.TriggerWords) == 0 { @@ -511,7 +511,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) return nil, err } - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { return nil, model.NewAppError("UpdateOutgoingWebhook", "api.webhook.create_outgoing.not_open.app_error", nil, "", http.StatusForbidden) } @@ -692,7 +692,7 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode // attachments is in here for slack compatibility if len(req.Attachments) > 0 { req.Props["attachments"] = req.Attachments - webhookType = model.POST_SLACK_ATTACHMENT + webhookType = model.PostTypeSlackAttachment } var channel *model.Channel @@ -764,11 +764,11 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode user = result.Data.(*model.User) if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && - channel.Name == model.DEFAULT_CHANNEL && !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { + channel.Name == model.DefaultChannelName && !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) { return model.NewAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden) } - if channel.Type != model.CHANNEL_OPEN && !a.HasPermissionToChannel(hook.UserId, channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.ChannelTypeOpen && !a.HasPermissionToChannel(hook.UserId, channel.Id, model.PermissionReadChannel) { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.permissions.app_error", nil, "", http.StatusForbidden) } diff --git a/app/webhook_test.go b/app/webhook_test.go index 4002a59ce7..ec488137a3 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -300,14 +300,14 @@ func TestCreateWebhookPost(t *testing.T) { }, }, "webhook_display_name": hook.DisplayName, - }, model.POST_SLACK_ATTACHMENT, "") + }, model.PostTypeSlackAttachment, "") require.Nil(t, err) assert.Contains(t, post.GetProps(), "from_webhook", "missing from_webhook prop") assert.Contains(t, post.GetProps(), "attachments", "missing attachments prop") assert.Contains(t, post.GetProps(), "webhook_display_name", "missing webhook_display_name prop") - _, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", nil, model.POST_SYSTEM_GENERIC, "") + _, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", nil, model.PostTypeSystemGeneric, "") require.NotNil(t, err, "Should have failed - bad post type") expectedText := "`<>|<>|`" @@ -318,7 +318,7 @@ func TestCreateWebhookPost(t *testing.T) { }, }, "webhook_display_name": hook.DisplayName, - }, model.POST_SLACK_ATTACHMENT, "") + }, model.PostTypeSlackAttachment, "") require.Nil(t, err) assert.Equal(t, expectedText, post.Message) @@ -330,7 +330,7 @@ func TestCreateWebhookPost(t *testing.T) { }, }, "webhook_display_name": hook.DisplayName, - }, model.POST_SLACK_ATTACHMENT, "") + }, model.PostTypeSlackAttachment, "") require.Nil(t, err) assert.Equal(t, expectedText, post.Message) @@ -358,7 +358,7 @@ Date: Thu Mar 1 19:46:48 2018 +0300 }, }, "webhook_display_name": hook.DisplayName, - }, model.POST_SLACK_ATTACHMENT, "") + }, model.PostTypeSlackAttachment, "") require.Nil(t, err) assert.Equal(t, expectedText, post.Message) } @@ -397,7 +397,7 @@ func TestSplitWebhookPost(t *testing.T) { Text: strings.Repeat("本", 2000), }, { - Text: strings.Repeat("本", model.POST_PROPS_MAX_USER_RUNES-1000), + Text: strings.Repeat("本", model.PostPropsMaxUserRunes-1000), }, }, }, @@ -423,7 +423,7 @@ func TestSplitWebhookPost(t *testing.T) { Props: map[string]interface{}{ "attachments": []*model.SlackAttachment{ { - Text: strings.Repeat("本", model.POST_PROPS_MAX_USER_RUNES-1000), + Text: strings.Repeat("本", model.PostPropsMaxUserRunes-1000), }, }, }, @@ -434,7 +434,7 @@ func TestSplitWebhookPost(t *testing.T) { Post: &model.Post{ Message: "foo", Props: map[string]interface{}{ - "foo": strings.Repeat("x", model.POST_PROPS_MAX_USER_RUNES*2), + "foo": strings.Repeat("x", model.PostPropsMaxUserRunes*2), }, }, }, @@ -491,29 +491,29 @@ func TestSplitWebhookPostAttachments(t *testing.T) { }, { name: "split into 2", - post: makePost(maxPostSize-1, []int{model.POST_PROPS_MAX_USER_RUNES * 3 / 4, model.POST_PROPS_MAX_USER_RUNES * 1 / 4}), + post: makePost(maxPostSize-1, []int{model.PostPropsMaxUserRunes * 3 / 4, model.PostPropsMaxUserRunes * 1 / 4}), expected: []*model.Post{ - makePost(maxPostSize-1, []int{model.POST_PROPS_MAX_USER_RUNES * 3 / 4}), - makePost(0, []int{model.POST_PROPS_MAX_USER_RUNES * 1 / 4}), + makePost(maxPostSize-1, []int{model.PostPropsMaxUserRunes * 3 / 4}), + makePost(0, []int{model.PostPropsMaxUserRunes * 1 / 4}), }, }, { name: "split into 3", - post: makePost(maxPostSize*3/2, []int{1000, 2000, model.POST_PROPS_MAX_USER_RUNES - 1000}), + post: makePost(maxPostSize*3/2, []int{1000, 2000, model.PostPropsMaxUserRunes - 1000}), expected: []*model.Post{ makePost(maxPostSize, nil), makePost(maxPostSize/2, []int{1000, 2000}), - makePost(0, []int{model.POST_PROPS_MAX_USER_RUNES - 1000}), + makePost(0, []int{model.PostPropsMaxUserRunes - 1000}), }, }, { name: "MM-24644 split into 3", - post: makePost(maxPostSize*3/2, []int{5150, 2000, model.POST_PROPS_MAX_USER_RUNES - 1000}), + post: makePost(maxPostSize*3/2, []int{5150, 2000, model.PostPropsMaxUserRunes - 1000}), expected: []*model.Post{ makePost(maxPostSize, nil), makePost(maxPostSize/2, []int{5150}), makePost(0, []int{2000}), - makePost(0, []int{model.POST_PROPS_MAX_USER_RUNES - 1000}), + makePost(0, []int{model.PostPropsMaxUserRunes - 1000}), }, }, } diff --git a/app/webhub_fuzz.go b/app/webhub_fuzz.go index 5387c12df3..45dbf69fea 100644 --- a/app/webhub_fuzz.go +++ b/app/webhub_fuzz.go @@ -106,16 +106,16 @@ type actionData struct { func getActionData(data []byte, userIDs, teamIDs, channelIDs []string) *actionData { // Some sample events events := []string{ - model.WEBSOCKET_EVENT_CHANNEL_CREATED, - model.WEBSOCKET_EVENT_CHANNEL_DELETED, - model.WEBSOCKET_EVENT_USER_ADDED, - model.WEBSOCKET_EVENT_USER_UPDATED, - model.WEBSOCKET_EVENT_STATUS_CHANGE, - model.WEBSOCKET_EVENT_HELLO, - model.WEBSOCKET_AUTHENTICATION_CHALLENGE, - model.WEBSOCKET_EVENT_REACTION_ADDED, - model.WEBSOCKET_EVENT_REACTION_REMOVED, - model.WEBSOCKET_EVENT_RESPONSE, + model.WebsocketEventChannelCreated, + model.WebsocketEventChannelDeleted, + model.WebsocketEventUserAdded, + model.WebsocketEventUserUpdated, + model.WebsocketEventStatusChange, + model.WebsocketEventHello, + model.WebsocketAuthenticationChallenge, + model.WebsocketEventReactionAdded, + model.WebsocketEventReactionRemoved, + model.WebsocketEventResponse, } // We need atleast 10 bytes to get all the data we need if len(data) < 10 { diff --git a/app/websocket_router.go b/app/websocket_router.go index cb20116561..e76d222288 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -37,7 +37,7 @@ func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketReque return } - if r.Action == model.WEBSOCKET_AUTHENTICATION_CHALLENGE { + if r.Action == model.WebsocketAuthenticationChallenge { if conn.GetSessionToken() != "" { return } @@ -66,7 +66,7 @@ func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketReque wr.app.UpdateLastActivityAtIfNeeded(*session) }) - resp := model.NewWebSocketResponse(model.STATUS_OK, r.Seq, nil) + resp := model.NewWebSocketResponse(model.StatusOk, r.Seq, nil) hub := wr.app.GetHubForUserId(conn.UserId) if hub == nil { return diff --git a/cmd/mattermost/commands/channel.go b/cmd/mattermost/commands/channel.go index 8c932fa8cb..fd8d3d2f5a 100644 --- a/cmd/mattermost/commands/channel.go +++ b/cmd/mattermost/commands/channel.go @@ -192,9 +192,9 @@ func createChannelCmdF(command *cobra.Command, args []string) error { purpose, _ := command.Flags().GetString("purpose") useprivate, _ := command.Flags().GetBool("private") - channelType := model.CHANNEL_OPEN + channelType := model.ChannelTypeOpen if useprivate { - channelType = model.CHANNEL_PRIVATE + channelType = model.ChannelTypePrivate } team := getTeamFromTeamArg(a, teamArg) @@ -487,7 +487,7 @@ func listChannelsCmdF(command *cobra.Command, args []string) error { if channel.DeleteAt > 0 { output += " (archived)" } - if channel.Type == model.CHANNEL_PRIVATE { + if channel.Type == model.ChannelTypePrivate { output += " (private)" } CommandPrettyPrintln(output) @@ -552,13 +552,13 @@ func modifyChannelCmdF(command *cobra.Command, args []string) error { return errors.New("Unable to find channel '" + args[0] + "'") } - if !(channel.Type == model.CHANNEL_OPEN || channel.Type == model.CHANNEL_PRIVATE) { + if !(channel.Type == model.ChannelTypeOpen || channel.Type == model.ChannelTypePrivate) { return errors.New("You can only change the type of public/private channels.") } - channel.Type = model.CHANNEL_OPEN + channel.Type = model.ChannelTypeOpen if private { - channel.Type = model.CHANNEL_PRIVATE + channel.Type = model.ChannelTypePrivate } user := getUserFromUserArg(a, username) @@ -657,7 +657,7 @@ func searchChannelCmdF(command *cobra.Command, args []string) error { if channel.DeleteAt > 0 { output += " (archived)" } - if channel.Type == model.CHANNEL_PRIVATE { + if channel.Type == model.ChannelTypePrivate { output += " (private)" } CommandPrettyPrintln(output) diff --git a/cmd/mattermost/commands/channel_test.go b/cmd/mattermost/commands/channel_test.go index ada00f5c89..02c5824b51 100644 --- a/cmd/mattermost/commands/channel_test.go +++ b/cmd/mattermost/commands/channel_test.go @@ -156,7 +156,7 @@ func TestCreateChannel(t *testing.T) { th.CheckCommand(t, "channel", "create", "--display_name", commonName, "--team", th.BasicTeam.Name, "--name", commonName) channel, _ := th.App.Srv().Store.Channel().GetByName(team.Id, commonName, false) assert.Equal(t, commonName, channel.Name) - assert.Equal(t, model.CHANNEL_OPEN, channel.Type) + assert.Equal(t, model.ChannelTypeOpen, channel.Type) }) t.Run("should create private channel", func(t *testing.T) { @@ -164,7 +164,7 @@ func TestCreateChannel(t *testing.T) { th.CheckCommand(t, "channel", "create", "--display_name", name, "--team", th.BasicTeam.Name, "--name", name, "--private") channel, _ := th.App.Srv().Store.Channel().GetByName(team.Id, name, false) assert.Equal(t, name, channel.Name) - assert.Equal(t, model.CHANNEL_PRIVATE, channel.Type) + assert.Equal(t, model.ChannelTypePrivate, channel.Type) }) t.Run("should create channel with header and purpose", func(t *testing.T) { @@ -172,7 +172,7 @@ func TestCreateChannel(t *testing.T) { th.CheckCommand(t, "channel", "create", "--display_name", name, "--team", th.BasicTeam.Name, "--name", name, "--header", "this is a header", "--purpose", "this is the purpose") channel, _ := th.App.Srv().Store.Channel().GetByName(team.Id, name, false) assert.Equal(t, name, channel.Name) - assert.Equal(t, model.CHANNEL_OPEN, channel.Type) + assert.Equal(t, model.ChannelTypeOpen, channel.Type) assert.Equal(t, "this is a header", channel.Header) assert.Equal(t, "this is the purpose", channel.Purpose) }) @@ -321,7 +321,7 @@ func TestModifyChannel(t *testing.T) { th.CheckCommand(t, "channel", "modify", "--public", th.BasicTeam.Name+":"+channel1.Name, "--username", th.BasicUser2.Email) res, err := th.App.Srv().Store.Channel().Get(channel1.Id, false) require.NoError(t, err) - assert.Equal(t, model.CHANNEL_OPEN, res.Type) + assert.Equal(t, model.ChannelTypeOpen, res.Type) // should fail because user doesn't exist require.Error(t, th.RunCommand(t, "channel", "modify", "--public", th.BasicTeam.Name+":"+channel2.Name, "--username", "idonotexist")) @@ -332,7 +332,7 @@ func TestModifyChannel(t *testing.T) { th.CheckCommand(t, "channel", "modify", "--private", th.BasicTeam.Name+":"+pchannel1.Name, "--username", th.BasicUser2.Email) res, err = th.App.Srv().Store.Channel().Get(pchannel1.Id, false) require.NoError(t, err) - assert.Equal(t, model.CHANNEL_PRIVATE, res.Type) + assert.Equal(t, model.ChannelTypePrivate, res.Type) // should fail because user doesn't exist require.Error(t, th.RunCommand(t, "channel", "modify", "--private", th.BasicTeam.Name+":"+pchannel2.Name, "--username", "idonotexist")) diff --git a/cmd/mattermost/commands/command.go b/cmd/mattermost/commands/command.go index a0f673cd65..867941b87c 100644 --- a/cmd/mattermost/commands/command.go +++ b/cmd/mattermost/commands/command.go @@ -131,7 +131,7 @@ func createCommandCmdF(command *cobra.Command, args []string) error { } // check if creator has permission to create slash commands - if !a.HasPermissionToTeam(user.Id, team.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !a.HasPermissionToTeam(user.Id, team.Id, model.PermissionManageSlashCommands) { return errors.New("the creator must be a user who has permissions to manage slash commands") } @@ -332,7 +332,7 @@ func modifyCommandCmdF(command *cobra.Command, args []string) (cmdError error) { } // check if creator has permission to create slash commands - if !a.HasPermissionToTeam(user.Id, modifiedCommand.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !a.HasPermissionToTeam(user.Id, modifiedCommand.TeamId, model.PermissionManageSlashCommands) { return errors.New("the creator must be a user who has permissions to manage slash commands") } diff --git a/cmd/mattermost/commands/config_test.go b/cmd/mattermost/commands/config_test.go index 278f7cafd3..7566f213e0 100644 --- a/cmd/mattermost/commands/config_test.go +++ b/cmd/mattermost/commands/config_test.go @@ -81,7 +81,7 @@ type TestPluginSettings struct { } func getDsn(driver string, source string) string { - if driver == model.DATABASE_DRIVER_MYSQL { + if driver == model.DatabaseDriverMysql { return driver + "://" + source } return source diff --git a/cmd/mattermost/commands/export.go b/cmd/mattermost/commands/export.go index 817eb3b56e..f84134e95c 100644 --- a/cmd/mattermost/commands/export.go +++ b/cmd/mattermost/commands/export.go @@ -133,7 +133,7 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error { } job, err := messageExportI.StartSynchronizeJob(ctx, startTime) - if err != nil || job.Status == model.JOB_STATUS_ERROR || job.Status == model.JOB_STATUS_CANCELED { + if err != nil || job.Status == model.JobStatusError || job.Status == model.JobStatusCanceled { CommandPrintErrorln("ERROR: Message export job failed. Please check the server logs") } else { CommandPrettyPrintln("SUCCESS: Message export job complete") @@ -175,7 +175,7 @@ func buildExportCmdF(format string) func(command *cobra.Command, args []string) if warningsCount == 0 { CommandPrettyPrintln("SUCCESS: Your data was exported.") } else { - if format == model.COMPLIANCE_EXPORT_TYPE_GLOBALRELAY || format == model.COMPLIANCE_EXPORT_TYPE_GLOBALRELAY_ZIP { + if format == model.ComplianceExportTypeGlobalrelay || format == model.ComplianceExportTypeGlobalrelayZip { CommandPrettyPrintln(fmt.Sprintf("WARNING: %d warnings encountered, see logs for details.", warningsCount)) } else { CommandPrettyPrintln(fmt.Sprintf("WARNING: %d warnings encountered, see warning.txt for details.", warningsCount)) diff --git a/cmd/mattermost/commands/extract_content.go b/cmd/mattermost/commands/extract_content.go index 24aab25bd1..a843555be7 100644 --- a/cmd/mattermost/commands/extract_content.go +++ b/cmd/mattermost/commands/extract_content.go @@ -66,7 +66,7 @@ func extractContentCmdF(command *cobra.Command, args []string) error { for { opts := model.GetFileInfosOptions{ Since: since, - SortBy: model.FILEINFO_SORT_BY_CREATED, + SortBy: model.FileinfoSortByCreated, IncludeDeleted: false, } fileInfos, err := a.Srv().Store.FileInfo().GetWithOptions(0, 1000, &opts) diff --git a/cmd/mattermost/commands/group.go b/cmd/mattermost/commands/group.go index 1670c53da0..238128a23c 100644 --- a/cmd/mattermost/commands/group.go +++ b/cmd/mattermost/commands/group.go @@ -129,7 +129,7 @@ func channelGroupEnableCmdF(command *cobra.Command, args []string) error { return errors.New("Unable to find channel '" + args[0] + "'") } - if channel.Type != model.CHANNEL_PRIVATE { + if channel.Type != model.ChannelTypePrivate { return errors.New("Channel '" + args[0] + "' is not private. It cannot be group-constrained") } diff --git a/cmd/mattermost/commands/ldap.go b/cmd/mattermost/commands/ldap.go index 5c42b7992c..f3e5c5ab4e 100644 --- a/cmd/mattermost/commands/ldap.go +++ b/cmd/mattermost/commands/ldap.go @@ -52,7 +52,7 @@ func ldapSyncCmdF(command *cobra.Command, args []string) error { if ldapI := a.Ldap(); ldapI != nil { job, err := ldapI.StartSynchronizeJob(true, includeRemovedMembers) - if err != nil || job.Status == model.JOB_STATUS_ERROR || job.Status == model.JOB_STATUS_CANCELED { + if err != nil || job.Status == model.JobStatusError || job.Status == model.JobStatusCanceled { CommandPrintErrorln("ERROR: AD/LDAP Synchronization please check the server logs") } else { CommandPrettyPrintln("SUCCESS: AD/LDAP Synchronization Complete") diff --git a/cmd/mattermost/commands/roles.go b/cmd/mattermost/commands/roles.go index a62665fbc5..84ea39dc4a 100644 --- a/cmd/mattermost/commands/roles.go +++ b/cmd/mattermost/commands/roles.go @@ -65,18 +65,18 @@ func makeSystemAdminCmdF(command *cobra.Command, args []string) error { roles := strings.Fields(user.Roles) for _, role := range roles { switch role { - case model.SYSTEM_ADMIN_ROLE_ID: + case model.SystemAdminRoleId: systemAdmin = true - case model.SYSTEM_USER_ROLE_ID: + case model.SystemUserRoleId: systemUser = true } } if !systemUser { - roles = append(roles, model.SYSTEM_USER_ROLE_ID) + roles = append(roles, model.SystemUserRoleId) } if !systemAdmin { - roles = append(roles, model.SYSTEM_ADMIN_ROLE_ID) + roles = append(roles, model.SystemAdminRoleId) } updatedUser, errUpdate := a.UpdateUserRoles(user.Id, strings.Join(roles, " "), true) @@ -115,9 +115,9 @@ func makeMemberCmdF(command *cobra.Command, args []string) error { roles := strings.Fields(user.Roles) for _, role := range roles { switch role { - case model.SYSTEM_ADMIN_ROLE_ID: + case model.SystemAdminRoleId: default: - if role == model.SYSTEM_USER_ROLE_ID { + if role == model.SystemUserRoleId { systemUser = true } newRoles = append(newRoles, role) @@ -125,7 +125,7 @@ func makeMemberCmdF(command *cobra.Command, args []string) error { } if !systemUser { - newRoles = append(roles, model.SYSTEM_USER_ROLE_ID) + newRoles = append(roles, model.SystemUserRoleId) } updatedUser, errUpdate := a.UpdateUserRoles(user.Id, strings.Join(newRoles, " "), true) diff --git a/cmd/mattermost/commands/team.go b/cmd/mattermost/commands/team.go index 547f4681d5..7f0ed7163f 100644 --- a/cmd/mattermost/commands/team.go +++ b/cmd/mattermost/commands/team.go @@ -160,9 +160,9 @@ func createTeamCmdF(command *cobra.Command, args []string) error { email = strings.ToLower(email) useprivate, _ := command.Flags().GetBool("private") - teamType := model.TEAM_OPEN + teamType := model.TeamOpen if useprivate { - teamType = model.TEAM_INVITE + teamType = model.TeamInvite } team := &model.Team{ @@ -480,10 +480,10 @@ func modifyTeamCmdF(command *cobra.Command, args []string) error { } if public { - team.Type = model.TEAM_OPEN + team.Type = model.TeamOpen team.AllowOpenInvite = true } else if private { - team.Type = model.TEAM_INVITE + team.Type = model.TeamInvite team.AllowOpenInvite = false } diff --git a/cmd/mattermost/commands/team_test.go b/cmd/mattermost/commands/team_test.go index 2729b16ad9..d2b5540d1a 100644 --- a/cmd/mattermost/commands/team_test.go +++ b/cmd/mattermost/commands/team_test.go @@ -245,9 +245,9 @@ func TestModifyTeam(t *testing.T) { updatedTeam, _ := th.App.GetTeam(team.Id) - require.False(t, !updatedTeam.AllowOpenInvite && team.Type == model.TEAM_INVITE, "Failed modifying team's privacy to private") + require.False(t, !updatedTeam.AllowOpenInvite && team.Type == model.TeamInvite, "Failed modifying team's privacy to private") th.CheckCommand(t, "team", "modify", team.Name, "--public") - require.False(t, updatedTeam.AllowOpenInvite && team.Type == model.TEAM_OPEN, "Failed modifying team's privacy to private") + require.False(t, updatedTeam.AllowOpenInvite && team.Type == model.TeamOpen, "Failed modifying team's privacy to private") } diff --git a/cmd/mattermost/commands/user.go b/cmd/mattermost/commands/user.go index a47fe61312..109ee58c9e 100644 --- a/cmd/mattermost/commands/user.go +++ b/cmd/mattermost/commands/user.go @@ -524,10 +524,10 @@ func botToUser(command *cobra.Command, args []string, a *app.App) error { } systemAdmin, _ := command.Flags().GetBool("system_admin") - if systemAdmin && !user.IsInRole(model.SYSTEM_ADMIN_ROLE_ID) { + if systemAdmin && !user.IsInRole(model.SystemAdminRoleId) { if _, appErr = a.UpdateUserRoles( user.Id, - fmt.Sprintf("%s %s", user.Roles, model.SYSTEM_ADMIN_ROLE_ID), + fmt.Sprintf("%s %s", user.Roles, model.SystemAdminRoleId), false); appErr != nil { return fmt.Errorf("Unable to make user system admin. Error: %s" + appErr.Error()) } diff --git a/cmd/mattermost/commands/webhook_test.go b/cmd/mattermost/commands/webhook_test.go index 0c56e6302f..1911a0f837 100644 --- a/cmd/mattermost/commands/webhook_test.go +++ b/cmd/mattermost/commands/webhook_test.go @@ -37,10 +37,10 @@ func TestListWebhooks(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) dispName := "myhookinc" hook := &model.IncomingWebhook{DisplayName: dispName, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId} @@ -80,10 +80,10 @@ func TestShowWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) dispName := "incominghook" hook := &model.IncomingWebhook{ @@ -145,8 +145,8 @@ func TestCreateIncomingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) // should fail because you need to specify valid channel require.Error(t, th.RunCommand(t, "webhook", "create-incoming")) @@ -193,8 +193,8 @@ func TestModifyIncomingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) description := "myhookincdesc" displayName := "myhookincname" @@ -257,8 +257,8 @@ func TestCreateOutgoingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) // team, user, display name, trigger words, callback urls are required team := th.BasicTeam.Id @@ -313,8 +313,8 @@ func TestModifyOutgoingWebhook(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) description := "myhookoutdesc" displayName := "myhookoutname" @@ -417,10 +417,10 @@ func TestDeleteWebhooks(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageIncomingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageIncomingWebhooks.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) dispName := "myhookinc" inHookStruct := &model.IncomingWebhook{DisplayName: dispName, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId} @@ -457,8 +457,8 @@ func TestMoveOutgoingWebhook(t *testing.T) { defaultRolePermissions := th.SaveDefaultRolePermissions() defer th.RestoreDefaultRolePermissions(defaultRolePermissions) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_ADMIN_ROLE_ID) - th.RemovePermissionFromRole(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, model.TEAM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamAdminRoleId) + th.RemovePermissionFromRole(model.PermissionManageOutgoingWebhooks.Id, model.TeamUserRoleId) description := "myhookoutdesc" displayName := "myhookoutname" @@ -501,7 +501,7 @@ func TestMoveOutgoingWebhook(t *testing.T) { require.Error(t, th.RunCommand(t, "webhook", "move-outgoing", newTeam.Id, th.BasicTeam.Id+":"+oldHook.Id, "--channel", "invalid")) - channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.CHANNEL_OPEN, newTeam.Id) + channel := th.CreateChannelWithClientAndTeam(th.SystemAdminClient, model.ChannelTypeOpen, newTeam.Id) th.CheckCommand(t, "webhook", "move-outgoing", newTeam.Id, th.BasicTeam.Id+":"+oldHook.Id, "--channel", channel.Name) _, webhookErr := th.App.GetOutgoingWebhook(oldHook.Id) diff --git a/config/client.go b/config/client.go index ca6a29dcd7..2ef7b5a91e 100644 --- a/config/client.go +++ b/config/client.go @@ -56,7 +56,7 @@ func GenerateClientConfig(c *model.Config, telemetryID string, license *model.Li props["ExperimentalCloudUserLimit"] = strconv.FormatInt(*c.ExperimentalSettings.CloudUserLimit, 10) props["ExperimentalCloudBilling"] = strconv.FormatBool(*c.ExperimentalSettings.CloudBilling) - if *c.ServiceSettings.ExperimentalChannelOrganization || *c.ServiceSettings.ExperimentalGroupUnreadChannels != model.GROUP_UNREAD_CHANNELS_DISABLED { + if *c.ServiceSettings.ExperimentalChannelOrganization || *c.ServiceSettings.ExperimentalGroupUnreadChannels != model.GroupUnreadChannelsDisabled { props["ExperimentalChannelOrganization"] = strconv.FormatBool(true) } else { props["ExperimentalChannelOrganization"] = strconv.FormatBool(false) @@ -137,7 +137,7 @@ func GenerateClientConfig(c *model.Config, telemetryID string, license *model.Li props["CWSUrl"] = "" props["CustomUrlSchemes"] = strings.Join(c.DisplaySettings.CustomUrlSchemes, ",") - props["IsDefaultMarketplace"] = strconv.FormatBool(*c.PluginSettings.MarketplaceUrl == model.PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL) + props["IsDefaultMarketplace"] = strconv.FormatBool(*c.PluginSettings.MarketplaceUrl == model.PluginSettingsDefaultMarketplaceUrl) props["ExperimentalSharedChannels"] = "false" props["CollapsedThreads"] = *c.ServiceSettings.CollapsedThreads diff --git a/config/client_test.go b/config/client_test.go index 1a9abe6212..cb7268a753 100644 --- a/config/client_test.go +++ b/config/client_test.go @@ -25,7 +25,7 @@ func TestGetClientConfig(t *testing.T) { "unlicensed", &model.Config{ EmailSettings: model.EmailSettings{ - EmailNotificationContentsType: model.NewString(model.EMAIL_NOTIFICATION_CONTENTS_FULL), + EmailNotificationContentsType: model.NewString(model.EmailNotificationContentsFull), }, ThemeSettings: model.ThemeSettings{ // Ignored, since not licensed. @@ -53,7 +53,7 @@ func TestGetClientConfig(t *testing.T) { "licensed, but not for theme management", &model.Config{ EmailSettings: model.EmailSettings{ - EmailNotificationContentsType: model.NewString(model.EMAIL_NOTIFICATION_CONTENTS_FULL), + EmailNotificationContentsType: model.NewString(model.EmailNotificationContentsFull), }, ThemeSettings: model.ThemeSettings{ // Ignored, since not licensed. @@ -76,7 +76,7 @@ func TestGetClientConfig(t *testing.T) { "licensed for theme management", &model.Config{ EmailSettings: model.EmailSettings{ - EmailNotificationContentsType: model.NewString(model.EMAIL_NOTIFICATION_CONTENTS_FULL), + EmailNotificationContentsType: model.NewString(model.EmailNotificationContentsFull), }, ThemeSettings: model.ThemeSettings{ AllowCustomThemes: model.NewBool(false), @@ -129,7 +129,7 @@ func TestGetClientConfig(t *testing.T) { &model.Config{ ServiceSettings: model.ServiceSettings{ ExperimentalChannelOrganization: model.NewBool(false), - ExperimentalGroupUnreadChannels: model.NewString(model.GROUP_UNREAD_CHANNELS_DEFAULT_ON), + ExperimentalGroupUnreadChannels: model.NewString(model.GroupUnreadChannelsDefaultOn), }, }, "tag1", @@ -142,7 +142,7 @@ func TestGetClientConfig(t *testing.T) { "default marketplace", &model.Config{ PluginSettings: model.PluginSettings{ - MarketplaceUrl: model.NewString(model.PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL), + MarketplaceUrl: model.NewString(model.PluginSettingsDefaultMarketplaceUrl), }, }, "tag1", @@ -213,7 +213,7 @@ func TestGetLimitedClientConfig(t *testing.T) { "unlicensed", &model.Config{ EmailSettings: model.EmailSettings{ - EmailNotificationContentsType: model.NewString(model.EMAIL_NOTIFICATION_CONTENTS_FULL), + EmailNotificationContentsType: model.NewString(model.EmailNotificationContentsFull), }, ThemeSettings: model.ThemeSettings{ // Ignored, since not licensed. diff --git a/config/common_test.go b/config/common_test.go index bb9c250e68..ee36d27faa 100644 --- a/config/common_test.go +++ b/config/common_test.go @@ -57,7 +57,7 @@ func init() { AtRestEncryptKey: model.NewString("abcdefghijklmnopqrstuvwxyz0123456789"), }, FileSettings: model.FileSettings{ - DriverName: model.NewString(model.IMAGE_DRIVER_LOCAL), + DriverName: model.NewString(model.ImageDriverLocal), Directory: model.NewString("/path/to/directory"), PublicLinkSalt: model.NewString("abcdefghijklmnopqrstuvwxyz0123456789"), }, diff --git a/config/database_test.go b/config/database_test.go index 0a6173c3ac..676391252f 100644 --- a/config/database_test.go +++ b/config/database_test.go @@ -20,7 +20,7 @@ import ( ) func getDsn(driver string, source string) string { - if driver == model.DATABASE_DRIVER_MYSQL { + if driver == model.DatabaseDriverMysql { return driver + "://" + source } return source @@ -321,7 +321,7 @@ func TestDatabaseStoreGetEnivironmentOverrides(t *testing.T) { require.NoError(t, err) defer ds.Close() - assert.Equal(t, model.TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM, *ds.Get().TeamSettings.MaxUsersPerTeam) + assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *ds.Get().TeamSettings.MaxUsersPerTeam) assert.Empty(t, ds.GetEnvironmentOverrides()) os.Setenv("MM_TEAMSETTINGS_MAXUSERSPERTEAM", "3000") @@ -451,7 +451,7 @@ func TestDatabaseStoreSet(t *testing.T) { defer ds.Close() newCfg := &model.Config{} - newCfg.LdapSettings.BindPassword = model.NewString(model.FAKE_SETTING) + newCfg.LdapSettings.BindPassword = model.NewString(model.FakeSetting) _, _, err = ds.Set(newCfg) require.NoError(t, err) @@ -745,7 +745,7 @@ func TestDatabaseStoreLoad(t *testing.T) { assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, ds.GetEnvironmentOverrides()) // check that in DB config does not include overwritten variable _, actualConfig := getActualDatabaseConfig(t) - assert.Equal(t, model.TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM, *actualConfig.TeamSettings.MaxUsersPerTeam) + assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *actualConfig.TeamSettings.MaxUsersPerTeam) }) t.Run("do not persist environment variables - int64", func(t *testing.T) { diff --git a/config/file_test.go b/config/file_test.go index 1a5f1beaba..ef0f9b5568 100644 --- a/config/file_test.go +++ b/config/file_test.go @@ -369,7 +369,7 @@ func TestFileStoreGetEnivironmentOverrides(t *testing.T) { require.NoError(t, err) defer fs.Close() - assert.Equal(t, model.TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM, *fs.Get().TeamSettings.MaxUsersPerTeam) + assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *fs.Get().TeamSettings.MaxUsersPerTeam) assert.Empty(t, fs.GetEnvironmentOverrides()) os.Setenv("MM_TEAMSETTINGS_MAXUSERSPERTEAM", "3000") @@ -485,7 +485,7 @@ func TestFileStoreSet(t *testing.T) { defer tearDown() newCfg := &model.Config{} - newCfg.LdapSettings.BindPassword = model.NewString(model.FAKE_SETTING) + newCfg.LdapSettings.BindPassword = model.NewString(model.FakeSetting) _, newConfig, err := configStore.Set(newCfg) require.NoError(t, err) @@ -764,7 +764,7 @@ func TestFileStoreLoad(t *testing.T) { assert.Equal(t, map[string]interface{}{"TeamSettings": map[string]interface{}{"MaxUsersPerTeam": true}}, fs.GetEnvironmentOverrides()) // check that on disk config does not include overwritten variable actualConfig := getActualFileConfig(t, path) - assert.Equal(t, model.TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM, *actualConfig.TeamSettings.MaxUsersPerTeam) + assert.Equal(t, model.TeamSettingsDefaultMaxUsersPerTeam, *actualConfig.TeamSettings.MaxUsersPerTeam) }) t.Run("do not persist environment variables - int64", func(t *testing.T) { diff --git a/config/main_test.go b/config/main_test.go index a36c5a3de0..293fb9e7eb 100644 --- a/config/main_test.go +++ b/config/main_test.go @@ -38,7 +38,7 @@ func truncateTable(t *testing.T, table string) { sqlStore := mainHelper.GetSQLStore() switch *sqlSetting.DriverName { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: _, err := sqlStore.GetMaster().Db.Exec(fmt.Sprintf("TRUNCATE TABLE %s", table)) if err != nil { if driverErr, ok := err.(*mysql.MySQLError); ok { @@ -50,7 +50,7 @@ func truncateTable(t *testing.T, table string) { } require.NoError(t, err) - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: _, err := sqlStore.GetMaster().Db.Exec(fmt.Sprintf("TRUNCATE TABLE %s", table)) if err != nil { if driverErr, ok := err.(*pq.Error); ok { diff --git a/config/utils.go b/config/utils.go index e696dad26a..f146f41c11 100644 --- a/config/utils.go +++ b/config/utils.go @@ -23,51 +23,51 @@ func marshalConfig(cfg *model.Config) ([]byte, error) { // desanitize replaces fake settings with their actual values. func desanitize(actual, target *model.Config) { - if target.LdapSettings.BindPassword != nil && *target.LdapSettings.BindPassword == model.FAKE_SETTING { + if target.LdapSettings.BindPassword != nil && *target.LdapSettings.BindPassword == model.FakeSetting { *target.LdapSettings.BindPassword = *actual.LdapSettings.BindPassword } - if *target.FileSettings.PublicLinkSalt == model.FAKE_SETTING { + if *target.FileSettings.PublicLinkSalt == model.FakeSetting { *target.FileSettings.PublicLinkSalt = *actual.FileSettings.PublicLinkSalt } - if *target.FileSettings.AmazonS3SecretAccessKey == model.FAKE_SETTING { + if *target.FileSettings.AmazonS3SecretAccessKey == model.FakeSetting { target.FileSettings.AmazonS3SecretAccessKey = actual.FileSettings.AmazonS3SecretAccessKey } - if *target.EmailSettings.SMTPPassword == model.FAKE_SETTING { + if *target.EmailSettings.SMTPPassword == model.FakeSetting { target.EmailSettings.SMTPPassword = actual.EmailSettings.SMTPPassword } - if *target.GitLabSettings.Secret == model.FAKE_SETTING { + if *target.GitLabSettings.Secret == model.FakeSetting { target.GitLabSettings.Secret = actual.GitLabSettings.Secret } - if target.GoogleSettings.Secret != nil && *target.GoogleSettings.Secret == model.FAKE_SETTING { + if target.GoogleSettings.Secret != nil && *target.GoogleSettings.Secret == model.FakeSetting { target.GoogleSettings.Secret = actual.GoogleSettings.Secret } - if target.Office365Settings.Secret != nil && *target.Office365Settings.Secret == model.FAKE_SETTING { + if target.Office365Settings.Secret != nil && *target.Office365Settings.Secret == model.FakeSetting { target.Office365Settings.Secret = actual.Office365Settings.Secret } - if target.OpenIdSettings.Secret != nil && *target.OpenIdSettings.Secret == model.FAKE_SETTING { + if target.OpenIdSettings.Secret != nil && *target.OpenIdSettings.Secret == model.FakeSetting { target.OpenIdSettings.Secret = actual.OpenIdSettings.Secret } - if *target.SqlSettings.DataSource == model.FAKE_SETTING { + if *target.SqlSettings.DataSource == model.FakeSetting { *target.SqlSettings.DataSource = *actual.SqlSettings.DataSource } - if *target.SqlSettings.AtRestEncryptKey == model.FAKE_SETTING { + if *target.SqlSettings.AtRestEncryptKey == model.FakeSetting { target.SqlSettings.AtRestEncryptKey = actual.SqlSettings.AtRestEncryptKey } - if *target.ElasticsearchSettings.Password == model.FAKE_SETTING { + if *target.ElasticsearchSettings.Password == model.FakeSetting { *target.ElasticsearchSettings.Password = *actual.ElasticsearchSettings.Password } if len(target.SqlSettings.DataSourceReplicas) == len(actual.SqlSettings.DataSourceReplicas) { for i, value := range target.SqlSettings.DataSourceReplicas { - if value == model.FAKE_SETTING { + if value == model.FakeSetting { target.SqlSettings.DataSourceReplicas[i] = actual.SqlSettings.DataSourceReplicas[i] } } @@ -75,21 +75,21 @@ func desanitize(actual, target *model.Config) { if len(target.SqlSettings.DataSourceSearchReplicas) == len(actual.SqlSettings.DataSourceSearchReplicas) { for i, value := range target.SqlSettings.DataSourceSearchReplicas { - if value == model.FAKE_SETTING { + if value == model.FakeSetting { target.SqlSettings.DataSourceSearchReplicas[i] = actual.SqlSettings.DataSourceSearchReplicas[i] } } } - if *target.MessageExportSettings.GlobalRelaySettings.SmtpPassword == model.FAKE_SETTING { + if *target.MessageExportSettings.GlobalRelaySettings.SmtpPassword == model.FakeSetting { *target.MessageExportSettings.GlobalRelaySettings.SmtpPassword = *actual.MessageExportSettings.GlobalRelaySettings.SmtpPassword } - if target.ServiceSettings.GfycatApiSecret != nil && *target.ServiceSettings.GfycatApiSecret == model.FAKE_SETTING { + if target.ServiceSettings.GfycatApiSecret != nil && *target.ServiceSettings.GfycatApiSecret == model.FakeSetting { *target.ServiceSettings.GfycatApiSecret = *actual.ServiceSettings.GfycatApiSecret } - if *target.ServiceSettings.SplitKey == model.FAKE_SETTING { + if *target.ServiceSettings.SplitKey == model.FakeSetting { *target.ServiceSettings.SplitKey = *actual.ServiceSettings.SplitKey } } @@ -102,7 +102,7 @@ func fixConfig(cfg *model.Config) { } // Ensure the directory for a local file store has a trailing slash. - if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL { + if *cfg.FileSettings.DriverName == model.ImageDriverLocal { if *cfg.FileSettings.Directory != "" && !strings.HasSuffix(*cfg.FileSettings.Directory, "/") { *cfg.FileSettings.Directory += "/" } @@ -120,13 +120,13 @@ func FixInvalidLocales(cfg *model.Config) bool { locales := i18n.GetSupportedLocales() if _, ok := locales[*cfg.LocalizationSettings.DefaultServerLocale]; !ok { - *cfg.LocalizationSettings.DefaultServerLocale = model.DEFAULT_LOCALE + *cfg.LocalizationSettings.DefaultServerLocale = model.DefaultLocale mlog.Warn("DefaultServerLocale must be one of the supported locales. Setting DefaultServerLocale to en as default value.") changed = true } if _, ok := locales[*cfg.LocalizationSettings.DefaultClientLocale]; !ok { - *cfg.LocalizationSettings.DefaultClientLocale = model.DEFAULT_LOCALE + *cfg.LocalizationSettings.DefaultClientLocale = model.DefaultLocale mlog.Warn("DefaultClientLocale must be one of the supported locales. Setting DefaultClientLocale to en as default value.") changed = true } diff --git a/config/utils_test.go b/config/utils_test.go index c948339918..da96970043 100644 --- a/config/utils_test.go +++ b/config/utils_test.go @@ -44,17 +44,17 @@ func TestDesanitize(t *testing.T) { target.FileSettings.DriverName = model.NewString("file") // These settings should be updated from actual - target.LdapSettings.BindPassword = model.NewString(model.FAKE_SETTING) - target.FileSettings.PublicLinkSalt = model.NewString(model.FAKE_SETTING) - target.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.FAKE_SETTING) - target.EmailSettings.SMTPPassword = model.NewString(model.FAKE_SETTING) - target.GitLabSettings.Secret = model.NewString(model.FAKE_SETTING) - target.OpenIdSettings.Secret = model.NewString(model.FAKE_SETTING) - target.SqlSettings.DataSource = model.NewString(model.FAKE_SETTING) - target.SqlSettings.AtRestEncryptKey = model.NewString(model.FAKE_SETTING) - target.ElasticsearchSettings.Password = model.NewString(model.FAKE_SETTING) - target.SqlSettings.DataSourceReplicas = []string{model.FAKE_SETTING, model.FAKE_SETTING} - target.SqlSettings.DataSourceSearchReplicas = []string{model.FAKE_SETTING, model.FAKE_SETTING} + target.LdapSettings.BindPassword = model.NewString(model.FakeSetting) + target.FileSettings.PublicLinkSalt = model.NewString(model.FakeSetting) + target.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.FakeSetting) + target.EmailSettings.SMTPPassword = model.NewString(model.FakeSetting) + target.GitLabSettings.Secret = model.NewString(model.FakeSetting) + target.OpenIdSettings.Secret = model.NewString(model.FakeSetting) + target.SqlSettings.DataSource = model.NewString(model.FakeSetting) + target.SqlSettings.AtRestEncryptKey = model.NewString(model.FakeSetting) + target.ElasticsearchSettings.Password = model.NewString(model.FakeSetting) + target.SqlSettings.DataSourceReplicas = []string{model.FakeSetting, model.FakeSetting} + target.SqlSettings.DataSourceSearchReplicas = []string{model.FakeSetting, model.FakeSetting} actualClone := actual.Clone() desanitize(actual, target) diff --git a/einterfaces/mocks/OauthProvider.go b/einterfaces/mocks/OAuthProvider.go similarity index 85% rename from einterfaces/mocks/OauthProvider.go rename to einterfaces/mocks/OAuthProvider.go index 4cf4b20114..11b7c1e072 100644 --- a/einterfaces/mocks/OauthProvider.go +++ b/einterfaces/mocks/OAuthProvider.go @@ -11,13 +11,13 @@ import ( mock "github.com/stretchr/testify/mock" ) -// OauthProvider is an autogenerated mock type for the OauthProvider type -type OauthProvider struct { +// OAuthProvider is an autogenerated mock type for the OAuthProvider type +type OAuthProvider struct { mock.Mock } // GetSSOSettings provides a mock function with given fields: config, service -func (_m *OauthProvider) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) { +func (_m *OAuthProvider) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) { ret := _m.Called(config, service) var r0 *model.SSOSettings @@ -40,7 +40,7 @@ func (_m *OauthProvider) GetSSOSettings(config *model.Config, service string) (* } // GetUserFromIdToken provides a mock function with given fields: idToken -func (_m *OauthProvider) GetUserFromIdToken(idToken string) (*model.User, error) { +func (_m *OAuthProvider) GetUserFromIdToken(idToken string) (*model.User, error) { ret := _m.Called(idToken) var r0 *model.User @@ -63,7 +63,7 @@ func (_m *OauthProvider) GetUserFromIdToken(idToken string) (*model.User, error) } // GetUserFromJson provides a mock function with given fields: data, tokenUser -func (_m *OauthProvider) GetUserFromJson(data io.Reader, tokenUser *model.User) (*model.User, error) { +func (_m *OAuthProvider) GetUserFromJson(data io.Reader, tokenUser *model.User) (*model.User, error) { ret := _m.Called(data, tokenUser) var r0 *model.User @@ -86,7 +86,7 @@ func (_m *OauthProvider) GetUserFromJson(data io.Reader, tokenUser *model.User) } // IsSameUser provides a mock function with given fields: dbUser, oAuthUser -func (_m *OauthProvider) IsSameUser(dbUser *model.User, oAuthUser *model.User) bool { +func (_m *OAuthProvider) IsSameUser(dbUser *model.User, oAuthUser *model.User) bool { ret := _m.Called(dbUser, oAuthUser) var r0 bool diff --git a/einterfaces/oauthproviders.go b/einterfaces/oauthproviders.go index af3335f5dd..2e4e07b9f0 100644 --- a/einterfaces/oauthproviders.go +++ b/einterfaces/oauthproviders.go @@ -9,20 +9,20 @@ import ( "github.com/mattermost/mattermost-server/v5/model" ) -type OauthProvider interface { +type OAuthProvider interface { GetUserFromJson(data io.Reader, tokenUser *model.User) (*model.User, error) GetSSOSettings(config *model.Config, service string) (*model.SSOSettings, error) GetUserFromIdToken(idToken string) (*model.User, error) IsSameUser(dbUser, oAuthUser *model.User) bool } -var oauthProviders = make(map[string]OauthProvider) +var oauthProviders = make(map[string]OAuthProvider) -func RegisterOauthProvider(name string, newProvider OauthProvider) { +func RegisterOAuthProvider(name string, newProvider OAuthProvider) { oauthProviders[name] = newProvider } -func GetOauthProvider(name string) OauthProvider { +func GetOAuthProvider(name string) OAuthProvider { provider, ok := oauthProviders[name] if ok { return provider diff --git a/jobs/active_users/scheduler.go b/jobs/active_users/scheduler.go index ef20234412..087cc52403 100644 --- a/jobs/active_users/scheduler.go +++ b/jobs/active_users/scheduler.go @@ -27,7 +27,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_ACTIVE_USERS + return model.JobTypeActiveUsers } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -43,7 +43,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { data := map[string]string{} - job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_ACTIVE_USERS, data) + job, err := scheduler.App.Srv().Jobs.CreateJob(model.JobTypeActiveUsers, data) if err != nil { return nil, err } diff --git a/jobs/expirynotify/scheduler.go b/jobs/expirynotify/scheduler.go index ab03799e38..938f74d8b8 100644 --- a/jobs/expirynotify/scheduler.go +++ b/jobs/expirynotify/scheduler.go @@ -27,7 +27,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_EXPIRY_NOTIFY + return model.JobTypeExpiryNotify } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -43,7 +43,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { data := map[string]string{} - job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_EXPIRY_NOTIFY, data) + job, err := scheduler.App.Srv().Jobs.CreateJob(model.JobTypeExpiryNotify, data) if err != nil { return nil, err } diff --git a/jobs/export_delete/scheduler.go b/jobs/export_delete/scheduler.go index 0e7cb9a2b0..bc91c1b757 100644 --- a/jobs/export_delete/scheduler.go +++ b/jobs/export_delete/scheduler.go @@ -28,7 +28,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_EXPORT_DELETE + return model.JobTypeExportDelete } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -43,7 +43,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { data := map[string]string{} - job, err := scheduler.app.Srv().Jobs.CreateJob(model.JOB_TYPE_EXPORT_DELETE, data) + job, err := scheduler.app.Srv().Jobs.CreateJob(model.JobTypeExportDelete, data) if err != nil { return nil, err } diff --git a/jobs/import_delete/scheduler.go b/jobs/import_delete/scheduler.go index 6982c5c352..6338c514d6 100644 --- a/jobs/import_delete/scheduler.go +++ b/jobs/import_delete/scheduler.go @@ -28,7 +28,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_IMPORT_DELETE + return model.JobTypeImportDelete } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -43,7 +43,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { data := map[string]string{} - job, err := scheduler.app.Srv().Jobs.CreateJob(model.JOB_TYPE_IMPORT_DELETE, data) + job, err := scheduler.app.Srv().Jobs.CreateJob(model.JobTypeImportDelete, data) if err != nil { return nil, err } diff --git a/jobs/jobs.go b/jobs/jobs.go index 690ed884a8..ce2ecc9cc6 100644 --- a/jobs/jobs.go +++ b/jobs/jobs.go @@ -23,7 +23,7 @@ func (srv *JobServer) CreateJob(jobType string, jobData map[string]string) (*mod Id: model.NewId(), Type: jobType, CreateAt: model.GetMillis(), - Status: model.JOB_STATUS_PENDING, + Status: model.JobStatusPending, Data: jobData, } @@ -54,7 +54,7 @@ func (srv *JobServer) GetJob(id string) (*model.Job, *model.AppError) { } func (srv *JobServer) ClaimJob(job *model.Job) (bool, *model.AppError) { - updated, err := srv.Store.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS) + updated, err := srv.Store.Job().UpdateStatusOptimistically(job.Id, model.JobStatusPending, model.JobStatusInProgress) if err != nil { return false, model.NewAppError("ClaimJob", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -67,24 +67,24 @@ func (srv *JobServer) ClaimJob(job *model.Job) (bool, *model.AppError) { } func (srv *JobServer) SetJobProgress(job *model.Job, progress int64) *model.AppError { - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress job.Progress = progress - if _, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS); err != nil { + if _, err := srv.Store.Job().UpdateOptimistically(job, model.JobStatusInProgress); err != nil { return model.NewAppError("SetJobProgress", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil } func (srv *JobServer) SetJobWarning(job *model.Job) *model.AppError { - if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JOB_STATUS_WARNING); err != nil { + if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JobStatusWarning); err != nil { return model.NewAppError("SetJobWarning", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil } func (srv *JobServer) SetJobSuccess(job *model.Job) *model.AppError { - if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JOB_STATUS_SUCCESS); err != nil { + if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JobStatusSuccess); err != nil { return model.NewAppError("SetJobSuccess", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -97,7 +97,7 @@ func (srv *JobServer) SetJobSuccess(job *model.Job) *model.AppError { func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *model.AppError { if jobError == nil { - _, err := srv.Store.Job().UpdateStatus(job.Id, model.JOB_STATUS_ERROR) + _, err := srv.Store.Job().UpdateStatus(job.Id, model.JobStatusError) if err != nil { return model.NewAppError("SetJobError", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -109,7 +109,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod return nil } - job.Status = model.JOB_STATUS_ERROR + job.Status = model.JobStatusError job.Progress = -1 if job.Data == nil { job.Data = make(map[string]string) @@ -118,7 +118,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod if jobError.DetailedError != "" { job.Data["error"] += " — " + jobError.DetailedError } - updated, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS) + updated, err := srv.Store.Job().UpdateOptimistically(job, model.JobStatusInProgress) if err != nil { return model.NewAppError("SetJobError", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -127,7 +127,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod } if !updated { - updated, err = srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_CANCEL_REQUESTED) + updated, err = srv.Store.Job().UpdateOptimistically(job, model.JobStatusCancelRequested) if err != nil { return model.NewAppError("SetJobError", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -140,7 +140,7 @@ func (srv *JobServer) SetJobError(job *model.Job, jobError *model.AppError) *mod } func (srv *JobServer) SetJobCanceled(job *model.Job) *model.AppError { - if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JOB_STATUS_CANCELED); err != nil { + if _, err := srv.Store.Job().UpdateStatus(job.Id, model.JobStatusCanceled); err != nil { return model.NewAppError("SetJobCanceled", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -152,16 +152,16 @@ func (srv *JobServer) SetJobCanceled(job *model.Job) *model.AppError { } func (srv *JobServer) UpdateInProgressJobData(job *model.Job) *model.AppError { - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress job.LastActivityAt = model.GetMillis() - if _, err := srv.Store.Job().UpdateOptimistically(job, model.JOB_STATUS_IN_PROGRESS); err != nil { + if _, err := srv.Store.Job().UpdateOptimistically(job, model.JobStatusInProgress); err != nil { return model.NewAppError("UpdateInProgressJobData", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil } func (srv *JobServer) RequestCancellation(jobId string) *model.AppError { - updated, err := srv.Store.Job().UpdateStatusOptimistically(jobId, model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED) + updated, err := srv.Store.Job().UpdateStatusOptimistically(jobId, model.JobStatusPending, model.JobStatusCanceled) if err != nil { return model.NewAppError("RequestCancellation", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -178,7 +178,7 @@ func (srv *JobServer) RequestCancellation(jobId string) *model.AppError { return nil } - updated, err = srv.Store.Job().UpdateStatusOptimistically(jobId, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_CANCEL_REQUESTED) + updated, err = srv.Store.Job().UpdateStatusOptimistically(jobId, model.JobStatusInProgress, model.JobStatusCancelRequested) if err != nil { return model.NewAppError("RequestCancellation", "app.job.update.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -199,7 +199,7 @@ func (srv *JobServer) CancellationWatcher(ctx context.Context, jobId string, can case <-time.After(CancelWatcherPollingInterval * time.Millisecond): mlog.Debug("CancellationWatcher for Job started polling.", mlog.String("job_id", jobId)) if jobStatus, err := srv.Store.Job().Get(jobId); err == nil { - if jobStatus.Status == model.JOB_STATUS_CANCEL_REQUESTED { + if jobStatus.Status == model.JobStatusCancelRequested { close(cancelChan) return } @@ -219,7 +219,7 @@ func GenerateNextStartDateTime(now time.Time, nextStartTime time.Time) *time.Tim } func (srv *JobServer) CheckForPendingJobsByType(jobType string) (bool, *model.AppError) { - count, err := srv.Store.Job().GetCountByStatusAndType(model.JOB_STATUS_PENDING, jobType) + count, err := srv.Store.Job().GetCountByStatusAndType(model.JobStatusPending, jobType) if err != nil { return false, model.NewAppError("CheckForPendingJobsByType", "app.job.get_count_by_status_and_type.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -227,9 +227,9 @@ func (srv *JobServer) CheckForPendingJobsByType(jobType string) (bool, *model.Ap } func (srv *JobServer) GetLastSuccessfulJobByType(jobType string) (*model.Job, *model.AppError) { - statuses := []string{model.JOB_STATUS_SUCCESS} - if jobType == model.JOB_TYPE_MESSAGE_EXPORT { - statuses = []string{model.JOB_STATUS_WARNING, model.JOB_STATUS_SUCCESS} + statuses := []string{model.JobStatusSuccess} + if jobType == model.JobTypeMessageExport { + statuses = []string{model.JobStatusWarning, model.JobStatusSuccess} } job, err := srv.Store.Job().GetNewestJobByStatusesAndType(statuses, jobType) var nfErr *store.ErrNotFound diff --git a/jobs/jobs_test.go b/jobs/jobs_test.go index 1571c10857..4776e468f5 100644 --- a/jobs/jobs_test.go +++ b/jobs/jobs_test.go @@ -61,7 +61,7 @@ func TestClaimJob(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusInProgress).Return(false, &model.AppError{Message: "message"}) updated, err := jobServer.ClaimJob(job) expectErrorId(t, "app.job.update.app_error", err) @@ -76,7 +76,7 @@ func TestClaimJob(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS).Return(false, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusInProgress).Return(false, nil) updated, err := jobServer.ClaimJob(job) require.Nil(t, err) @@ -91,7 +91,7 @@ func TestClaimJob(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusInProgress).Return(true, nil) mockMetrics.On("IncrementJobActive", "job_type") updated, err := jobServer.ClaimJob(job) @@ -107,7 +107,7 @@ func TestClaimJob(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusInProgress).Return(true, nil) updated, err := jobServer.ClaimJob(job) require.Nil(t, err) @@ -125,10 +125,10 @@ func TestSetJobProgress(t *testing.T) { Type: "job_type", } - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress job.Progress = progress - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, &model.AppError{Message: "message"}) err := jobServer.SetJobProgress(job, progress) expectErrorId(t, "app.job.update.app_error", err) @@ -143,10 +143,10 @@ func TestSetJobProgress(t *testing.T) { Type: "job_type", } - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress job.Progress = progress - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) err := jobServer.SetJobProgress(job, progress) require.Nil(t, err) @@ -162,7 +162,7 @@ func TestSetJobWarning(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_WARNING).Return(job, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusWarning).Return(job, &model.AppError{Message: "message"}) err := jobServer.SetJobWarning(job) expectErrorId(t, "app.job.update.app_error", err) @@ -176,7 +176,7 @@ func TestSetJobWarning(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_WARNING).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusWarning).Return(job, nil) err := jobServer.SetJobWarning(job) require.Nil(t, err) @@ -192,7 +192,7 @@ func TestSetJobSuccess(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_SUCCESS).Return(job, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusSuccess).Return(job, &model.AppError{Message: "message"}) err := jobServer.SetJobSuccess(job) expectErrorId(t, "app.job.update.app_error", err) @@ -206,7 +206,7 @@ func TestSetJobSuccess(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_SUCCESS).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusSuccess).Return(job, nil) mockMetrics.On("DecrementJobActive", "job_type") err := jobServer.SetJobSuccess(job) @@ -221,7 +221,7 @@ func TestSetJobSuccess(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_SUCCESS).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusSuccess).Return(job, nil) err := jobServer.SetJobSuccess(job) require.Nil(t, err) @@ -238,7 +238,7 @@ func TestSetJobError(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_ERROR).Return(job, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusError).Return(job, &model.AppError{Message: "message"}) err := jobServer.SetJobError(job, nil) expectErrorId(t, "app.job.update.app_error", err) @@ -252,7 +252,7 @@ func TestSetJobError(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_ERROR).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusError).Return(job, nil) mockMetrics.On("DecrementJobActive", "job_type") err := jobServer.SetJobError(job, nil) @@ -267,7 +267,7 @@ func TestSetJobError(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_ERROR).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusError).Return(job, nil) err := jobServer.SetJobError(job, nil) require.Nil(t, err) @@ -287,7 +287,7 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, &model.AppError{Message: "message"}) err := jobServer.SetJobError(job, jobError) expectErrorId(t, "app.job.update.app_error", err) @@ -305,7 +305,7 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) mockMetrics.On("DecrementJobActive", "job_type") err := jobServer.SetJobError(job, jobError) @@ -324,7 +324,7 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) err := jobServer.SetJobError(job, jobError) require.Nil(t, err) @@ -342,8 +342,8 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, nil) - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_CANCEL_REQUESTED).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusCancelRequested).Return(false, &model.AppError{Message: "message"}) err := jobServer.SetJobError(job, jobError) expectErrorId(t, "app.job.update.app_error", err) @@ -361,8 +361,8 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, nil) - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_CANCEL_REQUESTED).Return(false, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusCancelRequested).Return(false, nil) err := jobServer.SetJobError(job, jobError) expectErrorId(t, "jobs.set_job_error.update.error", err) @@ -380,8 +380,8 @@ func TestSetJobError(t *testing.T) { Data: map[string]string{"error": jobError.Message}, } - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, nil) - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_CANCEL_REQUESTED).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusCancelRequested).Return(true, nil) err := jobServer.SetJobError(job, jobError) require.Nil(t, err) @@ -398,7 +398,7 @@ func TestSetJobCanceled(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_CANCELED).Return(job, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusCanceled).Return(job, &model.AppError{Message: "message"}) err := jobServer.SetJobCanceled(job) expectErrorId(t, "app.job.update.app_error", err) @@ -412,7 +412,7 @@ func TestSetJobCanceled(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_CANCELED).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusCanceled).Return(job, nil) mockMetrics.On("DecrementJobActive", "job_type") err := jobServer.SetJobCanceled(job) @@ -427,7 +427,7 @@ func TestSetJobCanceled(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatus", "job_id", model.JOB_STATUS_CANCELED).Return(job, nil) + mockStore.JobStore.On("UpdateStatus", "job_id", model.JobStatusCanceled).Return(job, nil) err := jobServer.SetJobCanceled(job) require.Nil(t, err) @@ -443,9 +443,9 @@ func TestUpdateInProgressJobData(t *testing.T) { Type: "job_type", } - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(false, &model.AppError{Message: "message"}) err := jobServer.UpdateInProgressJobData(job) expectErrorId(t, "app.job.update.app_error", err) @@ -459,9 +459,9 @@ func TestUpdateInProgressJobData(t *testing.T) { Type: "job_type", } - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) err := jobServer.UpdateInProgressJobData(job) require.Nil(t, err) @@ -472,7 +472,7 @@ func TestRequestCancellation(t *testing.T) { t.Run("error cancelling", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(false, &model.AppError{Message: "message"}) err := jobServer.RequestCancellation("job_id") expectErrorId(t, "app.job.update.app_error", err) @@ -481,7 +481,7 @@ func TestRequestCancellation(t *testing.T) { t.Run("cancelled, job not found", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(true, nil) mockStore.JobStore.On("Get", "job_id").Return(nil, &store.ErrNotFound{}) err := jobServer.RequestCancellation("job_id") @@ -496,7 +496,7 @@ func TestRequestCancellation(t *testing.T) { Type: "job_type", } - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(true, nil) mockStore.JobStore.On("Get", "job_id").Return(job, nil) mockMetrics.On("DecrementJobActive", "job_type") @@ -507,7 +507,7 @@ func TestRequestCancellation(t *testing.T) { t.Run("cancelled, success, nil metrics service", func(t *testing.T) { jobServer, mockStore := makeTeamEditionJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(true, nil) err := jobServer.RequestCancellation("job_id") require.Nil(t, err) @@ -516,8 +516,8 @@ func TestRequestCancellation(t *testing.T) { t.Run("unable to cancel, requesting cancellation instead, error setting status", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(false, nil) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_CANCEL_REQUESTED).Return(false, &model.AppError{Message: "message"}) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(false, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusInProgress, model.JobStatusCancelRequested).Return(false, &model.AppError{Message: "message"}) err := jobServer.RequestCancellation("job_id") expectErrorId(t, "app.job.update.app_error", err) @@ -526,8 +526,8 @@ func TestRequestCancellation(t *testing.T) { t.Run("unable to cancel, requesting cancellation instead, success", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(false, nil) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_CANCEL_REQUESTED).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(false, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusInProgress, model.JobStatusCancelRequested).Return(true, nil) err := jobServer.RequestCancellation("job_id") require.Nil(t, err) @@ -536,8 +536,8 @@ func TestRequestCancellation(t *testing.T) { t.Run("unable to cancel, requesting cancellation instead, unexpected state", func(t *testing.T) { jobServer, mockStore, _ := makeJobServer(t) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_PENDING, model.JOB_STATUS_CANCELED).Return(false, nil) - mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_CANCEL_REQUESTED).Return(false, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusPending, model.JobStatusCanceled).Return(false, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", "job_id", model.JobStatusInProgress, model.JobStatusCancelRequested).Return(false, nil) err := jobServer.RequestCancellation("job_id") expectErrorId(t, "jobs.request_cancellation.status.error", err) diff --git a/jobs/jobs_watcher.go b/jobs/jobs_watcher.go index b3fcfaf981..5b2939c263 100644 --- a/jobs/jobs_watcher.go +++ b/jobs/jobs_watcher.go @@ -65,126 +65,126 @@ func (watcher *Watcher) Stop() { } func (watcher *Watcher) PollAndNotify() { - jobs, err := watcher.srv.Store.Job().GetAllByStatus(model.JOB_STATUS_PENDING) + jobs, err := watcher.srv.Store.Job().GetAllByStatus(model.JobStatusPending) if err != nil { mlog.Error("Error occurred getting all pending statuses.", mlog.Err(err)) return } for _, job := range jobs { - if job.Type == model.JOB_TYPE_DATA_RETENTION { + if job.Type == model.JobTypeDataRetention { if watcher.workers.DataRetention != nil { select { case watcher.workers.DataRetention.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_MESSAGE_EXPORT { + } else if job.Type == model.JobTypeMessageExport { if watcher.workers.MessageExport != nil { select { case watcher.workers.MessageExport.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING { + } else if job.Type == model.JobTypeElasticsearchPostIndexing { if watcher.workers.ElasticsearchIndexing != nil { select { case watcher.workers.ElasticsearchIndexing.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION { + } else if job.Type == model.JobTypeElasticsearchPostAggregation { if watcher.workers.ElasticsearchAggregation != nil { select { case watcher.workers.ElasticsearchAggregation.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_BLEVE_POST_INDEXING { + } else if job.Type == model.JobTypeBlevePostIndexing { if watcher.workers.BleveIndexing != nil { select { case watcher.workers.BleveIndexing.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_LDAP_SYNC { + } else if job.Type == model.JobTypeLdapSync { if watcher.workers.LdapSync != nil { select { case watcher.workers.LdapSync.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_MIGRATIONS { + } else if job.Type == model.JobTypeMigrations { if watcher.workers.Migrations != nil { select { case watcher.workers.Migrations.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_PLUGINS { + } else if job.Type == model.JobTypePlugins { if watcher.workers.Plugins != nil { select { case watcher.workers.Plugins.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_EXPIRY_NOTIFY { + } else if job.Type == model.JobTypeExpiryNotify { if watcher.workers.ExpiryNotify != nil { select { case watcher.workers.ExpiryNotify.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_PRODUCT_NOTICES { + } else if job.Type == model.JobTypeProductNotices { if watcher.workers.ProductNotices != nil { select { case watcher.workers.ProductNotices.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_ACTIVE_USERS { + } else if job.Type == model.JobTypeActiveUsers { if watcher.workers.ActiveUsers != nil { select { case watcher.workers.ActiveUsers.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_IMPORT_PROCESS { + } else if job.Type == model.JobTypeImportProcess { if watcher.workers.ImportProcess != nil { select { case watcher.workers.ImportProcess.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_IMPORT_DELETE { + } else if job.Type == model.JobTypeImportDelete { if watcher.workers.ImportDelete != nil { select { case watcher.workers.ImportDelete.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_EXPORT_PROCESS { + } else if job.Type == model.JobTypeExportProcess { if watcher.workers.ExportProcess != nil { select { case watcher.workers.ExportProcess.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_EXPORT_DELETE { + } else if job.Type == model.JobTypeExportDelete { if watcher.workers.ExportDelete != nil { select { case watcher.workers.ExportDelete.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_CLOUD { + } else if job.Type == model.JobTypeCloud { if watcher.workers.Cloud != nil { select { case watcher.workers.Cloud.JobChannel() <- *job: default: } } - } else if job.Type == model.JOB_TYPE_RESEND_INVITATION_EMAIL { + } else if job.Type == model.JobTypeResendInvitationEmail { if watcher.workers.ResendInvitationEmail != nil { select { case watcher.workers.ResendInvitationEmail.JobChannel() <- *job: diff --git a/jobs/product_notices/scheduler.go b/jobs/product_notices/scheduler.go index bb1eefddba..4097ea59ba 100644 --- a/jobs/product_notices/scheduler.go +++ b/jobs/product_notices/scheduler.go @@ -23,7 +23,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_PRODUCT_NOTICES + return model.JobTypeProductNotices } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -39,7 +39,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { data := map[string]string{} - job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_PRODUCT_NOTICES, data) + job, err := scheduler.App.Srv().Jobs.CreateJob(model.JobTypeProductNotices, data) if err != nil { return nil, err } diff --git a/jobs/resend_invitation_email/scheduler.go b/jobs/resend_invitation_email/scheduler.go index 579b0a7543..d904276fa2 100644 --- a/jobs/resend_invitation_email/scheduler.go +++ b/jobs/resend_invitation_email/scheduler.go @@ -24,7 +24,7 @@ func (s *ResendInvitationEmailScheduler) Name() string { } func (s *ResendInvitationEmailScheduler) JobType() string { - return model.JOB_TYPE_RESEND_INVITATION_EMAIL + return model.JobTypeResendInvitationEmail } func (s *ResendInvitationEmailScheduler) Enabled(cfg *model.Config) bool { diff --git a/jobs/schedulers_test.go b/jobs/schedulers_test.go index 22bd94d162..efa9e57a29 100644 --- a/jobs/schedulers_test.go +++ b/jobs/schedulers_test.go @@ -29,7 +29,7 @@ func (scheduler *MockScheduler) Name() string { } func (scheduler *MockScheduler) JobType() string { - return model.JOB_TYPE_DATA_RETENTION + return model.JobTypeDataRetention } func (scheduler *MockScheduler) NextScheduleTime(cfg *model.Config, now time.Time, pendingJobs bool, lastSuccessfulJob *model.Job) *time.Time { @@ -48,8 +48,8 @@ func TestScheduler(t *testing.T) { job := &model.Job{ Id: model.NewId(), CreateAt: model.GetMillis(), - Status: model.JOB_STATUS_PENDING, - Type: model.JOB_TYPE_MESSAGE_EXPORT, + Status: model.JobStatusPending, + Type: model.JobTypeMessageExport, } // mock job store doesn't return a previously successful job, forcing fallback to config mockStore.JobStore.On("GetNewestJobByStatusesAndType", mock.AnythingOfType("[]string"), mock.AnythingOfType("string")).Return(job, nil) diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index 142caadbcb..5303f20a4b 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -75,7 +75,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { DisplayName: teamDisplayName[0], Name: "zz" + utils.RandomName(utils.Range{Begin: 20, End: 20}, utils.LOWERCASE), Email: "success+" + model.NewId() + "simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } createdTeam, err := c.App.Srv().Store.Team().Save(team) @@ -93,7 +93,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { return } - channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: createdTeam.Id} + channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.ChannelTypeOpen, TeamId: createdTeam.Id} if _, err := c.App.CreateChannel(c.AppContext, channel, false); err != nil { c.Err = err return @@ -127,7 +127,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { // Respond with an auth token this can be overridden by a specific test as required sessionCookie := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: client.AuthToken, Path: "/", MaxAge: *c.App.Config().ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24, diff --git a/manualtesting/test_autolink.go b/manualtesting/test_autolink.go index d049468e8a..fb5769d1bb 100644 --- a/manualtesting/test_autolink.go +++ b/manualtesting/test_autolink.go @@ -23,7 +23,7 @@ https://medium.com/@slackhq/11-useful-tips-for-getting-the-most-of-slack-5dfb3d1 func testAutoLink(env TestEnvironment) *model.AppError { mlog.Info("Manual Auto Link Test") - channelID, err := getChannelID(env.Context.App, model.DEFAULT_CHANNEL, env.CreatedTeamID, env.CreatedUserID) + channelID, err := getChannelID(env.Context.App, model.DefaultChannelName, env.CreatedTeamID, env.CreatedUserID) if !err { return model.NewAppError("/manualtest", "manaultesting.test_autolink.unable.app_error", nil, "", http.StatusInternalServerError) } diff --git a/migrations/helper_test.go b/migrations/helper_test.go index a55656e91e..ff34d7b151 100644 --- a/migrations/helper_test.go +++ b/migrations/helper_test.go @@ -99,7 +99,7 @@ func Setup() *TestHelper { func (th *TestHelper) InitBasic() *TestHelper { th.SystemAdminUser = th.CreateUser() - th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) + th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false) th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id) th.BasicTeam = th.CreateTeam() @@ -123,7 +123,7 @@ func (th *TestHelper) CreateTeam() *model.Team { DisplayName: "dn_" + id, Name: "name" + id, Email: "success+" + id + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } utils.DisableDebugLogForTest() @@ -156,7 +156,7 @@ func (th *TestHelper) CreateUser() *model.User { } func (th *TestHelper) CreateChannel(team *model.Team) *model.Channel { - return th.createChannel(team, model.CHANNEL_OPEN) + return th.createChannel(team, model.ChannelTypeOpen) } func (th *TestHelper) createChannel(team *model.Team, channelType string) *model.Channel { @@ -250,13 +250,13 @@ func (*TestHelper) ResetRoleMigration() { mainHelper.GetClusterInterface().SendClearRoleCacheMessage() - if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.ADVANCED_PERMISSIONS_MIGRATION_KEY}); err != nil { + if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.AdvancedPermissionsMigrationKey}); err != nil { panic(err) } } func (th *TestHelper) DeleteAllJobsByTypeAndMigrationKey(jobType string, migrationKey string) { - jobs, err := th.App.Srv().Store.Job().GetAllByType(model.JOB_TYPE_MIGRATIONS) + jobs, err := th.App.Srv().Store.Job().GetAllByType(model.JobTypeMigrations) if err != nil { panic(err) } diff --git a/migrations/migrations.go b/migrations/migrations.go index c724afd2c0..db0c31bb1b 100644 --- a/migrations/migrations.go +++ b/migrations/migrations.go @@ -17,8 +17,8 @@ const ( MigrationStateInProgress = "in_progress" MigrationStateCompleted = "completed" - JobDataKeyMigration = "migration_key" - JobDataKeyMigration_LAST_DONE = "last_done" + JobDataKeyMigration = "migration_key" + JobDataKeyMigrationLastDone = "last_done" ) type MigrationsJobInterfaceImpl struct { @@ -33,7 +33,7 @@ func init() { func MakeMigrationsList() []string { return []string{ - model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, + model.MigrationKeyAdvancedPermissionsPhase2, } } @@ -42,7 +42,7 @@ func GetMigrationState(migration string, store store.Store) (string, *model.Job, return MigrationStateCompleted, nil, nil } - jobs, err := store.Job().GetAllByType(model.JOB_TYPE_MIGRATIONS) + jobs, err := store.Job().GetAllByType(model.JobTypeMigrations) if err != nil { return "", nil, model.NewAppError("GetMigrationState", "app.job.get_all.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -54,7 +54,7 @@ func GetMigrationState(migration string, store store.Store) (string, *model.Job, } switch job.Status { - case model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_PENDING: + case model.JobStatusInProgress, model.JobStatusPending: return MigrationStateInProgress, job, nil default: return MigrationStateUnscheduled, job, nil diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 7ce8e68c33..a47b2f365f 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -21,7 +21,7 @@ func TestGetMigrationState(t *testing.T) { migrationKey := model.NewId() - th.DeleteAllJobsByTypeAndMigrationKey(model.JOB_TYPE_MIGRATIONS, migrationKey) + th.DeleteAllJobsByTypeAndMigrationKey(model.JobTypeMigrations, migrationKey) // Test with no job yet. state, job, err := GetMigrationState(migrationKey, th.App.Srv().Store) @@ -52,8 +52,8 @@ func TestGetMigrationState(t *testing.T) { Data: map[string]string{ JobDataKeyMigration: migrationKey, }, - Status: model.JOB_STATUS_PENDING, - Type: model.JOB_TYPE_MIGRATIONS, + Status: model.JobStatusPending, + Type: model.JobTypeMigrations, } j1, nErr = th.App.Srv().Store.Job().Save(j1) @@ -71,8 +71,8 @@ func TestGetMigrationState(t *testing.T) { Data: map[string]string{ JobDataKeyMigration: migrationKey, }, - Status: model.JOB_STATUS_IN_PROGRESS, - Type: model.JOB_TYPE_MIGRATIONS, + Status: model.JobStatusInProgress, + Type: model.JobTypeMigrations, } j2, nErr = th.App.Srv().Store.Job().Save(j2) @@ -90,8 +90,8 @@ func TestGetMigrationState(t *testing.T) { Data: map[string]string{ JobDataKeyMigration: migrationKey, }, - Status: model.JOB_STATUS_ERROR, - Type: model.JOB_TYPE_MIGRATIONS, + Status: model.JobStatusError, + Type: model.JobTypeMigrations, } j3, nErr = th.App.Srv().Store.Job().Save(j3) diff --git a/migrations/scheduler.go b/migrations/scheduler.go index ed01dbbc32..6e75c49bc4 100644 --- a/migrations/scheduler.go +++ b/migrations/scheduler.go @@ -29,7 +29,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_MIGRATIONS + return model.JobTypeMigrations } func (scheduler *Scheduler) Enabled(_ *model.Config) bool { @@ -95,15 +95,15 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las func (scheduler *Scheduler) createJob(migrationKey string, lastJob *model.Job) (*model.Job, *model.AppError) { var lastDone string if lastJob != nil { - lastDone = lastJob.Data[JobDataKeyMigration_LAST_DONE] + lastDone = lastJob.Data[JobDataKeyMigrationLastDone] } data := map[string]string{ - JobDataKeyMigration: migrationKey, - JobDataKeyMigration_LAST_DONE: lastDone, + JobDataKeyMigration: migrationKey, + JobDataKeyMigrationLastDone: lastDone, } - job, err := scheduler.srv.Jobs.CreateJob(model.JOB_TYPE_MIGRATIONS, data) + job, err := scheduler.srv.Jobs.CreateJob(model.JobTypeMigrations, data) if err != nil { return nil, err } diff --git a/migrations/worker.go b/migrations/worker.go index 0ff648fb4a..c1b4000e33 100644 --- a/migrations/worker.go +++ b/migrations/worker.go @@ -100,7 +100,7 @@ func (worker *Worker) DoJob(job *model.Job) { return case <-time.After(TimeBetweenBatches * time.Millisecond): - done, progress, err := worker.runMigration(job.Data[JobDataKeyMigration], job.Data[JobDataKeyMigration_LAST_DONE]) + done, progress, err := worker.runMigration(job.Data[JobDataKeyMigration], job.Data[JobDataKeyMigrationLastDone]) if err != nil { mlog.Error("Worker: Failed to run migration", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) @@ -110,7 +110,7 @@ func (worker *Worker) DoJob(job *model.Job) { worker.setJobSuccess(job) return } else { - job.Data[JobDataKeyMigration_LAST_DONE] = progress + job.Data[JobDataKeyMigrationLastDone] = progress if err := worker.srv.Jobs.UpdateInProgressJobData(job); err != nil { mlog.Error("Worker: Failed to update migration status data for job", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) @@ -150,7 +150,7 @@ func (worker *Worker) runMigration(key string, lastDone string) (bool, string, * var err *model.AppError switch key { - case model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2: + case model.MigrationKeyAdvancedPermissionsPhase2: done, progress, err = worker.runAdvancedPermissionsPhase2Migration(lastDone) default: return false, "", model.NewAppError("MigrationsWorker.runMigration", "migrations.worker.run_migration.unknown_key", map[string]interface{}{"key": key}, "", http.StatusInternalServerError) diff --git a/model/access.go b/model/access.go index 6b60ea9e45..815a874738 100644 --- a/model/access.go +++ b/model/access.go @@ -10,9 +10,9 @@ import ( ) const ( - ACCESS_TOKEN_GRANT_TYPE = "authorization_code" - ACCESS_TOKEN_TYPE = "bearer" - REFRESH_TOKEN_GRANT_TYPE = "refresh_token" + AccessTokenGrantType = "authorization_code" + AccessTokenType = "bearer" + RefreshTokenGrantType = "refresh_token" ) type AccessData struct { diff --git a/model/authorize.go b/model/authorize.go index f2a8e8dcdf..8942f2c22c 100644 --- a/model/authorize.go +++ b/model/authorize.go @@ -10,10 +10,10 @@ import ( ) const ( - AUTHCODE_EXPIRE_TIME = 60 * 10 // 10 minutes - AUTHCODE_RESPONSE_TYPE = "code" - IMPLICIT_RESPONSE_TYPE = "token" - DEFAULT_SCOPE = "user" + AuthCodeExpireTime = 60 * 10 // 10 minutes + AuthCodeResponseType = "code" + ImplicitResponseType = "token" + DefaultScope = "user" ) type AuthData struct { @@ -103,7 +103,7 @@ func (ar *AuthorizeRequest) IsValid() *AppError { func (ad *AuthData) PreSave() { if ad.ExpiresIn == 0 { - ad.ExpiresIn = AUTHCODE_EXPIRE_TIME + ad.ExpiresIn = AuthCodeExpireTime } if ad.CreateAt == 0 { @@ -111,7 +111,7 @@ func (ad *AuthData) PreSave() { } if ad.Scope == "" { - ad.Scope = DEFAULT_SCOPE + ad.Scope = DefaultScope } } diff --git a/model/bot.go b/model/bot.go index e58fc0bea0..239477f8d1 100644 --- a/model/bot.go +++ b/model/bot.go @@ -13,11 +13,11 @@ import ( ) const ( - BOT_DISPLAY_NAME_MAX_RUNES = USER_FIRST_NAME_MAX_RUNES - BOT_DESCRIPTION_MAX_RUNES = 1024 - BOT_CREATOR_ID_MAX_RUNES = KEY_VALUE_PLUGIN_ID_MAX_RUNES // UserId or PluginId - BOT_WARN_METRIC_BOT_USERNAME = "mattermost-advisor" - BOT_SYSTEM_BOT_USERNAME = "system-bot" + BotDisplayNameMaxRunes = UserFirstNameMaxRunes + BotDescriptionMaxRunes = 1024 + BotCreatorIdMaxRunes = KeyValuePluginIdMaxRunes // UserId or PluginId + BotWarnMetricBotUsername = "mattermost-advisor" + BotSystemBotUsername = "system-bot" ) // Bot is a special type of User meant for programmatic interactions. @@ -75,15 +75,15 @@ func (b *Bot) IsValid() *AppError { return NewAppError("Bot.IsValid", "model.bot.is_valid.username.app_error", b.Trace(), "", http.StatusBadRequest) } - if utf8.RuneCountInString(b.DisplayName) > BOT_DISPLAY_NAME_MAX_RUNES { + if utf8.RuneCountInString(b.DisplayName) > BotDisplayNameMaxRunes { return NewAppError("Bot.IsValid", "model.bot.is_valid.user_id.app_error", b.Trace(), "", http.StatusBadRequest) } - if utf8.RuneCountInString(b.Description) > BOT_DESCRIPTION_MAX_RUNES { + if utf8.RuneCountInString(b.Description) > BotDescriptionMaxRunes { return NewAppError("Bot.IsValid", "model.bot.is_valid.description.app_error", b.Trace(), "", http.StatusBadRequest) } - if b.OwnerId == "" || utf8.RuneCountInString(b.OwnerId) > BOT_CREATOR_ID_MAX_RUNES { + if b.OwnerId == "" || utf8.RuneCountInString(b.OwnerId) > BotCreatorIdMaxRunes { return NewAppError("Bot.IsValid", "model.bot.is_valid.creator_id.app_error", b.Trace(), "", http.StatusBadRequest) } @@ -191,7 +191,7 @@ func UserFromBot(b *Bot) *User { Username: b.Username, Email: NormalizeEmail(fmt.Sprintf("%s@localhost", b.Username)), FirstName: b.DisplayName, - Roles: SYSTEM_USER_ROLE_ID, + Roles: SystemUserRoleId, } } @@ -201,7 +201,7 @@ func BotFromUser(u *User) *Bot { OwnerId: u.Id, UserId: u.Id, Username: u.Username, - DisplayName: u.GetDisplayName(SHOW_USERNAME), + DisplayName: u.GetDisplayName(ShowUsername), } } @@ -242,7 +242,7 @@ func MakeBotNotFoundError(userId string) *AppError { } func IsBotDMChannel(channel *Channel, botUserID string) bool { - if channel.Type != CHANNEL_DIRECT { + if channel.Type != ChannelTypeDirect { return false } diff --git a/model/bot_test.go b/model/bot_test.go index dbd921674b..8762b29b1b 100644 --- a/model/bot_test.go +++ b/model/bot_test.go @@ -762,14 +762,14 @@ func TestIsBotChannel(t *testing.T) { }{ { Name: "not a direct channel", - Channel: &Channel{Type: CHANNEL_OPEN}, + Channel: &Channel{Type: ChannelTypeOpen}, Expected: false, }, { Name: "a direct channel with another user", Channel: &Channel{ Name: "user1__user2", - Type: CHANNEL_DIRECT, + Type: ChannelTypeDirect, }, Expected: false, }, @@ -777,7 +777,7 @@ func TestIsBotChannel(t *testing.T) { Name: "a direct channel with the name containing the bot's ID first", Channel: &Channel{ Name: "botUserID__user2", - Type: CHANNEL_DIRECT, + Type: ChannelTypeDirect, }, Expected: true, }, @@ -785,7 +785,7 @@ func TestIsBotChannel(t *testing.T) { Name: "a direct channel with the name containing the bot's ID second", Channel: &Channel{ Name: "user1__botUserID", - Type: CHANNEL_DIRECT, + Type: ChannelTypeDirect, }, Expected: true, }, diff --git a/model/channel.go b/model/channel.go index 8dc3fa8d90..761e2a173a 100644 --- a/model/channel.go +++ b/model/channel.go @@ -15,22 +15,23 @@ import ( ) const ( - CHANNEL_OPEN = "O" - CHANNEL_PRIVATE = "P" - CHANNEL_DIRECT = "D" - CHANNEL_GROUP = "G" - CHANNEL_GROUP_MAX_USERS = 8 - CHANNEL_GROUP_MIN_USERS = 3 - DEFAULT_CHANNEL = "town-square" - CHANNEL_DISPLAY_NAME_MAX_RUNES = 64 - CHANNEL_NAME_MIN_LENGTH = 2 - CHANNEL_NAME_MAX_LENGTH = 64 - CHANNEL_HEADER_MAX_RUNES = 1024 - CHANNEL_PURPOSE_MAX_RUNES = 250 - CHANNEL_CACHE_SIZE = 25000 + ChannelTypeOpen = "O" + ChannelTypePrivate = "P" + ChannelTypeDirect = "D" + ChannelTypeGroup = "G" - CHANNEL_SORT_BY_USERNAME = "username" - CHANNEL_SORT_BY_STATUS = "status" + ChannelGroupMaxUsers = 8 + ChannelGroupMinUsers = 3 + DefaultChannelName = "town-square" + ChannelDisplayNameMaxRunes = 64 + ChannelNameMinLength = 2 + ChannelNameMaxLength = 64 + ChannelHeaderMaxRunes = 1024 + ChannelPurposeMaxRunes = 250 + ChannelCacheSize = 25000 + + ChannelSortByUsername = "username" + ChannelSortByStatus = "status" ) type Channel struct { @@ -230,7 +231,7 @@ func (o *Channel) IsValid() *AppError { return NewAppError("Channel.IsValid", "model.channel.is_valid.update_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(o.DisplayName) > CHANNEL_DISPLAY_NAME_MAX_RUNES { + if utf8.RuneCountInString(o.DisplayName) > ChannelDisplayNameMaxRunes { return NewAppError("Channel.IsValid", "model.channel.is_valid.display_name.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -238,15 +239,15 @@ func (o *Channel) IsValid() *AppError { return NewAppError("Channel.IsValid", "model.channel.is_valid.2_or_more.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if !(o.Type == CHANNEL_OPEN || o.Type == CHANNEL_PRIVATE || o.Type == CHANNEL_DIRECT || o.Type == CHANNEL_GROUP) { + if !(o.Type == ChannelTypeOpen || o.Type == ChannelTypePrivate || o.Type == ChannelTypeDirect || o.Type == ChannelTypeGroup) { return NewAppError("Channel.IsValid", "model.channel.is_valid.type.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(o.Header) > CHANNEL_HEADER_MAX_RUNES { + if utf8.RuneCountInString(o.Header) > ChannelHeaderMaxRunes { return NewAppError("Channel.IsValid", "model.channel.is_valid.header.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(o.Purpose) > CHANNEL_PURPOSE_MAX_RUNES { + if utf8.RuneCountInString(o.Purpose) > ChannelPurposeMaxRunes { return NewAppError("Channel.IsValid", "model.channel.is_valid.purpose.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -255,7 +256,7 @@ func (o *Channel) IsValid() *AppError { } userIds := strings.Split(o.Name, "__") - if o.Type != CHANNEL_DIRECT && len(userIds) == 2 && IsValidId(userIds[0]) && IsValidId(userIds[1]) { + if o.Type != ChannelTypeDirect && len(userIds) == 2 && IsValidId(userIds[0]) && IsValidId(userIds[1]) { return NewAppError("Channel.IsValid", "model.channel.is_valid.name.app_error", nil, "", http.StatusBadRequest) } @@ -282,11 +283,11 @@ func (o *Channel) PreUpdate() { } func (o *Channel) IsGroupOrDirect() bool { - return o.Type == CHANNEL_DIRECT || o.Type == CHANNEL_GROUP + return o.Type == ChannelTypeDirect || o.Type == ChannelTypeGroup } func (o *Channel) IsOpen() bool { - return o.Type == CHANNEL_OPEN + return o.Type == ChannelTypeOpen } func (o *Channel) Patch(patch *ChannelPatch) { @@ -332,7 +333,7 @@ func (o *Channel) IsShared() bool { } func (o *Channel) GetOtherUserIdForDM(userId string) string { - if o.Type != CHANNEL_DIRECT { + if o.Type != ChannelTypeDirect { return "" } @@ -368,8 +369,8 @@ func GetGroupDisplayNameFromUsers(users []*User, truncate bool) string { name := strings.Join(usernames, ", ") - if truncate && len(name) > CHANNEL_NAME_MAX_LENGTH { - name = name[:CHANNEL_NAME_MAX_LENGTH] + if truncate && len(name) > ChannelNameMaxLength { + name = name[:ChannelNameMaxLength] } return name diff --git a/model/channel_member.go b/model/channel_member.go index bc02881e63..068eafd903 100644 --- a/model/channel_member.go +++ b/model/channel_member.go @@ -11,16 +11,16 @@ import ( ) const ( - CHANNEL_NOTIFY_DEFAULT = "default" - CHANNEL_NOTIFY_ALL = "all" - CHANNEL_NOTIFY_MENTION = "mention" - CHANNEL_NOTIFY_NONE = "none" - CHANNEL_MARK_UNREAD_ALL = "all" - CHANNEL_MARK_UNREAD_MENTION = "mention" - IGNORE_CHANNEL_MENTIONS_DEFAULT = "default" - IGNORE_CHANNEL_MENTIONS_OFF = "off" - IGNORE_CHANNEL_MENTIONS_ON = "on" - IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP = "ignore_channel_mentions" + ChannelNotifyDefault = "default" + ChannelNotifyAll = "all" + ChannelNotifyMention = "mention" + ChannelNotifyNone = "none" + ChannelMarkUnreadAll = "all" + ChannelMarkUnreadMention = "mention" + IgnoreChannelMentionsDefault = "default" + IgnoreChannelMentionsOff = "off" + IgnoreChannelMentionsOn = "on" + IgnoreChannelMentionsNotifyProp = "ignore_channel_mentions" ) type ChannelUnread struct { @@ -127,29 +127,29 @@ func (o *ChannelMember) IsValid() *AppError { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) } - notifyLevel := o.NotifyProps[DESKTOP_NOTIFY_PROP] + notifyLevel := o.NotifyProps[DesktopNotifyProp] if len(notifyLevel) > 20 || !IsChannelNotifyLevelValid(notifyLevel) { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.notify_level.app_error", nil, "notify_level="+notifyLevel, http.StatusBadRequest) } - markUnreadLevel := o.NotifyProps[MARK_UNREAD_NOTIFY_PROP] + markUnreadLevel := o.NotifyProps[MarkUnreadNotifyProp] if len(markUnreadLevel) > 20 || !IsChannelMarkUnreadLevelValid(markUnreadLevel) { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.unread_level.app_error", nil, "mark_unread_level="+markUnreadLevel, http.StatusBadRequest) } - if pushLevel, ok := o.NotifyProps[PUSH_NOTIFY_PROP]; ok { + if pushLevel, ok := o.NotifyProps[PushNotifyProp]; ok { if len(pushLevel) > 20 || !IsChannelNotifyLevelValid(pushLevel) { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.push_level.app_error", nil, "push_notification_level="+pushLevel, http.StatusBadRequest) } } - if sendEmail, ok := o.NotifyProps[EMAIL_NOTIFY_PROP]; ok { + if sendEmail, ok := o.NotifyProps[EmailNotifyProp]; ok { if len(sendEmail) > 20 || !IsSendEmailValid(sendEmail) { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.email_value.app_error", nil, "push_notification_level="+sendEmail, http.StatusBadRequest) } } - if ignoreChannelMentions, ok := o.NotifyProps[IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP]; ok { + if ignoreChannelMentions, ok := o.NotifyProps[IgnoreChannelMentionsNotifyProp]; ok { if len(ignoreChannelMentions) > 40 || !IsIgnoreChannelMentionsValid(ignoreChannelMentions) { return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.ignore_channel_mentions_value.app_error", nil, "ignore_channel_mentions="+ignoreChannelMentions, http.StatusBadRequest) } @@ -172,41 +172,41 @@ func (o *ChannelMember) GetRoles() []string { func (o *ChannelMember) SetChannelMuted(muted bool) { if o.IsChannelMuted() { - o.NotifyProps[MARK_UNREAD_NOTIFY_PROP] = CHANNEL_MARK_UNREAD_ALL + o.NotifyProps[MarkUnreadNotifyProp] = ChannelMarkUnreadAll } else { - o.NotifyProps[MARK_UNREAD_NOTIFY_PROP] = CHANNEL_MARK_UNREAD_MENTION + o.NotifyProps[MarkUnreadNotifyProp] = ChannelMarkUnreadMention } } func (o *ChannelMember) IsChannelMuted() bool { - return o.NotifyProps[MARK_UNREAD_NOTIFY_PROP] == CHANNEL_MARK_UNREAD_MENTION + return o.NotifyProps[MarkUnreadNotifyProp] == ChannelMarkUnreadMention } func IsChannelNotifyLevelValid(notifyLevel string) bool { - return notifyLevel == CHANNEL_NOTIFY_DEFAULT || - notifyLevel == CHANNEL_NOTIFY_ALL || - notifyLevel == CHANNEL_NOTIFY_MENTION || - notifyLevel == CHANNEL_NOTIFY_NONE + return notifyLevel == ChannelNotifyDefault || + notifyLevel == ChannelNotifyAll || + notifyLevel == ChannelNotifyMention || + notifyLevel == ChannelNotifyNone } func IsChannelMarkUnreadLevelValid(markUnreadLevel string) bool { - return markUnreadLevel == CHANNEL_MARK_UNREAD_ALL || markUnreadLevel == CHANNEL_MARK_UNREAD_MENTION + return markUnreadLevel == ChannelMarkUnreadAll || markUnreadLevel == ChannelMarkUnreadMention } func IsSendEmailValid(sendEmail string) bool { - return sendEmail == CHANNEL_NOTIFY_DEFAULT || sendEmail == "true" || sendEmail == "false" + return sendEmail == ChannelNotifyDefault || sendEmail == "true" || sendEmail == "false" } func IsIgnoreChannelMentionsValid(ignoreChannelMentions string) bool { - return ignoreChannelMentions == IGNORE_CHANNEL_MENTIONS_ON || ignoreChannelMentions == IGNORE_CHANNEL_MENTIONS_OFF || ignoreChannelMentions == IGNORE_CHANNEL_MENTIONS_DEFAULT + return ignoreChannelMentions == IgnoreChannelMentionsOn || ignoreChannelMentions == IgnoreChannelMentionsOff || ignoreChannelMentions == IgnoreChannelMentionsDefault } func GetDefaultChannelNotifyProps() StringMap { return StringMap{ - DESKTOP_NOTIFY_PROP: CHANNEL_NOTIFY_DEFAULT, - MARK_UNREAD_NOTIFY_PROP: CHANNEL_MARK_UNREAD_ALL, - PUSH_NOTIFY_PROP: CHANNEL_NOTIFY_DEFAULT, - EMAIL_NOTIFY_PROP: CHANNEL_NOTIFY_DEFAULT, - IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: IGNORE_CHANNEL_MENTIONS_DEFAULT, + DesktopNotifyProp: ChannelNotifyDefault, + MarkUnreadNotifyProp: ChannelMarkUnreadAll, + PushNotifyProp: ChannelNotifyDefault, + EmailNotifyProp: ChannelNotifyDefault, + IgnoreChannelMentionsNotifyProp: IgnoreChannelMentionsDefault, } } diff --git a/model/channel_member_test.go b/model/channel_member_test.go index a8dd0fb929..cc81761679 100644 --- a/model/channel_member_test.go +++ b/model/channel_member_test.go @@ -35,13 +35,13 @@ func TestChannelMemberIsValid(t *testing.T) { o.NotifyProps["desktop"] = "123456789012345678901" require.NotNil(t, o.IsValid(), "should be invalid") - o.NotifyProps["desktop"] = CHANNEL_NOTIFY_ALL + o.NotifyProps["desktop"] = ChannelNotifyAll require.Nil(t, o.IsValid(), "should be valid") o.NotifyProps["mark_unread"] = "123456789012345678901" require.NotNil(t, o.IsValid(), "should be invalid") - o.NotifyProps["mark_unread"] = CHANNEL_MARK_UNREAD_ALL + o.NotifyProps["mark_unread"] = ChannelMarkUnreadAll require.Nil(t, o.IsValid(), "should be valid") o.Roles = "" diff --git a/model/channel_search.go b/model/channel_search.go index 51e117363b..ad76828066 100644 --- a/model/channel_search.go +++ b/model/channel_search.go @@ -8,7 +8,7 @@ import ( "io" ) -const CHANNEL_SEARCH_DEFAULT_LIMIT = 50 +const ChannelSearchDefaultLimit = 50 type ChannelSearch struct { Term string `json:"term"` diff --git a/model/channel_test.go b/model/channel_test.go index adac891e80..d2288e2c82 100644 --- a/model/channel_test.go +++ b/model/channel_test.go @@ -115,11 +115,11 @@ func TestGetGroupDisplayNameFromUsers(t *testing.T) { users[3] = &User{Username: NewId()} name := GetGroupDisplayNameFromUsers(users, true) - require.LessOrEqual(t, len(name), CHANNEL_NAME_MAX_LENGTH) + require.LessOrEqual(t, len(name), ChannelNameMaxLength) } func TestGetGroupNameFromUserIds(t *testing.T) { name := GetGroupNameFromUserIds([]string{NewId(), NewId(), NewId(), NewId(), NewId()}) - require.LessOrEqual(t, len(name), CHANNEL_NAME_MAX_LENGTH) + require.LessOrEqual(t, len(name), ChannelNameMaxLength) } diff --git a/model/client4.go b/model/client4.go index 77cb654dbc..dd5eb305b9 100644 --- a/model/client4.go +++ b/model/client4.go @@ -19,35 +19,35 @@ import ( ) const ( - HEADER_REQUEST_ID = "X-Request-ID" - HEADER_VERSION_ID = "X-Version-ID" - HEADER_CLUSTER_ID = "X-Cluster-ID" - HEADER_ETAG_SERVER = "ETag" - HEADER_ETAG_CLIENT = "If-None-Match" - HEADER_FORWARDED = "X-Forwarded-For" - HEADER_REAL_IP = "X-Real-IP" - HEADER_FORWARDED_PROTO = "X-Forwarded-Proto" - HEADER_TOKEN = "token" - HEADER_CSRF_TOKEN = "X-CSRF-Token" - HEADER_BEARER = "BEARER" - HEADER_AUTH = "Authorization" - HEADER_CLOUD_TOKEN = "X-Cloud-Token" - HEADER_REMOTECLUSTER_TOKEN = "X-RemoteCluster-Token" - HEADER_REMOTECLUSTER_ID = "X-RemoteCluster-Id" - HEADER_REQUESTED_WITH = "X-Requested-With" - HEADER_REQUESTED_WITH_XML = "XMLHttpRequest" - HEADER_RANGE = "Range" - STATUS = "status" - STATUS_OK = "OK" - STATUS_FAIL = "FAIL" - STATUS_UNHEALTHY = "UNHEALTHY" - STATUS_REMOVE = "REMOVE" + HeaderRequestId = "X-Request-ID" + HeaderVersionId = "X-Version-ID" + HeaderClusterId = "X-Cluster-ID" + HeaderEtagServer = "ETag" + HeaderEtagClient = "If-None-Match" + HeaderForwarded = "X-Forwarded-For" + HeaderRealIp = "X-Real-IP" + HeaderForwardedProto = "X-Forwarded-Proto" + HeaderToken = "token" + HeaderCsrfToken = "X-CSRF-Token" + HeaderBearer = "BEARER" + HeaderAuth = "Authorization" + HeaderCloudToken = "X-Cloud-Token" + HeaderRemoteclusterToken = "X-RemoteCluster-Token" + HeaderRemoteclusterId = "X-RemoteCluster-Id" + HeaderRequestedWith = "X-Requested-With" + HeaderRequestedWithXml = "XMLHttpRequest" + HeaderRange = "Range" + STATUS = "status" + StatusOk = "OK" + StatusFail = "FAIL" + StatusUnhealthy = "UNHEALTHY" + StatusRemove = "REMOVE" - CLIENT_DIR = "client" + ClientDir = "client" - API_URL_SUFFIX_V1 = "/api/v1" - API_URL_SUFFIX_V4 = "/api/v4" - API_URL_SUFFIX = API_URL_SUFFIX_V4 + ApiUrlSuffixV1 = "/api/v1" + ApiUrlSuffixV4 = "/api/v4" + ApiUrlSuffix = ApiUrlSuffixV4 ) type Response struct { @@ -120,7 +120,7 @@ func (c *Client4) Must(result interface{}, resp *Response) interface{} { func NewAPIv4Client(url string) *Client4 { url = strings.TrimRight(url, "/") - return &Client4{url, url + API_URL_SUFFIX, &http.Client{}, "", "", map[string]string{}, "", ""} + return &Client4{url, url + ApiUrlSuffix, &http.Client{}, "", "", map[string]string{}, "", ""} } func NewAPIv4SocketClient(socketPath string) *Client4 { @@ -157,16 +157,16 @@ func BuildErrorResponse(r *http.Response, err *AppError) *Response { func BuildResponse(r *http.Response) *Response { return &Response{ StatusCode: r.StatusCode, - RequestId: r.Header.Get(HEADER_REQUEST_ID), - Etag: r.Header.Get(HEADER_ETAG_SERVER), - ServerVersion: r.Header.Get(HEADER_VERSION_ID), + RequestId: r.Header.Get(HeaderRequestId), + Etag: r.Header.Get(HeaderEtagServer), + ServerVersion: r.Header.Get(HeaderVersionId), Header: r.Header, } } func (c *Client4) SetToken(token string) { c.AuthToken = token - c.AuthType = HEADER_BEARER + c.AuthType = HeaderBearer } // MockSession is deprecated in favour of SetToken @@ -176,12 +176,12 @@ func (c *Client4) MockSession(token string) { func (c *Client4) SetOAuthToken(token string) { c.AuthToken = token - c.AuthType = HEADER_TOKEN + c.AuthType = HeaderToken } func (c *Client4) ClearOAuthToken() { c.AuthToken = "" - c.AuthType = HEADER_BEARER + c.AuthType = HeaderBearer } func (c *Client4) GetUsersRoute() string { @@ -610,7 +610,7 @@ func (c *Client4) DoApiDelete(url string) (*http.Response, *AppError) { } func (c *Client4) DoApiRequest(method, url, data, etag string) (*http.Response, *AppError) { - return c.doApiRequestReader(method, url, strings.NewReader(data), map[string]string{HEADER_ETAG_CLIENT: etag}) + return c.doApiRequestReader(method, url, strings.NewReader(data), map[string]string{HeaderEtagClient: etag}) } func (c *Client4) DoApiRequestWithHeaders(method, url, data string, headers map[string]string) (*http.Response, *AppError) { @@ -618,7 +618,7 @@ func (c *Client4) DoApiRequestWithHeaders(method, url, data string, headers map[ } func (c *Client4) doApiRequestBytes(method, url string, data []byte, etag string) (*http.Response, *AppError) { - return c.doApiRequestReader(method, url, bytes.NewReader(data), map[string]string{HEADER_ETAG_CLIENT: etag}) + return c.doApiRequestReader(method, url, bytes.NewReader(data), map[string]string{HeaderEtagClient: etag}) } func (c *Client4) doApiRequestReader(method, url string, data io.Reader, headers map[string]string) (*http.Response, *AppError) { @@ -632,7 +632,7 @@ func (c *Client4) doApiRequestReader(method, url string, data io.Reader, headers } if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } if c.HttpHeader != nil && len(c.HttpHeader) > 0 { @@ -673,7 +673,7 @@ func (c *Client4) doUploadFile(url string, body io.Reader, contentType string, c rq.Header.Set("Content-Type", contentType) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -697,7 +697,7 @@ func (c *Client4) DoEmojiUploadFile(url string, data []byte, contentType string) rq.Header.Set("Content-Type", contentType) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -721,7 +721,7 @@ func (c *Client4) DoUploadImportTeam(url string, data []byte, contentType string rq.Header.Set("Content-Type", contentType) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -743,7 +743,7 @@ func CheckStatusOK(r *http.Response) bool { m := MapFromJson(r.Body) defer closeBody(r) - if m != nil && m[STATUS] == STATUS_OK { + if m != nil && m[STATUS] == StatusOk { return true } @@ -804,8 +804,8 @@ func (c *Client4) login(m map[string]string) (*User, *Response) { return nil, BuildErrorResponse(r, err) } defer closeBody(r) - c.AuthToken = r.Header.Get(HEADER_TOKEN) - c.AuthType = HEADER_BEARER + c.AuthToken = r.Header.Get(HeaderToken) + c.AuthType = HeaderBearer return UserFromJson(r.Body), BuildResponse(r) } @@ -817,7 +817,7 @@ func (c *Client4) Logout() (bool, *Response) { } defer closeBody(r) c.AuthToken = "" - c.AuthType = HEADER_BEARER + c.AuthType = HeaderBearer return CheckStatusOK(r), BuildResponse(r) } @@ -879,7 +879,7 @@ func (c *Client4) CreateUserWithInviteId(user *User, inviteId string) (*User, *R // GetMe returns the logged in user. func (c *Client4) GetMe(etag string) (*User, *Response) { - r, err := c.DoApiGet(c.GetUserRoute(ME), etag) + r, err := c.DoApiGet(c.GetUserRoute(Me), etag) if err != nil { return nil, BuildErrorResponse(r, err) } @@ -1534,7 +1534,7 @@ func (c *Client4) SetProfileImage(userId string, data []byte) (bool, *Response) rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -1783,7 +1783,7 @@ func (c *Client4) SetBotIconImage(botUserId string, data []byte) (bool, *Respons rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -2031,7 +2031,7 @@ func (c *Client4) PermanentDeleteTeam(teamId string) (bool, *Response) { return CheckStatusOK(r), BuildResponse(r) } -// UpdateTeamPrivacy modifies the team type (model.TEAM_OPEN <--> model.TEAM_INVITE) and sets +// UpdateTeamPrivacy modifies the team type (model.TeamOpen <--> model.TeamInvite) and sets // the corresponding AllowOpenInvite appropriately. func (c *Client4) UpdateTeamPrivacy(teamId string, privacy string) (*Team, *Response) { requestBody := map[string]string{"privacy": privacy} @@ -2056,8 +2056,8 @@ func (c *Client4) GetTeamMembers(teamId string, page int, perPage int, etag stri // GetTeamMembersWithoutDeletedUsers returns team members based on the provided team id string. Additional parameters of sort and exclude_deleted_users accepted as well // Could not add it to above function due to it be a breaking change. -func (c *Client4) GetTeamMembersSortAndWithoutDeletedUsers(teamId string, page int, perPage int, sort string, exclude_deleted_users bool, etag string) ([]*TeamMember, *Response) { - query := fmt.Sprintf("?page=%v&per_page=%v&sort=%v&exclude_deleted_users=%v", page, perPage, sort, exclude_deleted_users) +func (c *Client4) GetTeamMembersSortAndWithoutDeletedUsers(teamId string, page int, perPage int, sort string, excludeDeletedUsers bool, etag string) ([]*TeamMember, *Response) { + query := fmt.Sprintf("?page=%v&per_page=%v&sort=%v&exclude_deleted_users=%v", page, perPage, sort, excludeDeletedUsers) r, err := c.DoApiGet(c.GetTeamMembersRoute(teamId)+query, etag) if err != nil { return nil, BuildErrorResponse(r, err) @@ -2329,7 +2329,7 @@ func (c *Client4) SetTeamIcon(teamId string, data []byte) (bool, *Response) { rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -3376,7 +3376,7 @@ func (c *Client4) GetPing() (string, *Response) { r, err := c.DoApiGet(c.GetSystemRoute()+"/ping", "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() - return STATUS_UNHEALTHY, BuildErrorResponse(r, err) + return StatusUnhealthy, BuildErrorResponse(r, err) } if err != nil { return "", BuildErrorResponse(r, err) @@ -3391,7 +3391,7 @@ func (c *Client4) GetPingWithServerStatus() (string, *Response) { r, err := c.DoApiGet(c.GetSystemRoute()+"/ping?get_server_status="+c.boolString(true), "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() - return STATUS_UNHEALTHY, BuildErrorResponse(r, err) + return StatusUnhealthy, BuildErrorResponse(r, err) } if err != nil { return "", BuildErrorResponse(r, err) @@ -3406,7 +3406,7 @@ func (c *Client4) GetPingWithFullServerStatus() (map[string]string, *Response) { r, err := c.DoApiGet(c.GetSystemRoute()+"/ping?get_server_status="+c.boolString(true), "") if r != nil && r.StatusCode == 500 { defer r.Body.Close() - return map[string]string{"status": STATUS_UNHEALTHY}, BuildErrorResponse(r, err) + return map[string]string{"status": StatusUnhealthy}, BuildErrorResponse(r, err) } if err != nil { return nil, BuildErrorResponse(r, err) @@ -3569,7 +3569,7 @@ func (c *Client4) UploadLicenseFile(data []byte) (bool, *Response) { rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -3998,7 +3998,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response) } if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) + rq.Header.Set(HeaderAuth, "BEARER "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -4264,7 +4264,7 @@ func (c *Client4) MigrateAuthToSaml(fromAuthService string, usersMap map[string] // UploadLdapPublicCertificate will upload a public certificate for LDAP and set the config to use it. func (c *Client4) UploadLdapPublicCertificate(data []byte) (bool, *Response) { - body, writer, err := fileToMultipart(data, LDAP_PUBLIC_CERTIFICATE_NAME) + body, writer, err := fileToMultipart(data, LdapPublicCertificateName) if err != nil { return false, &Response{Error: NewAppError("UploadLdapPublicCertificate", "model.client.upload_ldap_cert.app_error", nil, err.Error(), http.StatusBadRequest)} } @@ -4275,7 +4275,7 @@ func (c *Client4) UploadLdapPublicCertificate(data []byte) (bool, *Response) { // UploadLdapPrivateCertificate will upload a private key for LDAP and set the config to use it. func (c *Client4) UploadLdapPrivateCertificate(data []byte) (bool, *Response) { - body, writer, err := fileToMultipart(data, LDAP_PRIVATE_KEY_NAME) + body, writer, err := fileToMultipart(data, LdapPrivateKeyName) if err != nil { return false, &Response{Error: NewAppError("UploadLdapPrivateCertificate", "model.client.upload_Ldap_cert.app_error", nil, err.Error(), http.StatusBadRequest)} } @@ -4373,7 +4373,7 @@ func (c *Client4) UploadBrandImage(data []byte) (bool, *Response) { rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -4528,7 +4528,7 @@ func (c *Client4) GetOAuthAccessToken(data url.Values) (*AccessResponse, *Respon rq.Header.Set("Content-Type", "application/x-www-form-urlencoded") if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -5389,7 +5389,7 @@ func (c *Client4) uploadPlugin(file io.Reader, force bool) (*Manifest, *Response rq.Header.Set("Content-Type", writer.FormDataContentType()) if c.AuthToken != "" { - rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) + rq.Header.Set(HeaderAuth, c.AuthType+" "+c.AuthToken) } rp, err := c.HttpClient.Do(rq) @@ -6165,7 +6165,7 @@ func (c *Client4) DownloadExport(name string, wr io.Writer, offset int64) (int64 var headers map[string]string if offset > 0 { headers = map[string]string{ - HEADER_RANGE: fmt.Sprintf("bytes=%d-", offset), + HeaderRange: fmt.Sprintf("bytes=%d-", offset), } } r, appErr := c.DoApiRequestWithHeaders(http.MethodGet, c.ApiUrl+c.GetExportRoute(name), "", headers) diff --git a/model/client4_test.go b/model/client4_test.go index 1296c0ddae..6429a2b724 100644 --- a/model/client4_test.go +++ b/model/client4_test.go @@ -21,7 +21,7 @@ func TestClient4TrimTrailingSlash(t *testing.T) { testUrl := baseUrl + strings.Repeat("/", s) client := NewAPIv4Client(testUrl) assert.Equal(t, baseUrl, client.Url) - assert.Equal(t, baseUrl+API_URL_SUFFIX, client.ApiUrl) + assert.Equal(t, baseUrl+ApiUrlSuffix, client.ApiUrl) } } @@ -75,12 +75,12 @@ func TestClient4SetToken(t *testing.T) { expected := NewId() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authHeader := r.Header.Get(HEADER_AUTH) + authHeader := r.Header.Get(HeaderAuth) - token := strings.Split(authHeader, HEADER_BEARER) + token := strings.Split(authHeader, HeaderBearer) if len(token) < 2 { - t.Errorf("wrong authorization header format, got %s, expected: %s %s", authHeader, HEADER_BEARER, expected) + t.Errorf("wrong authorization header format, got %s, expected: %s %s", authHeader, HeaderBearer, expected) } assert.Equal(t, expected, strings.TrimSpace(token[1])) @@ -97,12 +97,12 @@ func TestClient4MockSession(t *testing.T) { expected := NewId() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authHeader := r.Header.Get(HEADER_AUTH) + authHeader := r.Header.Get(HeaderAuth) - token := strings.Split(authHeader, HEADER_BEARER) + token := strings.Split(authHeader, HeaderBearer) if len(token) < 2 { - t.Errorf("wrong authorization header format, got %s, expected: %s %s", authHeader, HEADER_BEARER, expected) + t.Errorf("wrong authorization header format, got %s, expected: %s %s", authHeader, HeaderBearer, expected) } assert.Equal(t, expected, strings.TrimSpace(token[1])) diff --git a/model/cluster_discovery.go b/model/cluster_discovery.go index 758e498060..1cbe6d47bc 100644 --- a/model/cluster_discovery.go +++ b/model/cluster_discovery.go @@ -11,8 +11,8 @@ import ( ) const ( - CDS_OFFLINE_AFTER_MILLIS = 1000 * 60 * 30 // 30 minutes - CDS_TYPE_APP = "mattermost_app" + CDSOfflineAfterMillis = 1000 * 60 * 30 // 30 minutes + CDSTypeApp = "mattermost_app" ) type ClusterDiscovery struct { diff --git a/model/cluster_message.go b/model/cluster_message.go index bd73ba8ddd..9aab9661dd 100644 --- a/model/cluster_message.go +++ b/model/cluster_message.go @@ -9,54 +9,54 @@ import ( ) const ( - CLUSTER_EVENT_PUBLISH = "publish" - CLUSTER_EVENT_UPDATE_STATUS = "update_status" - CLUSTER_EVENT_INVALIDATE_ALL_CACHES = "inv_all_caches" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS = "inv_reactions" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOK = "inv_webhook" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_POSTS = "inv_channel_posts" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS = "inv_channel_members_notify_props" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS = "inv_channel_members" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME = "inv_channel_name" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL = "inv_channel" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_GUEST_COUNT = "inv_channel_guest_count" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER = "inv_user" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS = "inv_user_teams" - CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER = "clear_session_user" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLES = "inv_roles" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLE_PERMISSIONS = "inv_role_permissions" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_BY_IDS = "inv_profile_ids" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_IN_CHANNEL = "inv_profile_in_channel" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_SCHEMES = "inv_schemes" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_FILE_INFOS = "inv_file_infos" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOKS = "inv_webhooks" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_BY_ID = "inv_emojis_by_id" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_ID_BY_NAME = "inv_emojis_id_by_name" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_PINNEDPOSTS_COUNTS = "inv_channel_pinnedposts_counts" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBER_COUNTS = "inv_channel_member_counts" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POSTS = "inv_last_posts" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POST_TIME = "inv_last_post_time" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TEAMS = "inv_teams" - CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS = "inv_all_user_sessions" - CLUSTER_EVENT_INSTALL_PLUGIN = "install_plugin" - CLUSTER_EVENT_REMOVE_PLUGIN = "remove_plugin" - CLUSTER_EVENT_PLUGIN_EVENT = "plugin_event" - CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TERMS_OF_SERVICE = "inv_terms_of_service" - CLUSTER_EVENT_BUSY_STATE_CHANGED = "busy_state_change" + ClusterEventPublish = "publish" + ClusterEventUpdateStatus = "update_status" + ClusterEventInvalidateAllCaches = "inv_all_caches" + ClusterEventInvalidateCacheForReactions = "inv_reactions" + ClusterEventInvalidateCacheForWebhook = "inv_webhook" + ClusterEventInvalidateCacheForChannelPosts = "inv_channel_posts" + ClusterEventInvalidateCacheForChannelMembersNotifyProps = "inv_channel_members_notify_props" + ClusterEventInvalidateCacheForChannelMembers = "inv_channel_members" + ClusterEventInvalidateCacheForChannelByName = "inv_channel_name" + ClusterEventInvalidateCacheForChannel = "inv_channel" + ClusterEventInvalidateCacheForChannelGuestCount = "inv_channel_guest_count" + ClusterEventInvalidateCacheForUser = "inv_user" + ClusterEventInvalidateCacheForUserTeams = "inv_user_teams" + ClusterEventClearSessionCacheForUser = "clear_session_user" + ClusterEventInvalidateCacheForRoles = "inv_roles" + ClusterEventInvalidateCacheForRolePermissions = "inv_role_permissions" + ClusterEventInvalidateCacheForProfileByIds = "inv_profile_ids" + ClusterEventInvalidateCacheForProfileInChannel = "inv_profile_in_channel" + ClusterEventInvalidateCacheForSchemes = "inv_schemes" + ClusterEventInvalidateCacheForFileInfos = "inv_file_infos" + ClusterEventInvalidateCacheForWebhooks = "inv_webhooks" + ClusterEventInvalidateCacheForEmojisById = "inv_emojis_by_id" + ClusterEventInvalidateCacheForEmojisIdByName = "inv_emojis_id_by_name" + ClusterEventInvalidateCacheForChannelPinnedpostsCounts = "inv_channel_pinnedposts_counts" + ClusterEventInvalidateCacheForChannelMemberCounts = "inv_channel_member_counts" + ClusterEventInvalidateCacheForLastPosts = "inv_last_posts" + ClusterEventInvalidateCacheForLastPostTime = "inv_last_post_time" + ClusterEventInvalidateCacheForTeams = "inv_teams" + ClusterEventClearSessionCacheForAllUsers = "inv_all_user_sessions" + ClusterEventInstallPlugin = "install_plugin" + ClusterEventRemovePlugin = "remove_plugin" + ClusterEventPluginEvent = "plugin_event" + ClusterEventInvalidateCacheForTermsOfService = "inv_terms_of_service" + ClusterEventBusyStateChanged = "busy_state_change" // Gossip communication - CLUSTER_GOSSIP_EVENT_REQUEST_GET_LOGS = "gossip_request_get_logs" - CLUSTER_GOSSIP_EVENT_RESPONSE_GET_LOGS = "gossip_response_get_logs" - CLUSTER_GOSSIP_EVENT_REQUEST_GET_CLUSTER_STATS = "gossip_request_cluster_stats" - CLUSTER_GOSSIP_EVENT_RESPONSE_GET_CLUSTER_STATS = "gossip_response_cluster_stats" - CLUSTER_GOSSIP_EVENT_REQUEST_GET_PLUGIN_STATUSES = "gossip_request_plugin_statuses" - CLUSTER_GOSSIP_EVENT_RESPONSE_GET_PLUGIN_STATUSES = "gossip_response_plugin_statuses" - CLUSTER_GOSSIP_EVENT_REQUEST_SAVE_CONFIG = "gossip_request_save_config" - CLUSTER_GOSSIP_EVENT_RESPONSE_SAVE_CONFIG = "gossip_response_save_config" + ClusterGossipEventRequestGetLogs = "gossip_request_get_logs" + ClusterGossipEventResponseGetLogs = "gossip_response_get_logs" + ClusterGossipEventRequestGetClusterStats = "gossip_request_cluster_stats" + ClusterGossipEventResponseGetClusterStats = "gossip_response_cluster_stats" + ClusterGossipEventRequestGetPluginStatuses = "gossip_request_plugin_statuses" + ClusterGossipEventResponseGetPluginStatuses = "gossip_response_plugin_statuses" + ClusterGossipEventRequestSaveConfig = "gossip_request_save_config" + ClusterGossipEventResponseSaveConfig = "gossip_response_save_config" // SendTypes for ClusterMessage. - CLUSTER_SEND_BEST_EFFORT = "best_effort" - CLUSTER_SEND_RELIABLE = "reliable" + ClusterSendBestEffort = "best_effort" + ClusterSendReliable = "reliable" ) type ClusterMessage struct { diff --git a/model/cluster_message_test.go b/model/cluster_message_test.go index 44df3bf3b1..90ddb6d22b 100644 --- a/model/cluster_message_test.go +++ b/model/cluster_message_test.go @@ -12,8 +12,8 @@ import ( func TestClusterMessage(t *testing.T) { m := ClusterMessage{ - Event: CLUSTER_EVENT_PUBLISH, - SendType: CLUSTER_SEND_BEST_EFFORT, + Event: ClusterEventPublish, + SendType: ClusterSendBestEffort, Data: "hello", } json := m.ToJson() diff --git a/model/command.go b/model/command.go index 59a4eee4d1..a85a6425ce 100644 --- a/model/command.go +++ b/model/command.go @@ -11,10 +11,10 @@ import ( ) const ( - COMMAND_METHOD_POST = "P" - COMMAND_METHOD_GET = "G" - MIN_TRIGGER_LENGTH = 1 - MAX_TRIGGER_LENGTH = 128 + CommandMethodPost = "P" + CommandMethodGet = "G" + MinTriggerLength = 1 + MaxTriggerLength = 128 ) type Command struct { @@ -101,7 +101,7 @@ func (o *Command) IsValid() *AppError { return NewAppError("Command.IsValid", "model.command.is_valid.team_id.app_error", nil, "", http.StatusBadRequest) } - if len(o.Trigger) < MIN_TRIGGER_LENGTH || len(o.Trigger) > MAX_TRIGGER_LENGTH || strings.Index(o.Trigger, "/") == 0 || strings.Contains(o.Trigger, " ") { + if len(o.Trigger) < MinTriggerLength || len(o.Trigger) > MaxTriggerLength || strings.Index(o.Trigger, "/") == 0 || strings.Contains(o.Trigger, " ") { return NewAppError("Command.IsValid", "model.command.is_valid.trigger.app_error", nil, "", http.StatusBadRequest) } @@ -113,7 +113,7 @@ func (o *Command) IsValid() *AppError { return NewAppError("Command.IsValid", "model.command.is_valid.url_http.app_error", nil, "", http.StatusBadRequest) } - if !(o.Method == COMMAND_METHOD_GET || o.Method == COMMAND_METHOD_POST) { + if !(o.Method == CommandMethodGet || o.Method == CommandMethodPost) { return NewAppError("Command.IsValid", "model.command.is_valid.method.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/command_autocomplete.go b/model/command_autocomplete.go index f115ed24fe..649e8e3732 100644 --- a/model/command_autocomplete.go +++ b/model/command_autocomplete.go @@ -109,7 +109,7 @@ func NewAutocompleteData(trigger, hint, helpText string) *AutocompleteData { Trigger: trigger, Hint: hint, HelpText: helpText, - RoleID: SYSTEM_USER_ROLE_ID, + RoleID: SystemUserRoleId, Arguments: []*AutocompleteArg{}, SubCommands: []*AutocompleteData{}, } @@ -234,7 +234,7 @@ func (ad *AutocompleteData) IsValid() error { if strings.ToLower(ad.Trigger) != ad.Trigger { return errors.New("Command should be lowercase") } - roles := []string{SYSTEM_ADMIN_ROLE_ID, SYSTEM_USER_ROLE_ID, ""} + roles := []string{SystemAdminRoleId, SystemUserRoleId, ""} if stringNotInSlice(ad.RoleID, roles) { return errors.New("Wrong role in the autocomplete data") } diff --git a/model/command_autocomplete_test.go b/model/command_autocomplete_test.go index 66ba57477f..3da7d7dea8 100644 --- a/model/command_autocomplete_test.go +++ b/model/command_autocomplete_test.go @@ -15,7 +15,7 @@ func TestAutocompleteData(t *testing.T) { assert.NoError(t, ad.IsValid()) ad.RoleID = "some_id" assert.Error(t, ad.IsValid()) - ad.RoleID = SYSTEM_ADMIN_ROLE_ID + ad.RoleID = SystemAdminRoleId assert.NoError(t, ad.IsValid()) ad.AddDynamicListArgument("help", "/some/url", true) assert.NoError(t, ad.IsValid()) @@ -76,9 +76,9 @@ func TestAutocompleteDataJSON(t *testing.T) { func getAutocompleteData() *AutocompleteData { ad := NewAutocompleteData("jira", "", "Available commands:") - ad.RoleID = SYSTEM_USER_ROLE_ID + ad.RoleID = SystemUserRoleId command := NewAutocompleteData("connect", "", "Connect to mattermost") - command.RoleID = SYSTEM_ADMIN_ROLE_ID + command.RoleID = SystemAdminRoleId items := []AutocompleteListItem{ { Hint: "arg1", diff --git a/model/command_response.go b/model/command_response.go index 80cca5ab4a..7bf4aa0aff 100644 --- a/model/command_response.go +++ b/model/command_response.go @@ -13,8 +13,8 @@ import ( ) const ( - COMMAND_RESPONSE_TYPE_IN_CHANNEL = "in_channel" - COMMAND_RESPONSE_TYPE_EPHEMERAL = "ephemeral" + CommandResponseTypeInChannel = "in_channel" + CommandResponseTypeEphemeral = "ephemeral" ) type CommandResponse struct { diff --git a/model/command_test.go b/model/command_test.go index 1995c4572e..821be35466 100644 --- a/model/command_test.go +++ b/model/command_test.go @@ -28,7 +28,7 @@ func TestCommandIsValid(t *testing.T) { TeamId: NewId(), Trigger: "trigger", URL: "http://example.com", - Method: COMMAND_METHOD_GET, + Method: CommandMethodGet, DisplayName: "", Description: "", } @@ -95,10 +95,10 @@ func TestCommandIsValid(t *testing.T) { o.Method = "https://example.com" require.NotNil(t, o.IsValid(), "should be invalid") - o.Method = COMMAND_METHOD_GET + o.Method = CommandMethodGet require.Nil(t, o.IsValid()) - o.Method = COMMAND_METHOD_POST + o.Method = CommandMethodPost require.Nil(t, o.IsValid()) o.DisplayName = strings.Repeat("1", 65) diff --git a/model/command_webhook.go b/model/command_webhook.go index 3757ecc79a..e6c611d263 100644 --- a/model/command_webhook.go +++ b/model/command_webhook.go @@ -19,7 +19,7 @@ type CommandWebhook struct { } const ( - COMMAND_WEBHOOK_LIFETIME = 1000 * 60 * 30 + CommandWebhookLifetime = 1000 * 60 * 30 ) func (o *CommandWebhook) PreSave() { diff --git a/model/compliance.go b/model/compliance.go index 0211805e75..62fc1854e2 100644 --- a/model/compliance.go +++ b/model/compliance.go @@ -11,14 +11,14 @@ import ( ) const ( - COMPLIANCE_STATUS_CREATED = "created" - COMPLIANCE_STATUS_RUNNING = "running" - COMPLIANCE_STATUS_FINISHED = "finished" - COMPLIANCE_STATUS_FAILED = "failed" - COMPLIANCE_STATUS_REMOVED = "removed" + ComplianceStatusCreated = "created" + ComplianceStatusRunning = "running" + ComplianceStatusFinished = "finished" + ComplianceStatusFailed = "failed" + ComplianceStatusRemoved = "removed" - COMPLIANCE_TYPE_DAILY = "daily" - COMPLIANCE_TYPE_ADHOC = "adhoc" + ComplianceTypeDaily = "daily" + ComplianceTypeAdhoc = "adhoc" ) type Compliance struct { @@ -61,7 +61,7 @@ func (c *Compliance) PreSave() { } if c.Status == "" { - c.Status = COMPLIANCE_STATUS_CREATED + c.Status = ComplianceStatusCreated } c.Count = 0 @@ -78,7 +78,7 @@ func (c *Compliance) DeepCopy() *Compliance { func (c *Compliance) JobName() string { jobName := c.Type - if c.Type == COMPLIANCE_TYPE_DAILY { + if c.Type == ComplianceTypeDaily { jobName += "-" + c.Desc } diff --git a/model/config.go b/model/config.go index b8903e1f91..92fd7eda4c 100644 --- a/model/config.go +++ b/model/config.go @@ -25,223 +25,223 @@ import ( ) const ( - CONN_SECURITY_NONE = "" - CONN_SECURITY_PLAIN = "PLAIN" - CONN_SECURITY_TLS = "TLS" - CONN_SECURITY_STARTTLS = "STARTTLS" + ConnSecurityNone = "" + ConnSecurityPlain = "PLAIN" + ConnSecurityTls = "TLS" + ConnSecurityStarttls = "STARTTLS" - IMAGE_DRIVER_LOCAL = "local" - IMAGE_DRIVER_S3 = "amazons3" + ImageDriverLocal = "local" + ImageDriverS3 = "amazons3" - DATABASE_DRIVER_MYSQL = "mysql" - DATABASE_DRIVER_POSTGRES = "postgres" + DatabaseDriverMysql = "mysql" + DatabaseDriverPostgres = "postgres" - SEARCHENGINE_ELASTICSEARCH = "elasticsearch" + SearchengineElasticsearch = "elasticsearch" - MINIO_ACCESS_KEY = "minioaccesskey" - MINIO_SECRET_KEY = "miniosecretkey" - MINIO_BUCKET = "mattermost-test" + MinioAccessKey = "minioaccesskey" + MinioSecretKey = "miniosecretkey" + MinioBucket = "mattermost-test" - PASSWORD_MAXIMUM_LENGTH = 64 - PASSWORD_MINIMUM_LENGTH = 5 + PasswordMaximumLength = 64 + PasswordMinimumLength = 5 - SERVICE_GITLAB = "gitlab" - SERVICE_GOOGLE = "google" - SERVICE_OFFICE365 = "office365" - SERVICE_OPENID = "openid" + ServiceGitlab = "gitlab" + ServiceGoogle = "google" + ServiceOffice365 = "office365" + ServiceOpenid = "openid" - GENERIC_NO_CHANNEL_NOTIFICATION = "generic_no_channel" - GENERIC_NOTIFICATION = "generic" - GENERIC_NOTIFICATION_SERVER = "https://push-test.mattermost.com" - MM_SUPPORT_ADVISOR_ADDRESS = "support-advisor@mattermost.com" - FULL_NOTIFICATION = "full" - ID_LOADED_NOTIFICATION = "id_loaded" + GenericNoChannelNotification = "generic_no_channel" + GenericNotification = "generic" + GenericNotificationServer = "https://push-test.mattermost.com" + MmSupportAdvisorAddress = "support-advisor@mattermost.com" + FullNotification = "full" + IdLoadedNotification = "id_loaded" - DIRECT_MESSAGE_ANY = "any" - DIRECT_MESSAGE_TEAM = "team" + DirectMessageAny = "any" + DirectMessageTeam = "team" - SHOW_USERNAME = "username" - SHOW_NICKNAME_FULLNAME = "nickname_full_name" - SHOW_FULLNAME = "full_name" + ShowUsername = "username" + ShowNicknameFullName = "nickname_full_name" + ShowFullName = "full_name" - PERMISSIONS_ALL = "all" - PERMISSIONS_CHANNEL_ADMIN = "channel_admin" - PERMISSIONS_TEAM_ADMIN = "team_admin" - PERMISSIONS_SYSTEM_ADMIN = "system_admin" + PermissionsAll = "all" + PermissionsChannelAdmin = "channel_admin" + PermissionsTeamAdmin = "team_admin" + PermissionsSystemAdmin = "system_admin" - FAKE_SETTING = "********************************" + FakeSetting = "********************************" - RESTRICT_EMOJI_CREATION_ALL = "all" - RESTRICT_EMOJI_CREATION_ADMIN = "admin" - RESTRICT_EMOJI_CREATION_SYSTEM_ADMIN = "system_admin" + RestrictEmojiCreationAll = "all" + RestrictEmojiCreationAdmin = "admin" + RestrictEmojiCreationSystemAdmin = "system_admin" - PERMISSIONS_DELETE_POST_ALL = "all" - PERMISSIONS_DELETE_POST_TEAM_ADMIN = "team_admin" - PERMISSIONS_DELETE_POST_SYSTEM_ADMIN = "system_admin" + PermissionsDeletePostAll = "all" + PermissionsDeletePostTeamAdmin = "team_admin" + PermissionsDeletePostSystemAdmin = "system_admin" - ALLOW_EDIT_POST_ALWAYS = "always" - ALLOW_EDIT_POST_NEVER = "never" - ALLOW_EDIT_POST_TIME_LIMIT = "time_limit" + AllowEditPostAlways = "always" + AllowEditPostNever = "never" + AllowEditPostTimeLimit = "time_limit" - GROUP_UNREAD_CHANNELS_DISABLED = "disabled" - GROUP_UNREAD_CHANNELS_DEFAULT_ON = "default_on" - GROUP_UNREAD_CHANNELS_DEFAULT_OFF = "default_off" + GroupUnreadChannelsDisabled = "disabled" + GroupUnreadChannelsDefaultOn = "default_on" + GroupUnreadChannelsDefaultOff = "default_off" - COLLAPSED_THREADS_DISABLED = "disabled" - COLLAPSED_THREADS_DEFAULT_ON = "default_on" - COLLAPSED_THREADS_DEFAULT_OFF = "default_off" + CollapsedThreadsDisabled = "disabled" + CollapsedThreadsDefaultOn = "default_on" + CollapsedThreadsDefaultOff = "default_off" - EMAIL_BATCHING_BUFFER_SIZE = 256 - EMAIL_BATCHING_INTERVAL = 30 + EmailBatchingBufferSize = 256 + EmailBatchingInterval = 30 - EMAIL_NOTIFICATION_CONTENTS_FULL = "full" - EMAIL_NOTIFICATION_CONTENTS_GENERIC = "generic" + EmailNotificationContentsFull = "full" + EmailNotificationContentsGeneric = "generic" - SITENAME_MAX_LENGTH = 30 + SitenameMaxLength = 30 - SERVICE_SETTINGS_DEFAULT_SITE_URL = "http://localhost:8065" - SERVICE_SETTINGS_DEFAULT_TLS_CERT_FILE = "" - SERVICE_SETTINGS_DEFAULT_TLS_KEY_FILE = "" - SERVICE_SETTINGS_DEFAULT_READ_TIMEOUT = 300 - SERVICE_SETTINGS_DEFAULT_WRITE_TIMEOUT = 300 - SERVICE_SETTINGS_DEFAULT_IDLE_TIMEOUT = 60 - SERVICE_SETTINGS_DEFAULT_MAX_LOGIN_ATTEMPTS = 10 - SERVICE_SETTINGS_DEFAULT_ALLOW_CORS_FROM = "" - SERVICE_SETTINGS_DEFAULT_LISTEN_AND_ADDRESS = ":8065" - SERVICE_SETTINGS_DEFAULT_GFYCAT_API_KEY = "2_KtH_W5" - SERVICE_SETTINGS_DEFAULT_GFYCAT_API_SECRET = "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof" + ServiceSettingsDefaultSiteUrl = "http://localhost:8065" + ServiceSettingsDefaultTlsCertFile = "" + ServiceSettingsDefaultTlsKeyFile = "" + ServiceSettingsDefaultReadTimeout = 300 + ServiceSettingsDefaultWriteTimeout = 300 + ServiceSettingsDefaultIdleTimeout = 60 + ServiceSettingsDefaultMaxLoginAttempts = 10 + ServiceSettingsDefaultAllowCorsFrom = "" + ServiceSettingsDefaultListenAndAddress = ":8065" + ServiceSettingsDefaultGfycatApiKey = "2_KtH_W5" + ServiceSettingsDefaultGfycatApiSecret = "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof" - TEAM_SETTINGS_DEFAULT_SITE_NAME = "Mattermost" - TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM = 50 - TEAM_SETTINGS_DEFAULT_CUSTOM_BRAND_TEXT = "" - TEAM_SETTINGS_DEFAULT_CUSTOM_DESCRIPTION_TEXT = "" - TEAM_SETTINGS_DEFAULT_USER_STATUS_AWAY_TIMEOUT = 300 + TeamSettingsDefaultSiteName = "Mattermost" + TeamSettingsDefaultMaxUsersPerTeam = 50 + TeamSettingsDefaultCustomBrandText = "" + TeamSettingsDefaultCustomDescriptionText = "" + TeamSettingsDefaultUserStatusAwayTimeout = 300 - SQL_SETTINGS_DEFAULT_DATA_SOURCE = "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable&connect_timeout=10" + SqlSettingsDefaultDataSource = "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable&connect_timeout=10" - FILE_SETTINGS_DEFAULT_DIRECTORY = "./data/" + FileSettingsDefaultDirectory = "./data/" - IMPORT_SETTINGS_DEFAULT_DIRECTORY = "./import" - IMPORT_SETTINGS_DEFAULT_RETENTION_DAYS = 30 + ImportSettingsDefaultDirectory = "./import" + ImportSettingsDefaultRetentionDays = 30 - EXPORT_SETTINGS_DEFAULT_DIRECTORY = "./export" - EXPORT_SETTINGS_DEFAULT_RETENTION_DAYS = 30 + ExportSettingsDefaultDirectory = "./export" + ExportSettingsDefaultRetentionDays = 30 - EMAIL_SETTINGS_DEFAULT_FEEDBACK_ORGANIZATION = "" + EmailSettingsDefaultFeedbackOrganization = "" - SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK = "https://mattermost.com/terms-of-service/" - SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK = "https://mattermost.com/privacy-policy/" - SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK = "https://about.mattermost.com/default-about/" - SUPPORT_SETTINGS_DEFAULT_HELP_LINK = "https://about.mattermost.com/default-help/" - SUPPORT_SETTINGS_DEFAULT_REPORT_A_PROBLEM_LINK = "https://about.mattermost.com/default-report-a-problem/" - SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL = "" - SUPPORT_SETTINGS_DEFAULT_RE_ACCEPTANCE_PERIOD = 365 + SupportSettingsDefaultTermsOfServiceLink = "https://mattermost.com/terms-of-service/" + SupportSettingsDefaultPrivacyPolicyLink = "https://mattermost.com/privacy-policy/" + SupportSettingsDefaultAboutLink = "https://about.mattermost.com/default-about/" + SupportSettingsDefaultHelpLink = "https://about.mattermost.com/default-help/" + SupportSettingsDefaultReportAProblemLink = "https://about.mattermost.com/default-report-a-problem/" + SupportSettingsDefaultSupportEmail = "" + SupportSettingsDefaultReAcceptancePeriod = 365 - LDAP_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_ID_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_POSITION_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_LOGIN_FIELD_NAME = "" - LDAP_SETTINGS_DEFAULT_GROUP_DISPLAY_NAME_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_GROUP_ID_ATTRIBUTE = "" - LDAP_SETTINGS_DEFAULT_PICTURE_ATTRIBUTE = "" + LdapSettingsDefaultFirstNameAttribute = "" + LdapSettingsDefaultLastNameAttribute = "" + LdapSettingsDefaultEmailAttribute = "" + LdapSettingsDefaultUsernameAttribute = "" + LdapSettingsDefaultNicknameAttribute = "" + LdapSettingsDefaultIdAttribute = "" + LdapSettingsDefaultPositionAttribute = "" + LdapSettingsDefaultLoginFieldName = "" + LdapSettingsDefaultGroupDisplayNameAttribute = "" + LdapSettingsDefaultGroupIdAttribute = "" + LdapSettingsDefaultPictureAttribute = "" - SAML_SETTINGS_DEFAULT_ID_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_GUEST_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_ADMIN_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_LOCALE_ATTRIBUTE = "" - SAML_SETTINGS_DEFAULT_POSITION_ATTRIBUTE = "" + SamlSettingsDefaultIdAttribute = "" + SamlSettingsDefaultGuestAttribute = "" + SamlSettingsDefaultAdminAttribute = "" + SamlSettingsDefaultFirstNameAttribute = "" + SamlSettingsDefaultLastNameAttribute = "" + SamlSettingsDefaultEmailAttribute = "" + SamlSettingsDefaultUsernameAttribute = "" + SamlSettingsDefaultNicknameAttribute = "" + SamlSettingsDefaultLocaleAttribute = "" + SamlSettingsDefaultPositionAttribute = "" - SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA1 = "RSAwithSHA1" - SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256 = "RSAwithSHA256" - SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA512 = "RSAwithSHA512" - SAML_SETTINGS_DEFAULT_SIGNATURE_ALGORITHM = SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA1 + SamlSettingsSignatureAlgorithmSha1 = "RSAwithSHA1" + SamlSettingsSignatureAlgorithmSha256 = "RSAwithSHA256" + SamlSettingsSignatureAlgorithmSha512 = "RSAwithSHA512" + SamlSettingsDefaultSignatureAlgorithm = SamlSettingsSignatureAlgorithmSha1 - SAML_SETTINGS_CANONICAL_ALGORITHM_C14N = "Canonical1.0" - SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11 = "Canonical1.1" - SAML_SETTINGS_DEFAULT_CANONICAL_ALGORITHM = SAML_SETTINGS_CANONICAL_ALGORITHM_C14N + SamlSettingsCanonicalAlgorithmC14n = "Canonical1.0" + SamlSettingsCanonicalAlgorithmC14n11 = "Canonical1.1" + SamlSettingsDefaultCanonicalAlgorithm = SamlSettingsCanonicalAlgorithmC14n - NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK = "https://mattermost.com/download/#mattermostApps" - NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK = "https://about.mattermost.com/mattermost-android-app/" - NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK = "https://about.mattermost.com/mattermost-ios-app/" + NativeappSettingsDefaultAppDownloadLink = "https://mattermost.com/download/#mattermostApps" + NativeappSettingsDefaultAndroidAppDownloadLink = "https://about.mattermost.com/mattermost-android-app/" + NativeappSettingsDefaultIosAppDownloadLink = "https://about.mattermost.com/mattermost-ios-app/" - EXPERIMENTAL_SETTINGS_DEFAULT_LINK_METADATA_TIMEOUT_MILLISECONDS = 5000 + ExperimentalSettingsDefaultLinkMetadataTimeoutMilliseconds = 5000 - ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS = 2500 + AnalyticsSettingsDefaultMaxUsersForStatistics = 2500 - ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR = "#f2a93b" - ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR = "#333333" - ANNOUNCEMENT_SETTINGS_DEFAULT_NOTICES_JSON_URL = "https://notices.mattermost.com/" - ANNOUNCEMENT_SETTINGS_DEFAULT_NOTICES_FETCH_FREQUENCY_SECONDS = 3600 + AnnouncementSettingsDefaultBannerColor = "#f2a93b" + AnnouncementSettingsDefaultBannerTextColor = "#333333" + AnnouncementSettingsDefaultNoticesJsonUrl = "https://notices.mattermost.com/" + AnnouncementSettingsDefaultNoticesFetchFrequencySeconds = 3600 - TEAM_SETTINGS_DEFAULT_TEAM_TEXT = "default" + TeamSettingsDefaultTeamText = "default" - ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL = "http://localhost:9200" - ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME = "elastic" - ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD = "changeme" - ELASTICSEARCH_SETTINGS_DEFAULT_POST_INDEX_REPLICAS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_POST_INDEX_SHARDS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_CHANNEL_INDEX_REPLICAS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_CHANNEL_INDEX_SHARDS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_USER_INDEX_REPLICAS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_USER_INDEX_SHARDS = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_AGGREGATE_POSTS_AFTER_DAYS = 365 - ELASTICSEARCH_SETTINGS_DEFAULT_POSTS_AGGREGATOR_JOB_START_TIME = "03:00" - ELASTICSEARCH_SETTINGS_DEFAULT_INDEX_PREFIX = "" - ELASTICSEARCH_SETTINGS_DEFAULT_LIVE_INDEXING_BATCH_SIZE = 1 - ELASTICSEARCH_SETTINGS_DEFAULT_BULK_INDEXING_TIME_WINDOW_SECONDS = 3600 - ELASTICSEARCH_SETTINGS_DEFAULT_REQUEST_TIMEOUT_SECONDS = 30 + ElasticsearchSettingsDefaultConnectionUrl = "http://localhost:9200" + ElasticsearchSettingsDefaultUsername = "elastic" + ElasticsearchSettingsDefaultPassword = "changeme" + ElasticsearchSettingsDefaultPostIndexReplicas = 1 + ElasticsearchSettingsDefaultPostIndexShards = 1 + ElasticsearchSettingsDefaultChannelIndexReplicas = 1 + ElasticsearchSettingsDefaultChannelIndexShards = 1 + ElasticsearchSettingsDefaultUserIndexReplicas = 1 + ElasticsearchSettingsDefaultUserIndexShards = 1 + ElasticsearchSettingsDefaultAggregatePostsAfterDays = 365 + ElasticsearchSettingsDefaultPostsAggregatorJobStartTime = "03:00" + ElasticsearchSettingsDefaultIndexPrefix = "" + ElasticsearchSettingsDefaultLiveIndexingBatchSize = 1 + ElasticsearchSettingsDefaultBulkIndexingTimeWindowSeconds = 3600 + ElasticsearchSettingsDefaultRequestTimeoutSeconds = 30 - BLEVE_SETTINGS_DEFAULT_INDEX_DIR = "" - BLEVE_SETTINGS_DEFAULT_BULK_INDEXING_TIME_WINDOW_SECONDS = 3600 + BleveSettingsDefaultIndexDir = "" + BleveSettingsDefaultBulkIndexingTimeWindowSeconds = 3600 - DATA_RETENTION_SETTINGS_DEFAULT_MESSAGE_RETENTION_DAYS = 365 - DATA_RETENTION_SETTINGS_DEFAULT_FILE_RETENTION_DAYS = 365 - DATA_RETENTION_SETTINGS_DEFAULT_DELETION_JOB_START_TIME = "02:00" - DATA_RETENTION_SETTINGS_DEFAULT_BATCH_SIZE = 3000 + DataRetentionSettingsDefaultMessageRetentionDays = 365 + DataRetentionSettingsDefaultFileRetentionDays = 365 + DataRetentionSettingsDefaultDeletionJobStartTime = "02:00" + DataRetentionSettingsDefaultBatchSize = 3000 - PLUGIN_SETTINGS_DEFAULT_DIRECTORY = "./plugins" - PLUGIN_SETTINGS_DEFAULT_CLIENT_DIRECTORY = "./client/plugins" - PLUGIN_SETTINGS_DEFAULT_ENABLE_MARKETPLACE = true - PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL = "https://api.integrations.mattermost.com" - PLUGIN_SETTINGS_OLD_MARKETPLACE_URL = "https://marketplace.integrations.mattermost.com" + PluginSettingsDefaultDirectory = "./plugins" + PluginSettingsDefaultClientDirectory = "./client/plugins" + PluginSettingsDefaultEnableMarketplace = true + PluginSettingsDefaultMarketplaceUrl = "https://api.integrations.mattermost.com" + PluginSettingsOldMarketplaceUrl = "https://marketplace.integrations.mattermost.com" - COMPLIANCE_EXPORT_TYPE_CSV = "csv" - COMPLIANCE_EXPORT_TYPE_ACTIANCE = "actiance" - COMPLIANCE_EXPORT_TYPE_GLOBALRELAY = "globalrelay" - COMPLIANCE_EXPORT_TYPE_GLOBALRELAY_ZIP = "globalrelay-zip" - GLOBALRELAY_CUSTOMER_TYPE_A9 = "A9" - GLOBALRELAY_CUSTOMER_TYPE_A10 = "A10" + ComplianceExportTypeCsv = "csv" + ComplianceExportTypeActiance = "actiance" + ComplianceExportTypeGlobalrelay = "globalrelay" + ComplianceExportTypeGlobalrelayZip = "globalrelay-zip" + GlobalrelayCustomerTypeA9 = "A9" + GlobalrelayCustomerTypeA10 = "A10" - CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH = "primary" - CLIENT_SIDE_CERT_CHECK_SECONDARY_AUTH = "secondary" + ClientSideCertCheckPrimaryAuth = "primary" + ClientSideCertCheckSecondaryAuth = "secondary" - IMAGE_PROXY_TYPE_LOCAL = "local" - IMAGE_PROXY_TYPE_ATMOS_CAMO = "atmos/camo" + ImageProxyTypeLocal = "local" + ImageProxyTypeAtmosCamo = "atmos/camo" - GOOGLE_SETTINGS_DEFAULT_SCOPE = "profile email" - GOOGLE_SETTINGS_DEFAULT_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth" - GOOGLE_SETTINGS_DEFAULT_TOKEN_ENDPOINT = "https://www.googleapis.com/oauth2/v4/token" - GOOGLE_SETTINGS_DEFAULT_USER_API_ENDPOINT = "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata" + GoogleSettingsDefaultScope = "profile email" + GoogleSettingsDefaultAuthEndpoint = "https://accounts.google.com/o/oauth2/v2/auth" + GoogleSettingsDefaultTokenEndpoint = "https://www.googleapis.com/oauth2/v4/token" + GoogleSettingsDefaultUserApiEndpoint = "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata" - OFFICE365_SETTINGS_DEFAULT_SCOPE = "User.Read" - OFFICE365_SETTINGS_DEFAULT_AUTH_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" - OFFICE365_SETTINGS_DEFAULT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token" - OFFICE365_SETTINGS_DEFAULT_USER_API_ENDPOINT = "https://graph.microsoft.com/v1.0/me" + Office365SettingsDefaultScope = "User.Read" + Office365SettingsDefaultAuthEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" + Office365SettingsDefaultTokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token" + Office365SettingsDefaultUserApiEndpoint = "https://graph.microsoft.com/v1.0/me" - CLOUD_SETTINGS_DEFAULT_CWS_URL = "https://customers.mattermost.com" - CLOUD_SETTINGS_DEFAULT_CWS_API_URL = "https://portal.internal.prod.cloud.mattermost.com" - OPENID_SETTINGS_DEFAULT_SCOPE = "profile openid email" + CloudSettingsDefaultCwsUrl = "https://customers.mattermost.com" + CloudSettingsDefaultCwsApiUrl = "https://portal.internal.prod.cloud.mattermost.com" + OpenidSettingsDefaultScope = "profile openid email" - LOCAL_MODE_SOCKET_PATH = "/var/tmp/mattermost_local.socket" + LocalModeSocketPath = "/var/tmp/mattermost_local.socket" ) func GetDefaultAppCustomURLSchemes() []string { @@ -390,7 +390,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { if s.SiteURL == nil { if s.EnableDeveloper != nil && *s.EnableDeveloper { - s.SiteURL = NewString(SERVICE_SETTINGS_DEFAULT_SITE_URL) + s.SiteURL = NewString(ServiceSettingsDefaultSiteUrl) } else { s.SiteURL = NewString("") } @@ -405,7 +405,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.ListenAddress == nil { - s.ListenAddress = NewString(SERVICE_SETTINGS_DEFAULT_LISTEN_AND_ADDRESS) + s.ListenAddress = NewString(ServiceSettingsDefaultListenAndAddress) } if s.EnableLinkPreviews == nil { @@ -477,11 +477,11 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.TLSKeyFile == nil { - s.TLSKeyFile = NewString(SERVICE_SETTINGS_DEFAULT_TLS_KEY_FILE) + s.TLSKeyFile = NewString(ServiceSettingsDefaultTlsKeyFile) } if s.TLSCertFile == nil { - s.TLSCertFile = NewString(SERVICE_SETTINGS_DEFAULT_TLS_CERT_FILE) + s.TLSCertFile = NewString(ServiceSettingsDefaultTlsCertFile) } if s.TLSMinVer == nil { @@ -509,19 +509,19 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.ReadTimeout == nil { - s.ReadTimeout = NewInt(SERVICE_SETTINGS_DEFAULT_READ_TIMEOUT) + s.ReadTimeout = NewInt(ServiceSettingsDefaultReadTimeout) } if s.WriteTimeout == nil { - s.WriteTimeout = NewInt(SERVICE_SETTINGS_DEFAULT_WRITE_TIMEOUT) + s.WriteTimeout = NewInt(ServiceSettingsDefaultWriteTimeout) } if s.IdleTimeout == nil { - s.IdleTimeout = NewInt(SERVICE_SETTINGS_DEFAULT_IDLE_TIMEOUT) + s.IdleTimeout = NewInt(ServiceSettingsDefaultIdleTimeout) } if s.MaximumLoginAttempts == nil { - s.MaximumLoginAttempts = NewInt(SERVICE_SETTINGS_DEFAULT_MAX_LOGIN_ATTEMPTS) + s.MaximumLoginAttempts = NewInt(ServiceSettingsDefaultMaxLoginAttempts) } if s.Forward80To443 == nil { @@ -531,7 +531,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { if isUpdate { // When updating an existing configuration, ensure that defaults are set. if s.TrustedProxyIPHeader == nil { - s.TrustedProxyIPHeader = []string{HEADER_FORWARDED, HEADER_REAL_IP} + s.TrustedProxyIPHeader = []string{HeaderForwarded, HeaderRealIp} } } else { // When generating a blank configuration, leave the list empty. @@ -636,7 +636,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.AllowCorsFrom == nil { - s.AllowCorsFrom = NewString(SERVICE_SETTINGS_DEFAULT_ALLOW_CORS_FROM) + s.AllowCorsFrom = NewString(ServiceSettingsDefaultAllowCorsFrom) } if s.CorsExposedHeaders == nil { @@ -674,23 +674,23 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.GfycatApiKey == nil || *s.GfycatApiKey == "" { - s.GfycatApiKey = NewString(SERVICE_SETTINGS_DEFAULT_GFYCAT_API_KEY) + s.GfycatApiKey = NewString(ServiceSettingsDefaultGfycatApiKey) } if s.GfycatApiSecret == nil || *s.GfycatApiSecret == "" { - s.GfycatApiSecret = NewString(SERVICE_SETTINGS_DEFAULT_GFYCAT_API_SECRET) + s.GfycatApiSecret = NewString(ServiceSettingsDefaultGfycatApiSecret) } if s.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation == nil { - s.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = NewString(RESTRICT_EMOJI_CREATION_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = NewString(RestrictEmojiCreationAll) } if s.DEPRECATED_DO_NOT_USE_RestrictPostDelete == nil { - s.DEPRECATED_DO_NOT_USE_RestrictPostDelete = NewString(PERMISSIONS_DELETE_POST_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictPostDelete = NewString(PermissionsDeletePostAll) } if s.DEPRECATED_DO_NOT_USE_AllowEditPost == nil { - s.DEPRECATED_DO_NOT_USE_AllowEditPost = NewString(ALLOW_EDIT_POST_ALWAYS) + s.DEPRECATED_DO_NOT_USE_AllowEditPost = NewString(AllowEditPostAlways) } if s.ExperimentalEnableAuthenticationTransfer == nil { @@ -710,15 +710,15 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.ExperimentalGroupUnreadChannels == nil { - s.ExperimentalGroupUnreadChannels = NewString(GROUP_UNREAD_CHANNELS_DISABLED) + s.ExperimentalGroupUnreadChannels = NewString(GroupUnreadChannelsDisabled) } else if *s.ExperimentalGroupUnreadChannels == "0" { - s.ExperimentalGroupUnreadChannels = NewString(GROUP_UNREAD_CHANNELS_DISABLED) + s.ExperimentalGroupUnreadChannels = NewString(GroupUnreadChannelsDisabled) } else if *s.ExperimentalGroupUnreadChannels == "1" { - s.ExperimentalGroupUnreadChannels = NewString(GROUP_UNREAD_CHANNELS_DEFAULT_ON) + s.ExperimentalGroupUnreadChannels = NewString(GroupUnreadChannelsDefaultOn) } if s.ExperimentalChannelOrganization == nil { - experimentalUnreadEnabled := *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DISABLED + experimentalUnreadEnabled := *s.ExperimentalGroupUnreadChannels != GroupUnreadChannelsDisabled s.ExperimentalChannelOrganization = NewBool(experimentalUnreadEnabled) } @@ -787,7 +787,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.LocalModeSocketLocation == nil { - s.LocalModeSocketLocation = NewString(LOCAL_MODE_SOCKET_PATH) + s.LocalModeSocketLocation = NewString(LocalModeSocketPath) } if s.EnableAWSMetering == nil { @@ -811,7 +811,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) { } if s.CollapsedThreads == nil { - s.CollapsedThreads = NewString(COLLAPSED_THREADS_DISABLED) + s.CollapsedThreads = NewString(CollapsedThreadsDisabled) } if s.ManagedResourcePaths == nil { @@ -951,7 +951,7 @@ func (s *ExperimentalSettings) SetDefaults() { } if s.ClientSideCertCheck == nil { - s.ClientSideCertCheck = NewString(CLIENT_SIDE_CERT_CHECK_SECONDARY_AUTH) + s.ClientSideCertCheck = NewString(ClientSideCertCheckSecondaryAuth) } if s.EnableClickToReply == nil { @@ -959,7 +959,7 @@ func (s *ExperimentalSettings) SetDefaults() { } if s.LinkMetadataTimeoutMilliseconds == nil { - s.LinkMetadataTimeoutMilliseconds = NewInt64(EXPERIMENTAL_SETTINGS_DEFAULT_LINK_METADATA_TIMEOUT_MILLISECONDS) + s.LinkMetadataTimeoutMilliseconds = NewInt64(ExperimentalSettingsDefaultLinkMetadataTimeoutMilliseconds) } if s.RestrictSystemAdmin == nil { @@ -994,7 +994,7 @@ type AnalyticsSettings struct { func (s *AnalyticsSettings) SetDefaults() { if s.MaxUsersForStatistics == nil { - s.MaxUsersForStatistics = NewInt(ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS) + s.MaxUsersForStatistics = NewInt(AnalyticsSettingsDefaultMaxUsersForStatistics) } } @@ -1079,7 +1079,7 @@ func (s *Office365Settings) setDefaults() { } if s.Scope == nil { - s.Scope = NewString(OFFICE365_SETTINGS_DEFAULT_SCOPE) + s.Scope = NewString(Office365SettingsDefaultScope) } if s.DiscoveryEndpoint == nil { @@ -1087,15 +1087,15 @@ func (s *Office365Settings) setDefaults() { } if s.AuthEndpoint == nil { - s.AuthEndpoint = NewString(OFFICE365_SETTINGS_DEFAULT_AUTH_ENDPOINT) + s.AuthEndpoint = NewString(Office365SettingsDefaultAuthEndpoint) } if s.TokenEndpoint == nil { - s.TokenEndpoint = NewString(OFFICE365_SETTINGS_DEFAULT_TOKEN_ENDPOINT) + s.TokenEndpoint = NewString(Office365SettingsDefaultTokenEndpoint) } if s.UserApiEndpoint == nil { - s.UserApiEndpoint = NewString(OFFICE365_SETTINGS_DEFAULT_USER_API_ENDPOINT) + s.UserApiEndpoint = NewString(Office365SettingsDefaultUserApiEndpoint) } if s.DirectoryId == nil { @@ -1140,11 +1140,11 @@ type SqlSettings struct { func (s *SqlSettings) SetDefaults(isUpdate bool) { if s.DriverName == nil { - s.DriverName = NewString(DATABASE_DRIVER_POSTGRES) + s.DriverName = NewString(DatabaseDriverPostgres) } if s.DataSource == nil { - s.DataSource = NewString(SQL_SETTINGS_DEFAULT_DATA_SOURCE) + s.DataSource = NewString(SqlSettingsDefaultDataSource) } if s.DataSourceReplicas == nil { @@ -1430,11 +1430,11 @@ func (s *FileSettings) SetDefaults(isUpdate bool) { } if s.DriverName == nil { - s.DriverName = NewString(IMAGE_DRIVER_LOCAL) + s.DriverName = NewString(ImageDriverLocal) } if s.Directory == nil || *s.Directory == "" { - s.Directory = NewString(FILE_SETTINGS_DEFAULT_DIRECTORY) + s.Directory = NewString(FileSettingsDefaultDirectory) } if s.EnablePublicLink == nil { @@ -1508,7 +1508,7 @@ func (s *FileSettings) SetDefaults(isUpdate bool) { } func (s *FileSettings) ToFileBackendSettings(enableComplianceFeature bool) filestore.FileBackendSettings { - if *s.DriverName == IMAGE_DRIVER_LOCAL { + if *s.DriverName == ImageDriverLocal { return filestore.FileBackendSettings{ DriverName: *s.DriverName, Directory: *s.Directory, @@ -1600,11 +1600,11 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { } if s.FeedbackOrganization == nil { - s.FeedbackOrganization = NewString(EMAIL_SETTINGS_DEFAULT_FEEDBACK_ORGANIZATION) + s.FeedbackOrganization = NewString(EmailSettingsDefaultFeedbackOrganization) } if s.EnableSMTPAuth == nil { - if s.ConnectionSecurity == nil || *s.ConnectionSecurity == CONN_SECURITY_NONE { + if s.ConnectionSecurity == nil || *s.ConnectionSecurity == ConnSecurityNone { s.EnableSMTPAuth = NewBool(false) } else { s.EnableSMTPAuth = NewBool(true) @@ -1631,8 +1631,8 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { s.SMTPServerTimeout = NewInt(10) } - if s.ConnectionSecurity == nil || *s.ConnectionSecurity == CONN_SECURITY_PLAIN { - s.ConnectionSecurity = NewString(CONN_SECURITY_NONE) + if s.ConnectionSecurity == nil || *s.ConnectionSecurity == ConnSecurityPlain { + s.ConnectionSecurity = NewString(ConnSecurityNone) } if s.SendPushNotifications == nil { @@ -1643,12 +1643,12 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { if isUpdate { s.PushNotificationServer = NewString("") } else { - s.PushNotificationServer = NewString(GENERIC_NOTIFICATION_SERVER) + s.PushNotificationServer = NewString(GenericNotificationServer) } } if s.PushNotificationContents == nil { - s.PushNotificationContents = NewString(FULL_NOTIFICATION) + s.PushNotificationContents = NewString(FullNotification) } if s.PushNotificationBuffer == nil { @@ -1660,11 +1660,11 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { } if s.EmailBatchingBufferSize == nil { - s.EmailBatchingBufferSize = NewInt(EMAIL_BATCHING_BUFFER_SIZE) + s.EmailBatchingBufferSize = NewInt(EmailBatchingBufferSize) } if s.EmailBatchingInterval == nil { - s.EmailBatchingInterval = NewInt(EMAIL_BATCHING_INTERVAL) + s.EmailBatchingInterval = NewInt(EmailBatchingInterval) } if s.EnablePreviewModeBanner == nil { @@ -1672,15 +1672,15 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { } if s.EnableSMTPAuth == nil { - if *s.ConnectionSecurity == CONN_SECURITY_NONE { + if *s.ConnectionSecurity == ConnSecurityNone { s.EnableSMTPAuth = NewBool(false) } else { s.EnableSMTPAuth = NewBool(true) } } - if *s.ConnectionSecurity == CONN_SECURITY_PLAIN { - *s.ConnectionSecurity = CONN_SECURITY_NONE + if *s.ConnectionSecurity == ConnSecurityPlain { + *s.ConnectionSecurity = ConnSecurityNone } if s.SkipServerCertificateVerification == nil { @@ -1688,7 +1688,7 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) { } if s.EmailNotificationContentsType == nil { - s.EmailNotificationContentsType = NewString(EMAIL_NOTIFICATION_CONTENTS_FULL) + s.EmailNotificationContentsType = NewString(EmailNotificationContentsFull) } if s.LoginButtonColor == nil { @@ -1769,11 +1769,11 @@ type SupportSettings struct { func (s *SupportSettings) SetDefaults() { if !IsSafeLink(s.TermsOfServiceLink) { - *s.TermsOfServiceLink = SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK + *s.TermsOfServiceLink = SupportSettingsDefaultTermsOfServiceLink } if s.TermsOfServiceLink == nil { - s.TermsOfServiceLink = NewString(SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK) + s.TermsOfServiceLink = NewString(SupportSettingsDefaultTermsOfServiceLink) } if !IsSafeLink(s.PrivacyPolicyLink) { @@ -1781,7 +1781,7 @@ func (s *SupportSettings) SetDefaults() { } if s.PrivacyPolicyLink == nil { - s.PrivacyPolicyLink = NewString(SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK) + s.PrivacyPolicyLink = NewString(SupportSettingsDefaultPrivacyPolicyLink) } if !IsSafeLink(s.AboutLink) { @@ -1789,7 +1789,7 @@ func (s *SupportSettings) SetDefaults() { } if s.AboutLink == nil { - s.AboutLink = NewString(SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK) + s.AboutLink = NewString(SupportSettingsDefaultAboutLink) } if !IsSafeLink(s.HelpLink) { @@ -1797,7 +1797,7 @@ func (s *SupportSettings) SetDefaults() { } if s.HelpLink == nil { - s.HelpLink = NewString(SUPPORT_SETTINGS_DEFAULT_HELP_LINK) + s.HelpLink = NewString(SupportSettingsDefaultHelpLink) } if !IsSafeLink(s.ReportAProblemLink) { @@ -1805,11 +1805,11 @@ func (s *SupportSettings) SetDefaults() { } if s.ReportAProblemLink == nil { - s.ReportAProblemLink = NewString(SUPPORT_SETTINGS_DEFAULT_REPORT_A_PROBLEM_LINK) + s.ReportAProblemLink = NewString(SupportSettingsDefaultReportAProblemLink) } if s.SupportEmail == nil { - s.SupportEmail = NewString(SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL) + s.SupportEmail = NewString(SupportSettingsDefaultSupportEmail) } if s.CustomTermsOfServiceEnabled == nil { @@ -1817,7 +1817,7 @@ func (s *SupportSettings) SetDefaults() { } if s.CustomTermsOfServiceReAcceptancePeriod == nil { - s.CustomTermsOfServiceReAcceptancePeriod = NewInt(SUPPORT_SETTINGS_DEFAULT_RE_ACCEPTANCE_PERIOD) + s.CustomTermsOfServiceReAcceptancePeriod = NewInt(SupportSettingsDefaultReAcceptancePeriod) } if s.EnableAskCommunityLink == nil { @@ -1848,11 +1848,11 @@ func (s *AnnouncementSettings) SetDefaults() { } if s.BannerColor == nil { - s.BannerColor = NewString(ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR) + s.BannerColor = NewString(AnnouncementSettingsDefaultBannerColor) } if s.BannerTextColor == nil { - s.BannerTextColor = NewString(ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR) + s.BannerTextColor = NewString(AnnouncementSettingsDefaultBannerTextColor) } if s.AllowBannerDismissal == nil { @@ -1867,13 +1867,13 @@ func (s *AnnouncementSettings) SetDefaults() { s.UserNoticesEnabled = NewBool(true) } if s.NoticesURL == nil { - s.NoticesURL = NewString(ANNOUNCEMENT_SETTINGS_DEFAULT_NOTICES_JSON_URL) + s.NoticesURL = NewString(AnnouncementSettingsDefaultNoticesJsonUrl) } if s.NoticesSkipCache == nil { s.NoticesSkipCache = NewBool(false) } if s.NoticesFetchFrequency == nil { - s.NoticesFetchFrequency = NewInt(ANNOUNCEMENT_SETTINGS_DEFAULT_NOTICES_FETCH_FREQUENCY_SECONDS) + s.NoticesFetchFrequency = NewInt(AnnouncementSettingsDefaultNoticesFetchFrequencySeconds) } } @@ -1891,7 +1891,7 @@ func (s *ThemeSettings) SetDefaults() { } if s.DefaultTheme == nil { - s.DefaultTheme = NewString(TEAM_SETTINGS_DEFAULT_TEAM_TEXT) + s.DefaultTheme = NewString(TeamSettingsDefaultTeamText) } if s.AllowCustomThemes == nil { @@ -1942,11 +1942,11 @@ type TeamSettings struct { func (s *TeamSettings) SetDefaults() { if s.SiteName == nil || *s.SiteName == "" { - s.SiteName = NewString(TEAM_SETTINGS_DEFAULT_SITE_NAME) + s.SiteName = NewString(TeamSettingsDefaultSiteName) } if s.MaxUsersPerTeam == nil { - s.MaxUsersPerTeam = NewInt(TEAM_SETTINGS_DEFAULT_MAX_USERS_PER_TEAM) + s.MaxUsersPerTeam = NewInt(TeamSettingsDefaultMaxUsersPerTeam) } if s.DEPRECATED_DO_NOT_USE_EnableTeamCreation == nil { @@ -1978,34 +1978,34 @@ func (s *TeamSettings) SetDefaults() { } if s.CustomBrandText == nil { - s.CustomBrandText = NewString(TEAM_SETTINGS_DEFAULT_CUSTOM_BRAND_TEXT) + s.CustomBrandText = NewString(TeamSettingsDefaultCustomBrandText) } if s.CustomDescriptionText == nil { - s.CustomDescriptionText = NewString(TEAM_SETTINGS_DEFAULT_CUSTOM_DESCRIPTION_TEXT) + s.CustomDescriptionText = NewString(TeamSettingsDefaultCustomDescriptionText) } if s.RestrictDirectMessage == nil { - s.RestrictDirectMessage = NewString(DIRECT_MESSAGE_ANY) + s.RestrictDirectMessage = NewString(DirectMessageAny) } if s.DEPRECATED_DO_NOT_USE_RestrictTeamInvite == nil { - s.DEPRECATED_DO_NOT_USE_RestrictTeamInvite = NewString(PERMISSIONS_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictTeamInvite = NewString(PermissionsAll) } if s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement == nil { - s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = NewString(PERMISSIONS_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = NewString(PermissionsAll) } if s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement == nil { - s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = NewString(PERMISSIONS_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = NewString(PermissionsAll) } if s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation == nil { s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation = new(string) // If this setting does not exist, assume migration from <3.6, so use management setting as default. - if *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement == PERMISSIONS_CHANNEL_ADMIN { - *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation = PERMISSIONS_TEAM_ADMIN + if *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement == PermissionsChannelAdmin { + *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation = PermissionsTeamAdmin } else { *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation = *s.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement } @@ -2013,8 +2013,8 @@ func (s *TeamSettings) SetDefaults() { if s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelCreation == nil { // If this setting does not exist, assume migration from <3.6, so use management setting as default. - if *s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement == PERMISSIONS_CHANNEL_ADMIN { - s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelCreation = NewString(PERMISSIONS_TEAM_ADMIN) + if *s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement == PermissionsChannelAdmin { + s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelCreation = NewString(PermissionsTeamAdmin) } else { s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelCreation = NewString(*s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement) } @@ -2031,7 +2031,7 @@ func (s *TeamSettings) SetDefaults() { } if s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManageMembers == nil { - s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManageMembers = NewString(PERMISSIONS_ALL) + s.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManageMembers = NewString(PermissionsAll) } if s.EnableXToLeaveChannelsFromLHS == nil { @@ -2039,7 +2039,7 @@ func (s *TeamSettings) SetDefaults() { } if s.UserStatusAwayTimeout == nil { - s.UserStatusAwayTimeout = NewInt64(TEAM_SETTINGS_DEFAULT_USER_STATUS_AWAY_TIMEOUT) + s.UserStatusAwayTimeout = NewInt64(TeamSettingsDefaultUserStatusAwayTimeout) } if s.MaxChannelsPerTeam == nil { @@ -2216,43 +2216,43 @@ func (s *LdapSettings) SetDefaults() { } if s.GroupDisplayNameAttribute == nil { - s.GroupDisplayNameAttribute = NewString(LDAP_SETTINGS_DEFAULT_GROUP_DISPLAY_NAME_ATTRIBUTE) + s.GroupDisplayNameAttribute = NewString(LdapSettingsDefaultGroupDisplayNameAttribute) } if s.GroupIdAttribute == nil { - s.GroupIdAttribute = NewString(LDAP_SETTINGS_DEFAULT_GROUP_ID_ATTRIBUTE) + s.GroupIdAttribute = NewString(LdapSettingsDefaultGroupIdAttribute) } if s.FirstNameAttribute == nil { - s.FirstNameAttribute = NewString(LDAP_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE) + s.FirstNameAttribute = NewString(LdapSettingsDefaultFirstNameAttribute) } if s.LastNameAttribute == nil { - s.LastNameAttribute = NewString(LDAP_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE) + s.LastNameAttribute = NewString(LdapSettingsDefaultLastNameAttribute) } if s.EmailAttribute == nil { - s.EmailAttribute = NewString(LDAP_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE) + s.EmailAttribute = NewString(LdapSettingsDefaultEmailAttribute) } if s.UsernameAttribute == nil { - s.UsernameAttribute = NewString(LDAP_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE) + s.UsernameAttribute = NewString(LdapSettingsDefaultUsernameAttribute) } if s.NicknameAttribute == nil { - s.NicknameAttribute = NewString(LDAP_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE) + s.NicknameAttribute = NewString(LdapSettingsDefaultNicknameAttribute) } if s.IdAttribute == nil { - s.IdAttribute = NewString(LDAP_SETTINGS_DEFAULT_ID_ATTRIBUTE) + s.IdAttribute = NewString(LdapSettingsDefaultIdAttribute) } if s.PositionAttribute == nil { - s.PositionAttribute = NewString(LDAP_SETTINGS_DEFAULT_POSITION_ATTRIBUTE) + s.PositionAttribute = NewString(LdapSettingsDefaultPositionAttribute) } if s.PictureAttribute == nil { - s.PictureAttribute = NewString(LDAP_SETTINGS_DEFAULT_PICTURE_ATTRIBUTE) + s.PictureAttribute = NewString(LdapSettingsDefaultPictureAttribute) } // For those upgrading to the version when LoginIdAttribute was added @@ -2278,7 +2278,7 @@ func (s *LdapSettings) SetDefaults() { } if s.LoginFieldName == nil { - s.LoginFieldName = NewString(LDAP_SETTINGS_DEFAULT_LOGIN_FIELD_NAME) + s.LoginFieldName = NewString(LdapSettingsDefaultLoginFieldName) } if s.LoginButtonColor == nil { @@ -2331,11 +2331,11 @@ type LocalizationSettings struct { func (s *LocalizationSettings) SetDefaults() { if s.DefaultServerLocale == nil { - s.DefaultServerLocale = NewString(DEFAULT_LOCALE) + s.DefaultServerLocale = NewString(DefaultLocale) } if s.DefaultClientLocale == nil { - s.DefaultClientLocale = NewString(DEFAULT_LOCALE) + s.DefaultClientLocale = NewString(DefaultLocale) } if s.AvailableLocales == nil { @@ -2424,11 +2424,11 @@ func (s *SamlSettings) SetDefaults() { } if s.SignatureAlgorithm == nil { - s.SignatureAlgorithm = NewString(SAML_SETTINGS_DEFAULT_SIGNATURE_ALGORITHM) + s.SignatureAlgorithm = NewString(SamlSettingsDefaultSignatureAlgorithm) } if s.CanonicalAlgorithm == nil { - s.CanonicalAlgorithm = NewString(SAML_SETTINGS_DEFAULT_CANONICAL_ALGORITHM) + s.CanonicalAlgorithm = NewString(SamlSettingsDefaultCanonicalAlgorithm) } if s.IdpUrl == nil { @@ -2476,45 +2476,45 @@ func (s *SamlSettings) SetDefaults() { } if s.LoginButtonText == nil || *s.LoginButtonText == "" { - s.LoginButtonText = NewString(USER_AUTH_SERVICE_SAML_TEXT) + s.LoginButtonText = NewString(UserAuthServiceSamlText) } if s.IdAttribute == nil { - s.IdAttribute = NewString(SAML_SETTINGS_DEFAULT_ID_ATTRIBUTE) + s.IdAttribute = NewString(SamlSettingsDefaultIdAttribute) } if s.GuestAttribute == nil { - s.GuestAttribute = NewString(SAML_SETTINGS_DEFAULT_GUEST_ATTRIBUTE) + s.GuestAttribute = NewString(SamlSettingsDefaultGuestAttribute) } if s.AdminAttribute == nil { - s.AdminAttribute = NewString(SAML_SETTINGS_DEFAULT_ADMIN_ATTRIBUTE) + s.AdminAttribute = NewString(SamlSettingsDefaultAdminAttribute) } if s.FirstNameAttribute == nil { - s.FirstNameAttribute = NewString(SAML_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE) + s.FirstNameAttribute = NewString(SamlSettingsDefaultFirstNameAttribute) } if s.LastNameAttribute == nil { - s.LastNameAttribute = NewString(SAML_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE) + s.LastNameAttribute = NewString(SamlSettingsDefaultLastNameAttribute) } if s.EmailAttribute == nil { - s.EmailAttribute = NewString(SAML_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE) + s.EmailAttribute = NewString(SamlSettingsDefaultEmailAttribute) } if s.UsernameAttribute == nil { - s.UsernameAttribute = NewString(SAML_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE) + s.UsernameAttribute = NewString(SamlSettingsDefaultUsernameAttribute) } if s.NicknameAttribute == nil { - s.NicknameAttribute = NewString(SAML_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE) + s.NicknameAttribute = NewString(SamlSettingsDefaultNicknameAttribute) } if s.PositionAttribute == nil { - s.PositionAttribute = NewString(SAML_SETTINGS_DEFAULT_POSITION_ATTRIBUTE) + s.PositionAttribute = NewString(SamlSettingsDefaultPositionAttribute) } if s.LocaleAttribute == nil { - s.LocaleAttribute = NewString(SAML_SETTINGS_DEFAULT_LOCALE_ATTRIBUTE) + s.LocaleAttribute = NewString(SamlSettingsDefaultLocaleAttribute) } if s.LoginButtonColor == nil { @@ -2539,15 +2539,15 @@ type NativeAppSettings struct { func (s *NativeAppSettings) SetDefaults() { if s.AppDownloadLink == nil { - s.AppDownloadLink = NewString(NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK) + s.AppDownloadLink = NewString(NativeappSettingsDefaultAppDownloadLink) } if s.AndroidAppDownloadLink == nil { - s.AndroidAppDownloadLink = NewString(NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK) + s.AndroidAppDownloadLink = NewString(NativeappSettingsDefaultAndroidAppDownloadLink) } if s.IosAppDownloadLink == nil { - s.IosAppDownloadLink = NewString(NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK) + s.IosAppDownloadLink = NewString(NativeappSettingsDefaultIosAppDownloadLink) } if s.AppCustomURLSchemes == nil { @@ -2581,15 +2581,15 @@ type ElasticsearchSettings struct { func (s *ElasticsearchSettings) SetDefaults() { if s.ConnectionUrl == nil { - s.ConnectionUrl = NewString(ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL) + s.ConnectionUrl = NewString(ElasticsearchSettingsDefaultConnectionUrl) } if s.Username == nil { - s.Username = NewString(ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME) + s.Username = NewString(ElasticsearchSettingsDefaultUsername) } if s.Password == nil { - s.Password = NewString(ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD) + s.Password = NewString(ElasticsearchSettingsDefaultPassword) } if s.EnableIndexing == nil { @@ -2609,51 +2609,51 @@ func (s *ElasticsearchSettings) SetDefaults() { } if s.PostIndexReplicas == nil { - s.PostIndexReplicas = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_POST_INDEX_REPLICAS) + s.PostIndexReplicas = NewInt(ElasticsearchSettingsDefaultPostIndexReplicas) } if s.PostIndexShards == nil { - s.PostIndexShards = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_POST_INDEX_SHARDS) + s.PostIndexShards = NewInt(ElasticsearchSettingsDefaultPostIndexShards) } if s.ChannelIndexReplicas == nil { - s.ChannelIndexReplicas = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_CHANNEL_INDEX_REPLICAS) + s.ChannelIndexReplicas = NewInt(ElasticsearchSettingsDefaultChannelIndexReplicas) } if s.ChannelIndexShards == nil { - s.ChannelIndexShards = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_CHANNEL_INDEX_SHARDS) + s.ChannelIndexShards = NewInt(ElasticsearchSettingsDefaultChannelIndexShards) } if s.UserIndexReplicas == nil { - s.UserIndexReplicas = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_USER_INDEX_REPLICAS) + s.UserIndexReplicas = NewInt(ElasticsearchSettingsDefaultUserIndexReplicas) } if s.UserIndexShards == nil { - s.UserIndexShards = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_USER_INDEX_SHARDS) + s.UserIndexShards = NewInt(ElasticsearchSettingsDefaultUserIndexShards) } if s.AggregatePostsAfterDays == nil { - s.AggregatePostsAfterDays = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_AGGREGATE_POSTS_AFTER_DAYS) + s.AggregatePostsAfterDays = NewInt(ElasticsearchSettingsDefaultAggregatePostsAfterDays) } if s.PostsAggregatorJobStartTime == nil { - s.PostsAggregatorJobStartTime = NewString(ELASTICSEARCH_SETTINGS_DEFAULT_POSTS_AGGREGATOR_JOB_START_TIME) + s.PostsAggregatorJobStartTime = NewString(ElasticsearchSettingsDefaultPostsAggregatorJobStartTime) } if s.IndexPrefix == nil { - s.IndexPrefix = NewString(ELASTICSEARCH_SETTINGS_DEFAULT_INDEX_PREFIX) + s.IndexPrefix = NewString(ElasticsearchSettingsDefaultIndexPrefix) } if s.LiveIndexingBatchSize == nil { - s.LiveIndexingBatchSize = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_LIVE_INDEXING_BATCH_SIZE) + s.LiveIndexingBatchSize = NewInt(ElasticsearchSettingsDefaultLiveIndexingBatchSize) } if s.BulkIndexingTimeWindowSeconds == nil { - s.BulkIndexingTimeWindowSeconds = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_BULK_INDEXING_TIME_WINDOW_SECONDS) + s.BulkIndexingTimeWindowSeconds = NewInt(ElasticsearchSettingsDefaultBulkIndexingTimeWindowSeconds) } if s.RequestTimeoutSeconds == nil { - s.RequestTimeoutSeconds = NewInt(ELASTICSEARCH_SETTINGS_DEFAULT_REQUEST_TIMEOUT_SECONDS) + s.RequestTimeoutSeconds = NewInt(ElasticsearchSettingsDefaultRequestTimeoutSeconds) } if s.SkipTLSVerification == nil { @@ -2675,7 +2675,7 @@ type BleveSettings struct { func (bs *BleveSettings) SetDefaults() { if bs.IndexDir == nil { - bs.IndexDir = NewString(BLEVE_SETTINGS_DEFAULT_INDEX_DIR) + bs.IndexDir = NewString(BleveSettingsDefaultIndexDir) } if bs.EnableIndexing == nil { @@ -2691,7 +2691,7 @@ func (bs *BleveSettings) SetDefaults() { } if bs.BulkIndexingTimeWindowSeconds == nil { - bs.BulkIndexingTimeWindowSeconds = NewInt(BLEVE_SETTINGS_DEFAULT_BULK_INDEXING_TIME_WINDOW_SECONDS) + bs.BulkIndexingTimeWindowSeconds = NewInt(BleveSettingsDefaultBulkIndexingTimeWindowSeconds) } } @@ -2714,19 +2714,19 @@ func (s *DataRetentionSettings) SetDefaults() { } if s.MessageRetentionDays == nil { - s.MessageRetentionDays = NewInt(DATA_RETENTION_SETTINGS_DEFAULT_MESSAGE_RETENTION_DAYS) + s.MessageRetentionDays = NewInt(DataRetentionSettingsDefaultMessageRetentionDays) } if s.FileRetentionDays == nil { - s.FileRetentionDays = NewInt(DATA_RETENTION_SETTINGS_DEFAULT_FILE_RETENTION_DAYS) + s.FileRetentionDays = NewInt(DataRetentionSettingsDefaultFileRetentionDays) } if s.DeletionJobStartTime == nil { - s.DeletionJobStartTime = NewString(DATA_RETENTION_SETTINGS_DEFAULT_DELETION_JOB_START_TIME) + s.DeletionJobStartTime = NewString(DataRetentionSettingsDefaultDeletionJobStartTime) } if s.BatchSize == nil { - s.BatchSize = NewInt(DATA_RETENTION_SETTINGS_DEFAULT_BATCH_SIZE) + s.BatchSize = NewInt(DataRetentionSettingsDefaultBatchSize) } } @@ -2752,10 +2752,10 @@ type CloudSettings struct { func (s *CloudSettings) SetDefaults() { if s.CWSUrl == nil { - s.CWSUrl = NewString(CLOUD_SETTINGS_DEFAULT_CWS_URL) + s.CWSUrl = NewString(CloudSettingsDefaultCwsUrl) } if s.CWSAPIUrl == nil { - s.CWSAPIUrl = NewString(CLOUD_SETTINGS_DEFAULT_CWS_API_URL) + s.CWSAPIUrl = NewString(CloudSettingsDefaultCwsApiUrl) } } @@ -2799,11 +2799,11 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { } if s.Directory == nil || *s.Directory == "" { - s.Directory = NewString(PLUGIN_SETTINGS_DEFAULT_DIRECTORY) + s.Directory = NewString(PluginSettingsDefaultDirectory) } if s.ClientDirectory == nil || *s.ClientDirectory == "" { - s.ClientDirectory = NewString(PLUGIN_SETTINGS_DEFAULT_CLIENT_DIRECTORY) + s.ClientDirectory = NewString(PluginSettingsDefaultClientDirectory) } if s.Plugins == nil { @@ -2830,7 +2830,7 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { } if s.EnableMarketplace == nil { - s.EnableMarketplace = NewBool(PLUGIN_SETTINGS_DEFAULT_ENABLE_MARKETPLACE) + s.EnableMarketplace = NewBool(PluginSettingsDefaultEnableMarketplace) } if s.EnableRemoteMarketplace == nil { @@ -2841,8 +2841,8 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) { s.AutomaticPrepackagedPlugins = NewBool(true) } - if s.MarketplaceUrl == nil || *s.MarketplaceUrl == "" || *s.MarketplaceUrl == PLUGIN_SETTINGS_OLD_MARKETPLACE_URL { - s.MarketplaceUrl = NewString(PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL) + if s.MarketplaceUrl == nil || *s.MarketplaceUrl == "" || *s.MarketplaceUrl == PluginSettingsOldMarketplaceUrl { + s.MarketplaceUrl = NewString(PluginSettingsDefaultMarketplaceUrl) } if s.RequirePluginSignature == nil { @@ -2868,7 +2868,7 @@ type GlobalRelayMessageExportSettings struct { func (s *GlobalRelayMessageExportSettings) SetDefaults() { if s.CustomerType == nil { - s.CustomerType = NewString(GLOBALRELAY_CUSTOMER_TYPE_A9) + s.CustomerType = NewString(GlobalrelayCustomerTypeA9) } if s.SmtpUsername == nil { s.SmtpUsername = NewString("") @@ -2906,7 +2906,7 @@ func (s *MessageExportSettings) SetDefaults() { } if s.ExportFormat == nil { - s.ExportFormat = NewString(COMPLIANCE_EXPORT_TYPE_ACTIANCE) + s.ExportFormat = NewString(ComplianceExportTypeActiance) } if s.DailyRunTime == nil { @@ -2986,7 +2986,7 @@ func (s *ImageProxySettings) SetDefaults(ss ServiceSettings) { if s.ImageProxyType == nil { if ss.DEPRECATED_DO_NOT_USE_ImageProxyType == nil || *ss.DEPRECATED_DO_NOT_USE_ImageProxyType == "" { - s.ImageProxyType = NewString(IMAGE_PROXY_TYPE_LOCAL) + s.ImageProxyType = NewString(ImageProxyTypeLocal) } else { s.ImageProxyType = ss.DEPRECATED_DO_NOT_USE_ImageProxyType } @@ -3032,11 +3032,11 @@ func (s *ImportSettings) isValid() *AppError { // SetDefaults applies the default settings to the struct. func (s *ImportSettings) SetDefaults() { if s.Directory == nil || *s.Directory == "" { - s.Directory = NewString(IMPORT_SETTINGS_DEFAULT_DIRECTORY) + s.Directory = NewString(ImportSettingsDefaultDirectory) } if s.RetentionDays == nil { - s.RetentionDays = NewInt(IMPORT_SETTINGS_DEFAULT_RETENTION_DAYS) + s.RetentionDays = NewInt(ImportSettingsDefaultRetentionDays) } } @@ -3063,11 +3063,11 @@ func (s *ExportSettings) isValid() *AppError { // SetDefaults applies the default settings to the struct. func (s *ExportSettings) SetDefaults() { if s.Directory == nil || *s.Directory == "" { - s.Directory = NewString(EXPORT_SETTINGS_DEFAULT_DIRECTORY) + s.Directory = NewString(ExportSettingsDefaultDirectory) } if s.RetentionDays == nil { - s.RetentionDays = NewInt(EXPORT_SETTINGS_DEFAULT_RETENTION_DAYS) + s.RetentionDays = NewInt(ExportSettingsDefaultRetentionDays) } } @@ -3077,42 +3077,41 @@ const ConfigAccessTagType = "access" const ConfigAccessTagWriteRestrictable = "write_restrictable" const ConfigAccessTagCloudRestrictable = "cloud_restrictable" -// Allows read access if any PERMISSION_SYSCONSOLE_READ_* is allowed +// Allows read access if any PermissionSysconsoleRead* is allowed const ConfigAccessTagAnySysConsoleRead = "*_read" // Config fields support the 'access' tag with the following values corresponding to the suffix of the associated -// PERMISSION_SYSCONSOLE_*_* permission Id: 'about', 'reporting', 'user_management_users', +// PermissionSysconsole* permission Id: 'about', 'reporting', 'user_management_users', // 'user_management_groups', 'user_management_teams', 'user_management_channels', // 'user_management_permissions', 'environment_web_server', 'environment_database', 'environment_elasticsearch', // 'environment_file_storage', 'environment_image_proxy', 'environment_smtp', 'environment_push_notification_server', // 'environment_high_availability', 'environment_rate_limiting', 'environment_logging', 'environment_session_lengths', // 'environment_performance_monitoring', 'environment_developer', 'site', 'authentication', 'plugins', // 'integrations', 'compliance', 'plugins', and 'experimental'. They grant read and/or write access to the config field -// to roles without PERMISSION_MANAGE_SYSTEM. +// to roles without PermissionManageSystem. // -// The 'access' tag '*_read' checks for any SYSCONSOLE read permission and grants access if any read permission is allowed. +// The 'access' tag '*_read' checks for any Sysconsole read permission and grants access if any read permission is allowed. // -// By default config values can be written with PERMISSION_MANAGE_SYSTEM, but if ExperimentalSettings.RestrictSystemAdmin is true -// and the access tag contains the value 'write_restrictable', then even PERMISSION_MANAGE_SYSTEM does not grant write access. +// By default config values can be written with PermissionManageSystem, but if ExperimentalSettings.RestrictSystemAdmin is true +// and the access tag contains the value 'write_restrictable', then even PermissionManageSystem, does not grant write access. // -// PERMISSION_MANAGE_SYSTEM always grants read access. +// PermissionManageSystem always grants read access. // // Config values with the access tag 'cloud_restrictable' mean that are marked to be filtered when it's used in a cloud licensed // environment with ExperimentalSettings.RestrictedSystemAdmin set to true. // // Example: // type HairSettings struct { -// // Colour is writeable with either PERMISSION_SYSCONSOLE_WRITE_REPORTING or PERMISSION_SYSCONSOLE_WRITE_USER_MANAGEMENT_GROUPS. -// // It is readable by PERMISSION_SYSCONSOLE_READ_REPORTING and PERMISSION_SYSCONSOLE_READ_USER_MANAGEMENT_GROUPS permissions. -// // PERMISSION_MANAGE_SYSTEM grants read and write access. +// // Colour is writeable with either PermissionSysconsoleWriteReporting or PermissionSysconsoleWriteUserManagementGroups. +// // It is readable by PermissionSysconsoleReadReporting and PermissionSysconsoleReadUserManagementGroups permissions. +// // PermissionManageSystem grants read and write access. // Colour string `access:"reporting,user_management_groups"` // -// -// // Length is only readable and writable via PERMISSION_MANAGE_SYSTEM. +// // Length is only readable and writable via PermissionManageSystem. // Length string // -// // Product is only writeable by PERMISSION_MANAGE_SYSTEM if ExperimentalSettings.RestrictSystemAdmin is false. -// // PERMISSION_MANAGE_SYSTEM can always read the value. +// // Product is only writeable by PermissionManageSystem if ExperimentalSettings.RestrictSystemAdmin is false. +// // PermissionManageSystem can always read the value. // Product bool `access:write_restrictable` // } type Config struct { @@ -3186,13 +3185,13 @@ func (o *Config) ToJsonFiltered(tagType, tagValue string) string { func (o *Config) GetSSOService(service string) *SSOSettings { switch service { - case SERVICE_GITLAB: + case ServiceGitlab: return &o.GitLabSettings - case SERVICE_GOOGLE: + case ServiceGoogle: return &o.GoogleSettings - case SERVICE_OFFICE365: + case ServiceOffice365: return o.Office365Settings.SSOSettings() - case SERVICE_OPENID: + case ServiceOpenid: return &o.OpenIdSettings } @@ -3217,10 +3216,10 @@ func (o *Config) SetDefaults() { o.SamlSettings.SetDefaults() if o.TeamSettings.TeammateNameDisplay == nil { - o.TeamSettings.TeammateNameDisplay = NewString(SHOW_USERNAME) + o.TeamSettings.TeammateNameDisplay = NewString(ShowUsername) if *o.SamlSettings.Enable || *o.LdapSettings.Enable { - *o.TeamSettings.TeammateNameDisplay = SHOW_FULLNAME + *o.TeamSettings.TeammateNameDisplay = ShowFullName } } @@ -3231,8 +3230,8 @@ func (o *Config) SetDefaults() { o.Office365Settings.setDefaults() o.Office365Settings.setDefaults() o.GitLabSettings.setDefaults("", "", "", "", "") - o.GoogleSettings.setDefaults(GOOGLE_SETTINGS_DEFAULT_SCOPE, GOOGLE_SETTINGS_DEFAULT_AUTH_ENDPOINT, GOOGLE_SETTINGS_DEFAULT_TOKEN_ENDPOINT, GOOGLE_SETTINGS_DEFAULT_USER_API_ENDPOINT, "") - o.OpenIdSettings.setDefaults(OPENID_SETTINGS_DEFAULT_SCOPE, "", "", "", "#145DBF") + o.GoogleSettings.setDefaults(GoogleSettingsDefaultScope, GoogleSettingsDefaultAuthEndpoint, GoogleSettingsDefaultTokenEndpoint, GoogleSettingsDefaultUserApiEndpoint, "") + o.OpenIdSettings.setDefaults(OpenidSettingsDefaultScope, "", "", "", "#145DBF") o.ServiceSettings.SetDefaults(isUpdate) o.PasswordSettings.SetDefaults() o.TeamSettings.SetDefaults() @@ -3305,8 +3304,8 @@ func (o *Config) IsValid() *AppError { return err } - if *o.PasswordSettings.MinimumLength < PASSWORD_MINIMUM_LENGTH || *o.PasswordSettings.MinimumLength > PASSWORD_MAXIMUM_LENGTH { - return NewAppError("Config.IsValid", "model.config.is_valid.password_length.app_error", map[string]interface{}{"MinLength": PASSWORD_MINIMUM_LENGTH, "MaxLength": PASSWORD_MAXIMUM_LENGTH}, "", http.StatusBadRequest) + if *o.PasswordSettings.MinimumLength < PasswordMinimumLength || *o.PasswordSettings.MinimumLength > PasswordMaximumLength { + return NewAppError("Config.IsValid", "model.config.is_valid.password_length.app_error", map[string]interface{}{"MinLength": PasswordMinimumLength, "MaxLength": PasswordMaximumLength}, "", http.StatusBadRequest) } if err := o.RateLimitSettings.isValid(); err != nil { @@ -3364,16 +3363,16 @@ func (s *TeamSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.max_notify_per_channel.app_error", nil, "", http.StatusBadRequest) } - if !(*s.RestrictDirectMessage == DIRECT_MESSAGE_ANY || *s.RestrictDirectMessage == DIRECT_MESSAGE_TEAM) { + if !(*s.RestrictDirectMessage == DirectMessageAny || *s.RestrictDirectMessage == DirectMessageTeam) { return NewAppError("Config.IsValid", "model.config.is_valid.restrict_direct_message.app_error", nil, "", http.StatusBadRequest) } - if !(*s.TeammateNameDisplay == SHOW_FULLNAME || *s.TeammateNameDisplay == SHOW_NICKNAME_FULLNAME || *s.TeammateNameDisplay == SHOW_USERNAME) { + if !(*s.TeammateNameDisplay == ShowFullName || *s.TeammateNameDisplay == ShowNicknameFullName || *s.TeammateNameDisplay == ShowUsername) { return NewAppError("Config.IsValid", "model.config.is_valid.teammate_name_display.app_error", nil, "", http.StatusBadRequest) } - if len(*s.SiteName) > SITENAME_MAX_LENGTH { - return NewAppError("Config.IsValid", "model.config.is_valid.sitename_length.app_error", map[string]interface{}{"MaxLength": SITENAME_MAX_LENGTH}, "", http.StatusBadRequest) + if len(*s.SiteName) > SitenameMaxLength { + return NewAppError("Config.IsValid", "model.config.is_valid.sitename_length.app_error", map[string]interface{}{"MaxLength": SitenameMaxLength}, "", http.StatusBadRequest) } return nil @@ -3384,7 +3383,7 @@ func (s *SqlSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.encrypt_sql.app_error", nil, "", http.StatusBadRequest) } - if !(*s.DriverName == DATABASE_DRIVER_MYSQL || *s.DriverName == DATABASE_DRIVER_POSTGRES) { + if !(*s.DriverName == DatabaseDriverMysql || *s.DriverName == DatabaseDriverPostgres) { return NewAppError("Config.IsValid", "model.config.is_valid.sql_driver.app_error", nil, "", http.StatusBadRequest) } @@ -3420,7 +3419,7 @@ func (s *FileSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.max_file_size.app_error", nil, "", http.StatusBadRequest) } - if !(*s.DriverName == IMAGE_DRIVER_LOCAL || *s.DriverName == IMAGE_DRIVER_S3) { + if !(*s.DriverName == ImageDriverLocal || *s.DriverName == ImageDriverS3) { return NewAppError("Config.IsValid", "model.config.is_valid.file_driver.app_error", nil, "", http.StatusBadRequest) } @@ -3436,7 +3435,7 @@ func (s *FileSettings) isValid() *AppError { } func (s *EmailSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS || *s.ConnectionSecurity == CONN_SECURITY_STARTTLS || *s.ConnectionSecurity == CONN_SECURITY_PLAIN) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls || *s.ConnectionSecurity == ConnSecurityStarttls || *s.ConnectionSecurity == ConnSecurityPlain) { return NewAppError("Config.IsValid", "model.config.is_valid.email_security.app_error", nil, "", http.StatusBadRequest) } @@ -3448,7 +3447,7 @@ func (s *EmailSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.email_batching_interval.app_error", nil, "", http.StatusBadRequest) } - if !(*s.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_FULL || *s.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_GENERIC) { + if !(*s.EmailNotificationContentsType == EmailNotificationContentsFull || *s.EmailNotificationContentsType == EmailNotificationContentsGeneric) { return NewAppError("Config.IsValid", "model.config.is_valid.email_notification_contents_type.app_error", nil, "", http.StatusBadRequest) } @@ -3472,7 +3471,7 @@ func (s *RateLimitSettings) isValid() *AppError { } func (s *LdapSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS || *s.ConnectionSecurity == CONN_SECURITY_STARTTLS) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls || *s.ConnectionSecurity == ConnSecurityStarttls) { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_security.app_error", nil, "", http.StatusBadRequest) } @@ -3577,10 +3576,10 @@ func (s *SamlSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) } - if !(*s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA1 || *s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256 || *s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA512) { + if !(*s.SignatureAlgorithm == SamlSettingsSignatureAlgorithmSha1 || *s.SignatureAlgorithm == SamlSettingsSignatureAlgorithmSha256 || *s.SignatureAlgorithm == SamlSettingsSignatureAlgorithmSha512) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_signature_algorithm.app_error", nil, "", http.StatusBadRequest) } - if !(*s.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N || *s.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11) { + if !(*s.CanonicalAlgorithm == SamlSettingsCanonicalAlgorithmC14n || *s.CanonicalAlgorithm == SamlSettingsCanonicalAlgorithmC14n11) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_canonical_algorithm.app_error", nil, "", http.StatusBadRequest) } @@ -3607,11 +3606,11 @@ func (s *SamlSettings) isValid() *AppError { } func (s *ServiceSettings) isValid() *AppError { - if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS) { + if !(*s.ConnectionSecurity == ConnSecurityNone || *s.ConnectionSecurity == ConnSecurityTls) { return NewAppError("Config.IsValid", "model.config.is_valid.webserver_security.app_error", nil, "", http.StatusBadRequest) } - if *s.ConnectionSecurity == CONN_SECURITY_TLS && !*s.UseLetsEncrypt { + if *s.ConnectionSecurity == ConnSecurityTls && !*s.UseLetsEncrypt { appErr := NewAppError("Config.IsValid", "model.config.is_valid.tls_cert_file_missing.app_error", nil, "", http.StatusBadRequest) if *s.TLSCertFile == "" { @@ -3677,15 +3676,15 @@ func (s *ServiceSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.listen_address.app_error", nil, "", http.StatusBadRequest) } - if *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DISABLED && - *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_ON && - *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_OFF { + if *s.ExperimentalGroupUnreadChannels != GroupUnreadChannelsDisabled && + *s.ExperimentalGroupUnreadChannels != GroupUnreadChannelsDefaultOn && + *s.ExperimentalGroupUnreadChannels != GroupUnreadChannelsDefaultOff { return NewAppError("Config.IsValid", "model.config.is_valid.group_unread_channels.app_error", nil, "", http.StatusBadRequest) } - if *s.CollapsedThreads != COLLAPSED_THREADS_DISABLED && - *s.CollapsedThreads != COLLAPSED_THREADS_DEFAULT_ON && - *s.CollapsedThreads != COLLAPSED_THREADS_DEFAULT_OFF { + if *s.CollapsedThreads != CollapsedThreadsDisabled && + *s.CollapsedThreads != CollapsedThreadsDefaultOn && + *s.CollapsedThreads != CollapsedThreadsDefaultOff { return NewAppError("Config.IsValid", "model.config.is_valid.collapsed_threads.app_error", nil, "", http.StatusBadRequest) } @@ -3789,14 +3788,14 @@ func (s *MessageExportSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.daily_runtime.app_error", nil, err.Error(), http.StatusBadRequest) } else if s.BatchSize == nil || *s.BatchSize < 0 { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.batch_size.app_error", nil, "", http.StatusBadRequest) - } else if s.ExportFormat == nil || (*s.ExportFormat != COMPLIANCE_EXPORT_TYPE_ACTIANCE && *s.ExportFormat != COMPLIANCE_EXPORT_TYPE_GLOBALRELAY && *s.ExportFormat != COMPLIANCE_EXPORT_TYPE_CSV) { + } else if s.ExportFormat == nil || (*s.ExportFormat != ComplianceExportTypeActiance && *s.ExportFormat != ComplianceExportTypeGlobalrelay && *s.ExportFormat != ComplianceExportTypeCsv) { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.export_type.app_error", nil, "", http.StatusBadRequest) } - if *s.ExportFormat == COMPLIANCE_EXPORT_TYPE_GLOBALRELAY { + if *s.ExportFormat == ComplianceExportTypeGlobalrelay { if s.GlobalRelaySettings == nil { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.config_missing.app_error", nil, "", http.StatusBadRequest) - } else if s.GlobalRelaySettings.CustomerType == nil || (*s.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A9 && *s.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A10) { + } else if s.GlobalRelaySettings.CustomerType == nil || (*s.GlobalRelaySettings.CustomerType != GlobalrelayCustomerTypeA9 && *s.GlobalRelaySettings.CustomerType != GlobalrelayCustomerTypeA10) { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.customer_type.app_error", nil, "", http.StatusBadRequest) } else if s.GlobalRelaySettings.EmailAddress == nil || !strings.Contains(*s.GlobalRelaySettings.EmailAddress, "@") { // validating email addresses is hard - just make sure it contains an '@' sign @@ -3835,9 +3834,9 @@ func (s *DisplaySettings) isValid() *AppError { func (s *ImageProxySettings) isValid() *AppError { if *s.Enable { switch *s.ImageProxyType { - case IMAGE_PROXY_TYPE_LOCAL: + case ImageProxyTypeLocal: // No other settings to validate - case IMAGE_PROXY_TYPE_ATMOS_CAMO: + case ImageProxyTypeAtmosCamo: if *s.RemoteImageProxyURL == "" { return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_url.app_error", nil, "", http.StatusBadRequest) } @@ -3863,57 +3862,57 @@ func (o *Config) GetSanitizeOptions() map[string]bool { func (o *Config) Sanitize() { if o.LdapSettings.BindPassword != nil && *o.LdapSettings.BindPassword != "" { - *o.LdapSettings.BindPassword = FAKE_SETTING + *o.LdapSettings.BindPassword = FakeSetting } - *o.FileSettings.PublicLinkSalt = FAKE_SETTING + *o.FileSettings.PublicLinkSalt = FakeSetting if *o.FileSettings.AmazonS3SecretAccessKey != "" { - *o.FileSettings.AmazonS3SecretAccessKey = FAKE_SETTING + *o.FileSettings.AmazonS3SecretAccessKey = FakeSetting } if o.EmailSettings.SMTPPassword != nil && *o.EmailSettings.SMTPPassword != "" { - *o.EmailSettings.SMTPPassword = FAKE_SETTING + *o.EmailSettings.SMTPPassword = FakeSetting } if *o.GitLabSettings.Secret != "" { - *o.GitLabSettings.Secret = FAKE_SETTING + *o.GitLabSettings.Secret = FakeSetting } if o.GoogleSettings.Secret != nil && *o.GoogleSettings.Secret != "" { - *o.GoogleSettings.Secret = FAKE_SETTING + *o.GoogleSettings.Secret = FakeSetting } if o.Office365Settings.Secret != nil && *o.Office365Settings.Secret != "" { - *o.Office365Settings.Secret = FAKE_SETTING + *o.Office365Settings.Secret = FakeSetting } if o.OpenIdSettings.Secret != nil && *o.OpenIdSettings.Secret != "" { - *o.OpenIdSettings.Secret = FAKE_SETTING + *o.OpenIdSettings.Secret = FakeSetting } - *o.SqlSettings.DataSource = FAKE_SETTING - *o.SqlSettings.AtRestEncryptKey = FAKE_SETTING + *o.SqlSettings.DataSource = FakeSetting + *o.SqlSettings.AtRestEncryptKey = FakeSetting - *o.ElasticsearchSettings.Password = FAKE_SETTING + *o.ElasticsearchSettings.Password = FakeSetting for i := range o.SqlSettings.DataSourceReplicas { - o.SqlSettings.DataSourceReplicas[i] = FAKE_SETTING + o.SqlSettings.DataSourceReplicas[i] = FakeSetting } for i := range o.SqlSettings.DataSourceSearchReplicas { - o.SqlSettings.DataSourceSearchReplicas[i] = FAKE_SETTING + o.SqlSettings.DataSourceSearchReplicas[i] = FakeSetting } if o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != nil && *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword != "" { - *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FAKE_SETTING + *o.MessageExportSettings.GlobalRelaySettings.SmtpPassword = FakeSetting } if o.ServiceSettings.GfycatApiSecret != nil && *o.ServiceSettings.GfycatApiSecret != "" { - *o.ServiceSettings.GfycatApiSecret = FAKE_SETTING + *o.ServiceSettings.GfycatApiSecret = FakeSetting } - *o.ServiceSettings.SplitKey = FAKE_SETTING + *o.ServiceSettings.SplitKey = FakeSetting } // structToMapFilteredByTag converts a struct into a map removing those fields that has the tag passed diff --git a/model/config_test.go b/model/config_test.go index d2bee1bb9f..5835f92ce9 100644 --- a/model/config_test.go +++ b/model/config_test.go @@ -64,7 +64,7 @@ func TestConfigEmptySiteName(t *testing.T) { } c1.SetDefaults() - require.Equal(t, *c1.TeamSettings.SiteName, TEAM_SETTINGS_DEFAULT_SITE_NAME) + require.Equal(t, *c1.TeamSettings.SiteName, TeamSettingsDefaultSiteName) } func TestConfigEnableDeveloper(t *testing.T) { @@ -73,7 +73,7 @@ func TestConfigEnableDeveloper(t *testing.T) { EnableDeveloper *bool ExpectedSiteURL string }{ - {"enable developer is true", NewBool(true), SERVICE_SETTINGS_DEFAULT_SITE_URL}, + {"enable developer is true", NewBool(true), ServiceSettingsDefaultSiteUrl}, {"enable developer is false", NewBool(false), ""}, {"enable developer is nil", nil, ""}, } @@ -103,7 +103,7 @@ func TestConfigDefaultEmailNotificationContentsType(t *testing.T) { c1 := Config{} c1.SetDefaults() - require.Equal(t, *c1.EmailSettings.EmailNotificationContentsType, EMAIL_NOTIFICATION_CONTENTS_FULL) + require.Equal(t, *c1.EmailSettings.EmailNotificationContentsType, EmailNotificationContentsFull) } func TestConfigDefaultFileSettingsS3SSE(t *testing.T) { @@ -117,8 +117,8 @@ func TestConfigDefaultSignatureAlgorithm(t *testing.T) { c1 := Config{} c1.SetDefaults() - require.Equal(t, *c1.SamlSettings.SignatureAlgorithm, SAML_SETTINGS_DEFAULT_SIGNATURE_ALGORITHM) - require.Equal(t, *c1.SamlSettings.CanonicalAlgorithm, SAML_SETTINGS_DEFAULT_CANONICAL_ALGORITHM) + require.Equal(t, *c1.SamlSettings.SignatureAlgorithm, SamlSettingsDefaultSignatureAlgorithm) + require.Equal(t, *c1.SamlSettings.CanonicalAlgorithm, SamlSettingsDefaultCanonicalAlgorithm) } func TestConfigOverwriteSignatureAlgorithm(t *testing.T) { @@ -237,7 +237,7 @@ func TestConfigDefaultServiceSettingsExperimentalGroupUnreadChannels(t *testing. c1 := Config{} c1.SetDefaults() - require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DISABLED) + require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GroupUnreadChannelsDisabled) // This setting was briefly a boolean, so ensure that those values still work as expected c1 = Config{ @@ -247,7 +247,7 @@ func TestConfigDefaultServiceSettingsExperimentalGroupUnreadChannels(t *testing. } c1.SetDefaults() - require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DEFAULT_ON) + require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GroupUnreadChannelsDefaultOn) c1 = Config{ ServiceSettings: ServiceSettings{ @@ -256,7 +256,7 @@ func TestConfigDefaultServiceSettingsExperimentalGroupUnreadChannels(t *testing. } c1.SetDefaults() - require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GROUP_UNREAD_CHANNELS_DISABLED) + require.Equal(t, *c1.ServiceSettings.ExperimentalGroupUnreadChannels, GroupUnreadChannelsDisabled) } func TestConfigDefaultNPSPluginState(t *testing.T) { @@ -463,7 +463,7 @@ func TestMessageExportSettingsIsValidExportFormatInvalid(t *testing.T) { func TestMessageExportSettingsIsValidGlobalRelayEmailAddressInvalid(t *testing.T) { mes := &MessageExportSettings{ EnableExport: NewBool(true), - ExportFormat: NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY), + ExportFormat: NewString(ComplianceExportTypeGlobalrelay), ExportFromTimestamp: NewInt64(0), DailyRunTime: NewString("15:04"), BatchSize: NewInt(100), @@ -476,7 +476,7 @@ func TestMessageExportSettingsIsValidGlobalRelayEmailAddressInvalid(t *testing.T func TestMessageExportSettingsIsValidActiance(t *testing.T) { mes := &MessageExportSettings{ EnableExport: NewBool(true), - ExportFormat: NewString(COMPLIANCE_EXPORT_TYPE_ACTIANCE), + ExportFormat: NewString(ComplianceExportTypeActiance), ExportFromTimestamp: NewInt64(0), DailyRunTime: NewString("15:04"), BatchSize: NewInt(100), @@ -489,7 +489,7 @@ func TestMessageExportSettingsIsValidActiance(t *testing.T) { func TestMessageExportSettingsIsValidGlobalRelaySettingsMissing(t *testing.T) { mes := &MessageExportSettings{ EnableExport: NewBool(true), - ExportFormat: NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY), + ExportFormat: NewString(ComplianceExportTypeGlobalrelay), ExportFromTimestamp: NewInt64(0), DailyRunTime: NewString("15:04"), BatchSize: NewInt(100), @@ -502,7 +502,7 @@ func TestMessageExportSettingsIsValidGlobalRelaySettingsMissing(t *testing.T) { func TestMessageExportSettingsIsValidGlobalRelaySettingsInvalidCustomerType(t *testing.T) { mes := &MessageExportSettings{ EnableExport: NewBool(true), - ExportFormat: NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY), + ExportFormat: NewString(ComplianceExportTypeGlobalrelay), ExportFromTimestamp: NewInt64(0), DailyRunTime: NewString("15:04"), BatchSize: NewInt(100), @@ -528,7 +528,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { { "Invalid email address", &GlobalRelayMessageExportSettings{ - CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A9), + CustomerType: NewString(GlobalrelayCustomerTypeA9), EmailAddress: NewString("invalidEmailAddress"), SmtpUsername: NewString("SomeUsername"), SmtpPassword: NewString("SomePassword"), @@ -538,7 +538,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { { "Missing smtp username", &GlobalRelayMessageExportSettings{ - CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10), + CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), SmtpPassword: NewString("SomePassword"), }, @@ -547,7 +547,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { { "Invalid smtp username", &GlobalRelayMessageExportSettings{ - CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10), + CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), SmtpUsername: NewString(""), SmtpPassword: NewString("SomePassword"), @@ -557,7 +557,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { { "Invalid smtp password", &GlobalRelayMessageExportSettings{ - CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A10), + CustomerType: NewString(GlobalrelayCustomerTypeA10), EmailAddress: NewString("valid@mattermost.com"), SmtpUsername: NewString("SomeUsername"), SmtpPassword: NewString(""), @@ -567,7 +567,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { { "Valid data", &GlobalRelayMessageExportSettings{ - CustomerType: NewString(GLOBALRELAY_CUSTOMER_TYPE_A9), + CustomerType: NewString(GlobalrelayCustomerTypeA9), EmailAddress: NewString("valid@mattermost.com"), SmtpUsername: NewString("SomeUsername"), SmtpPassword: NewString("SomePassword"), @@ -580,7 +580,7 @@ func TestMessageExportSettingsGlobalRelaySettings(t *testing.T) { t.Run(tt.name, func(t *testing.T) { mes := &MessageExportSettings{ EnableExport: NewBool(true), - ExportFormat: NewString(COMPLIANCE_EXPORT_TYPE_GLOBALRELAY), + ExportFormat: NewString(ComplianceExportTypeGlobalrelay), ExportFromTimestamp: NewInt64(0), DailyRunTime: NewString("15:04"), BatchSize: NewInt(100), @@ -604,7 +604,7 @@ func TestMessageExportSetDefaults(t *testing.T) { require.Equal(t, "01:00", *mes.DailyRunTime) require.Equal(t, int64(0), *mes.ExportFromTimestamp) require.Equal(t, 10000, *mes.BatchSize) - require.Equal(t, COMPLIANCE_EXPORT_TYPE_ACTIANCE, *mes.ExportFormat) + require.Equal(t, ComplianceExportTypeActiance, *mes.ExportFormat) } func TestMessageExportSetDefaultsExportEnabledExportFromTimestampNil(t *testing.T) { @@ -815,7 +815,7 @@ func TestListenAddressIsValidated(t *testing.T) { func TestImageProxySettingsSetDefaults(t *testing.T) { ss := ServiceSettings{ - DEPRECATED_DO_NOT_USE_ImageProxyType: NewString(IMAGE_PROXY_TYPE_ATMOS_CAMO), + DEPRECATED_DO_NOT_USE_ImageProxyType: NewString(ImageProxyTypeAtmosCamo), DEPRECATED_DO_NOT_USE_ImageProxyURL: NewString("http://images.example.com"), DEPRECATED_DO_NOT_USE_ImageProxyOptions: NewString("1234abcd"), } @@ -825,7 +825,7 @@ func TestImageProxySettingsSetDefaults(t *testing.T) { ips.SetDefaults(ServiceSettings{}) assert.Equal(t, false, *ips.Enable) - assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType) + assert.Equal(t, ImageProxyTypeLocal, *ips.ImageProxyType) assert.Equal(t, "", *ips.RemoteImageProxyURL) assert.Equal(t, "", *ips.RemoteImageProxyOptions) }) @@ -846,14 +846,14 @@ func TestImageProxySettingsSetDefaults(t *testing.T) { ips := ImageProxySettings{ Enable: NewBool(false), - ImageProxyType: NewString(IMAGE_PROXY_TYPE_LOCAL), + ImageProxyType: NewString(ImageProxyTypeLocal), RemoteImageProxyURL: &url, RemoteImageProxyOptions: &options, } ips.SetDefaults(ss) assert.Equal(t, false, *ips.Enable) - assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType) + assert.Equal(t, ImageProxyTypeLocal, *ips.ImageProxyType) assert.Equal(t, url, *ips.RemoteImageProxyURL) assert.Equal(t, options, *ips.RemoteImageProxyOptions) }) @@ -898,7 +898,7 @@ func TestImageProxySettingsIsValid(t *testing.T) { { Name: "atmos/camo", Enable: true, - ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO, + ImageProxyType: ImageProxyTypeAtmosCamo, RemoteImageProxyURL: "someurl", RemoteImageProxyOptions: "someoptions", ExpectError: false, @@ -906,7 +906,7 @@ func TestImageProxySettingsIsValid(t *testing.T) { { Name: "atmos/camo, missing url", Enable: true, - ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO, + ImageProxyType: ImageProxyTypeAtmosCamo, RemoteImageProxyURL: "", RemoteImageProxyOptions: "garbage", ExpectError: true, @@ -914,7 +914,7 @@ func TestImageProxySettingsIsValid(t *testing.T) { { Name: "atmos/camo, missing options", Enable: true, - ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO, + ImageProxyType: ImageProxyTypeAtmosCamo, RemoteImageProxyURL: "someurl", RemoteImageProxyOptions: "", ExpectError: true, @@ -1303,17 +1303,17 @@ func TestConfigSanitize(t *testing.T) { c.Sanitize() - assert.Equal(t, FAKE_SETTING, *c.LdapSettings.BindPassword) - assert.Equal(t, FAKE_SETTING, *c.FileSettings.PublicLinkSalt) - assert.Equal(t, FAKE_SETTING, *c.FileSettings.AmazonS3SecretAccessKey) - assert.Equal(t, FAKE_SETTING, *c.EmailSettings.SMTPPassword) - assert.Equal(t, FAKE_SETTING, *c.GitLabSettings.Secret) - assert.Equal(t, FAKE_SETTING, *c.OpenIdSettings.Secret) - assert.Equal(t, FAKE_SETTING, *c.SqlSettings.DataSource) - assert.Equal(t, FAKE_SETTING, *c.SqlSettings.AtRestEncryptKey) - assert.Equal(t, FAKE_SETTING, *c.ElasticsearchSettings.Password) - assert.Equal(t, FAKE_SETTING, c.SqlSettings.DataSourceReplicas[0]) - assert.Equal(t, FAKE_SETTING, c.SqlSettings.DataSourceSearchReplicas[0]) + assert.Equal(t, FakeSetting, *c.LdapSettings.BindPassword) + assert.Equal(t, FakeSetting, *c.FileSettings.PublicLinkSalt) + assert.Equal(t, FakeSetting, *c.FileSettings.AmazonS3SecretAccessKey) + assert.Equal(t, FakeSetting, *c.EmailSettings.SMTPPassword) + assert.Equal(t, FakeSetting, *c.GitLabSettings.Secret) + assert.Equal(t, FakeSetting, *c.OpenIdSettings.Secret) + assert.Equal(t, FakeSetting, *c.SqlSettings.DataSource) + assert.Equal(t, FakeSetting, *c.SqlSettings.AtRestEncryptKey) + assert.Equal(t, FakeSetting, *c.ElasticsearchSettings.Password) + assert.Equal(t, FakeSetting, c.SqlSettings.DataSourceReplicas[0]) + assert.Equal(t, FakeSetting, c.SqlSettings.DataSourceSearchReplicas[0]) } func TestConfigFilteredByTag(t *testing.T) { @@ -1368,18 +1368,18 @@ func TestConfigMarketplaceDefaults(t *testing.T) { c.SetDefaults() require.True(t, *c.PluginSettings.EnableMarketplace) - require.Equal(t, PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL, *c.PluginSettings.MarketplaceUrl) + require.Equal(t, PluginSettingsDefaultMarketplaceUrl, *c.PluginSettings.MarketplaceUrl) }) t.Run("old marketplace url", func(t *testing.T) { c := Config{} c.SetDefaults() - *c.PluginSettings.MarketplaceUrl = PLUGIN_SETTINGS_OLD_MARKETPLACE_URL + *c.PluginSettings.MarketplaceUrl = PluginSettingsOldMarketplaceUrl c.SetDefaults() require.True(t, *c.PluginSettings.EnableMarketplace) - require.Equal(t, PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL, *c.PluginSettings.MarketplaceUrl) + require.Equal(t, PluginSettingsDefaultMarketplaceUrl, *c.PluginSettings.MarketplaceUrl) }) t.Run("custom marketplace url", func(t *testing.T) { diff --git a/model/emoji.go b/model/emoji.go index f990c670d6..3e30237366 100644 --- a/model/emoji.go +++ b/model/emoji.go @@ -12,11 +12,11 @@ import ( ) const ( - EMOJI_NAME_MAX_LENGTH = 64 - EMOJI_SORT_BY_NAME = "name" + EmojiNameMaxLength = 64 + EmojiSortByName = "name" ) -var EMOJI_PATTERN = regexp.MustCompile(`:[a-zA-Z0-9_+-]+:`) +var EmojiPattern = regexp.MustCompile(`:[a-zA-Z0-9_+-]+:`) var ReverseSystemEmojisMap = makeReverseEmojiMap() @@ -80,7 +80,7 @@ func (emoji *Emoji) IsValid() *AppError { } func IsValidEmojiName(name string) *AppError { - if name == "" || len(name) > EMOJI_NAME_MAX_LENGTH || !IsValidAlphaNumHyphenUnderscorePlus(name) || inSystemEmoji(name) { + if name == "" || len(name) > EmojiNameMaxLength || !IsValidAlphaNumHyphenUnderscorePlus(name) || inSystemEmoji(name) { return NewAppError("Emoji.IsValid", "model.emoji.name.app_error", nil, "", http.StatusBadRequest) } diff --git a/model/file_info.go b/model/file_info.go index 2bad90233a..0285b2f8f5 100644 --- a/model/file_info.go +++ b/model/file_info.go @@ -15,8 +15,8 @@ import ( ) const ( - FILEINFO_SORT_BY_CREATED = "CreateAt" - FILEINFO_SORT_BY_SIZE = "Size" + FileinfoSortByCreated = "CreateAt" + FileinfoSortBySize = "Size" ) // GetFileInfosOptions contains options for getting FileInfos diff --git a/model/file_info_list.go b/model/file_info_list.go index cd9694f511..fd87c3aa37 100644 --- a/model/file_info_list.go +++ b/model/file_info_list.go @@ -37,9 +37,9 @@ func (o *FileInfoList) ToJson() string { b, err := json.Marshal(o) if err != nil { return "" - } else { - return string(b) } + + return string(b) } func (o *FileInfoList) MakeNonNil() { diff --git a/model/gitlab.go b/model/gitlab.go index 0b069cd6bc..c6233f1312 100644 --- a/model/gitlab.go +++ b/model/gitlab.go @@ -4,5 +4,5 @@ package model const ( - USER_AUTH_SERVICE_GITLAB = "gitlab" + UserAuthServiceGitlab = "gitlab" ) diff --git a/model/gitlab/gitlab.go b/model/gitlab/gitlab.go index ac90a481a9..61d13fe03a 100644 --- a/model/gitlab/gitlab.go +++ b/model/gitlab/gitlab.go @@ -27,7 +27,7 @@ type GitLabUser struct { func init() { provider := &GitLabProvider{} - einterfaces.RegisterOauthProvider(model.USER_AUTH_SERVICE_GITLAB, provider) + einterfaces.RegisterOAuthProvider(model.UserAuthServiceGitlab, provider) } func userFromGitLabUser(glu *GitLabUser) *model.User { @@ -51,7 +51,7 @@ func userFromGitLabUser(glu *GitLabUser) *model.User { user.Email = strings.ToLower(user.Email) userId := glu.getAuthData() user.AuthData = &userId - user.AuthService = model.USER_AUTH_SERVICE_GITLAB + user.AuthService = model.UserAuthServiceGitlab return user } diff --git a/model/guest_invite.go b/model/guest_invite.go index ac803a5d36..826aa74d94 100644 --- a/model/guest_invite.go +++ b/model/guest_invite.go @@ -23,7 +23,7 @@ func (i *GuestsInvite) IsValid() *AppError { } for _, email := range i.Emails { - if len(email) > USER_EMAIL_MAX_LENGTH || email == "" || !IsValidEmail(email) { + if len(email) > UserEmailMaxLength || email == "" || !IsValidEmail(email) { return NewAppError("GuestsInvite.IsValid", "model.guest.is_valid.email.app_error", nil, "email="+email, http.StatusBadRequest) } } diff --git a/model/incoming_webhook.go b/model/incoming_webhook.go index f8fffe201e..e389bf5457 100644 --- a/model/incoming_webhook.go +++ b/model/incoming_webhook.go @@ -12,7 +12,7 @@ import ( ) const ( - DEFAULT_WEBHOOK_USERNAME = "webhook" + DefaultWebhookUsername = "webhook" ) type IncomingWebhook struct { diff --git a/model/integration_action.go b/model/integration_action.go index 7124a7e37b..375d29869b 100644 --- a/model/integration_action.go +++ b/model/integration_action.go @@ -22,9 +22,9 @@ import ( ) const ( - POST_ACTION_TYPE_BUTTON = "button" - POST_ACTION_TYPE_SELECT = "select" - INTERACTIVE_DIALOG_TRIGGER_TIMEOUT_MILLISECONDS = 3000 + PostActionTypeButton = "button" + PostActionTypeSelect = "select" + InteractiveDialogTriggerTimeoutMilliseconds = 3000 ) var PostActionRetainPropKeys = []string{"from_webhook", "override_username", "override_icon_url"} @@ -289,8 +289,8 @@ func DecodeAndVerifyTriggerId(triggerId string, s *ecdsa.PrivateKey) (string, st timestamp, _ := strconv.ParseInt(timestampStr, 10, 64) now := GetMillis() - if now-timestamp > INTERACTIVE_DIALOG_TRIGGER_TIMEOUT_MILLISECONDS { - return "", "", NewAppError("DecodeAndVerifyTriggerId", "interactive_message.decode_trigger_id.expired", map[string]interface{}{"Seconds": INTERACTIVE_DIALOG_TRIGGER_TIMEOUT_MILLISECONDS / 1000}, "", http.StatusBadRequest) + if now-timestamp > InteractiveDialogTriggerTimeoutMilliseconds { + return "", "", NewAppError("DecodeAndVerifyTriggerId", "interactive_message.decode_trigger_id.expired", map[string]interface{}{"Seconds": InteractiveDialogTriggerTimeoutMilliseconds / 1000}, "", http.StatusBadRequest) } signature, err := base64.StdEncoding.DecodeString(split[3]) diff --git a/model/job.go b/model/job.go index 78d5a4ff5a..e0e9103de0 100644 --- a/model/job.go +++ b/model/job.go @@ -11,50 +11,50 @@ import ( ) const ( - JOB_TYPE_DATA_RETENTION = "data_retention" - JOB_TYPE_MESSAGE_EXPORT = "message_export" - JOB_TYPE_ELASTICSEARCH_POST_INDEXING = "elasticsearch_post_indexing" - JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION = "elasticsearch_post_aggregation" - JOB_TYPE_BLEVE_POST_INDEXING = "bleve_post_indexing" - JOB_TYPE_LDAP_SYNC = "ldap_sync" - JOB_TYPE_MIGRATIONS = "migrations" - JOB_TYPE_PLUGINS = "plugins" - JOB_TYPE_EXPIRY_NOTIFY = "expiry_notify" - JOB_TYPE_PRODUCT_NOTICES = "product_notices" - JOB_TYPE_ACTIVE_USERS = "active_users" - JOB_TYPE_IMPORT_PROCESS = "import_process" - JOB_TYPE_IMPORT_DELETE = "import_delete" - JOB_TYPE_EXPORT_PROCESS = "export_process" - JOB_TYPE_EXPORT_DELETE = "export_delete" - JOB_TYPE_CLOUD = "cloud" - JOB_TYPE_RESEND_INVITATION_EMAIL = "resend_invitation_email" + JobTypeDataRetention = "data_retention" + JobTypeMessageExport = "message_export" + JobTypeElasticsearchPostIndexing = "elasticsearch_post_indexing" + JobTypeElasticsearchPostAggregation = "elasticsearch_post_aggregation" + JobTypeBlevePostIndexing = "bleve_post_indexing" + JobTypeLdapSync = "ldap_sync" + JobTypeMigrations = "migrations" + JobTypePlugins = "plugins" + JobTypeExpiryNotify = "expiry_notify" + JobTypeProductNotices = "product_notices" + JobTypeActiveUsers = "active_users" + JobTypeImportProcess = "import_process" + JobTypeImportDelete = "import_delete" + JobTypeExportProcess = "export_process" + JobTypeExportDelete = "export_delete" + JobTypeCloud = "cloud" + JobTypeResendInvitationEmail = "resend_invitation_email" - JOB_STATUS_PENDING = "pending" - JOB_STATUS_IN_PROGRESS = "in_progress" - JOB_STATUS_SUCCESS = "success" - JOB_STATUS_ERROR = "error" - JOB_STATUS_CANCEL_REQUESTED = "cancel_requested" - JOB_STATUS_CANCELED = "canceled" - JOB_STATUS_WARNING = "warning" + JobStatusPending = "pending" + JobStatusInProgress = "in_progress" + JobStatusSuccess = "success" + JobStatusError = "error" + JobStatusCancelRequested = "cancel_requested" + JobStatusCanceled = "canceled" + JobStatusWarning = "warning" ) -var ALL_JOB_TYPES = [...]string{ - JOB_TYPE_DATA_RETENTION, - JOB_TYPE_MESSAGE_EXPORT, - JOB_TYPE_ELASTICSEARCH_POST_INDEXING, - JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION, - JOB_TYPE_BLEVE_POST_INDEXING, - JOB_TYPE_LDAP_SYNC, - JOB_TYPE_MIGRATIONS, - JOB_TYPE_PLUGINS, - JOB_TYPE_EXPIRY_NOTIFY, - JOB_TYPE_PRODUCT_NOTICES, - JOB_TYPE_ACTIVE_USERS, - JOB_TYPE_IMPORT_PROCESS, - JOB_TYPE_IMPORT_DELETE, - JOB_TYPE_EXPORT_PROCESS, - JOB_TYPE_EXPORT_DELETE, - JOB_TYPE_CLOUD, +var AllJobTypes = [...]string{ + JobTypeDataRetention, + JobTypeMessageExport, + JobTypeElasticsearchPostIndexing, + JobTypeElasticsearchPostAggregation, + JobTypeBlevePostIndexing, + JobTypeLdapSync, + JobTypeMigrations, + JobTypePlugins, + JobTypeExpiryNotify, + JobTypeProductNotices, + JobTypeActiveUsers, + JobTypeImportProcess, + JobTypeImportDelete, + JobTypeExportProcess, + JobTypeExportDelete, + JobTypeCloud, } type Job struct { @@ -79,34 +79,34 @@ func (j *Job) IsValid() *AppError { } switch j.Type { - case JOB_TYPE_DATA_RETENTION: - case JOB_TYPE_ELASTICSEARCH_POST_INDEXING: - case JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION: - case JOB_TYPE_BLEVE_POST_INDEXING: - case JOB_TYPE_LDAP_SYNC: - case JOB_TYPE_MESSAGE_EXPORT: - case JOB_TYPE_MIGRATIONS: - case JOB_TYPE_PLUGINS: - case JOB_TYPE_PRODUCT_NOTICES: - case JOB_TYPE_EXPIRY_NOTIFY: - case JOB_TYPE_ACTIVE_USERS: - case JOB_TYPE_IMPORT_PROCESS: - case JOB_TYPE_IMPORT_DELETE: - case JOB_TYPE_EXPORT_PROCESS: - case JOB_TYPE_EXPORT_DELETE: - case JOB_TYPE_CLOUD: - case JOB_TYPE_RESEND_INVITATION_EMAIL: + case JobTypeDataRetention: + case JobTypeElasticsearchPostIndexing: + case JobTypeElasticsearchPostAggregation: + case JobTypeBlevePostIndexing: + case JobTypeLdapSync: + case JobTypeMessageExport: + case JobTypeMigrations: + case JobTypePlugins: + case JobTypeProductNotices: + case JobTypeExpiryNotify: + case JobTypeActiveUsers: + case JobTypeImportProcess: + case JobTypeImportDelete: + case JobTypeExportProcess: + case JobTypeExportDelete: + case JobTypeCloud: + case JobTypeResendInvitationEmail: default: return NewAppError("Job.IsValid", "model.job.is_valid.type.app_error", nil, "id="+j.Id, http.StatusBadRequest) } switch j.Status { - case JOB_STATUS_PENDING: - case JOB_STATUS_IN_PROGRESS: - case JOB_STATUS_SUCCESS: - case JOB_STATUS_ERROR: - case JOB_STATUS_CANCEL_REQUESTED: - case JOB_STATUS_CANCELED: + case JobStatusPending: + case JobStatusInProgress: + case JobStatusSuccess: + case JobStatusError: + case JobStatusCancelRequested: + case JobStatusCanceled: default: return NewAppError("Job.IsValid", "model.job.is_valid.status.app_error", nil, "id="+j.Id, http.StatusBadRequest) } diff --git a/model/ldap.go b/model/ldap.go index 1262dfb8f9..314e7222e6 100644 --- a/model/ldap.go +++ b/model/ldap.go @@ -4,7 +4,7 @@ package model const ( - USER_AUTH_SERVICE_LDAP = "ldap" - LDAP_PUBLIC_CERTIFICATE_NAME = "ldap-public.crt" - LDAP_PRIVATE_KEY_NAME = "ldap-private.key" + UserAuthServiceLdap = "ldap" + LdapPublicCertificateName = "ldap-public.crt" + LdapPrivateKeyName = "ldap-private.key" ) diff --git a/model/license.go b/model/license.go index ab9e481a2a..d424a6d39d 100644 --- a/model/license.go +++ b/model/license.go @@ -12,16 +12,14 @@ import ( ) const ( - EXPIRED_LICENSE_ERROR = "api.license.add_license.expired.app_error" - INVALID_LICENSE_ERROR = "api.license.add_license.invalid.app_error" - LICENSE_GRACE_PERIOD = 1000 * 60 * 60 * 24 * 10 //10 days - LICENSE_RENEWAL_LINK = "https://mattermost.com/renew/" + ExpiredLicenseError = "api.license.add_license.expired.app_error" + InvalidLicenseError = "api.license.add_license.invalid.app_error" + LicenseGracePeriod = 1000 * 60 * 60 * 24 * 10 //10 days + LicenseRenewalLink = "https://mattermost.com/renew/" ) const ( - SIXTY_DAYS = 60 - FIFTY_EIGHT = 58 - LICENSE_UP_FOR_RENEWAL_EMAIL_SENT = "LicenseUpForRenewalEmailSent" + LicenseUpForRenewalEmailSent = "LicenseUpForRenewalEmailSent" ) var ( @@ -269,12 +267,12 @@ func (l *License) IsExpired() bool { func (l *License) IsPastGracePeriod() bool { timeDiff := GetMillis() - l.ExpiresAt - return timeDiff > LICENSE_GRACE_PERIOD + return timeDiff > LicenseGracePeriod } func (l *License) IsWithinExpirationPeriod() bool { days := l.DaysToExpiration() - return days <= SIXTY_DAYS && days >= FIFTY_EIGHT + return days <= 60 && days >= 58 } func (l *License) DaysToExpiration() int { diff --git a/model/license_test.go b/model/license_test.go index 1a5d6d6c7a..f98e97dbb0 100644 --- a/model/license_test.go +++ b/model/license_test.go @@ -126,7 +126,7 @@ func TestLicenseIsExpired(t *testing.T) { func TestLicenseIsPastGracePeriod(t *testing.T) { l1 := License{} - l1.ExpiresAt = GetMillis() - LICENSE_GRACE_PERIOD - 1000 + l1.ExpiresAt = GetMillis() - LicenseGracePeriod - 1000 assert.True(t, l1.IsPastGracePeriod()) l1.ExpiresAt = GetMillis() + 1000 diff --git a/model/link_metadata.go b/model/link_metadata.go index 6c3e0bd8fa..66d1073980 100644 --- a/model/link_metadata.go +++ b/model/link_metadata.go @@ -16,10 +16,10 @@ import ( ) const ( - LINK_METADATA_TYPE_IMAGE LinkMetadataType = "image" - LINK_METADATA_TYPE_NONE LinkMetadataType = "none" - LINK_METADATA_TYPE_OPENGRAPH LinkMetadataType = "opengraph" - MAX_IMAGES int = 5 + LinkMetadataTypeImage LinkMetadataType = "image" + LinkMetadataTypeNone LinkMetadataType = "none" + LinkMetadataTypeOpengraph LinkMetadataType = "opengraph" + LinkMetadataMaxImages int = 5 ) type LinkMetadataType string @@ -51,8 +51,8 @@ func truncateText(original string) string { } func firstNImages(images []*opengraph.Image, maxImages int) []*opengraph.Image { - if maxImages < 0 { // dont break stuff, if it's weird, go for sane defaults - maxImages = MAX_IMAGES + if maxImages < 0 { // don't break stuff, if it's weird, go for sane defaults + maxImages = LinkMetadataMaxImages } numImages := len(images) if numImages > maxImages { @@ -76,7 +76,7 @@ func TruncateOpenGraph(ogdata *opengraph.OpenGraph) *opengraph.OpenGraph { ogdata.Determiner = empty.Determiner ogdata.Locale = empty.Locale ogdata.LocalesAlternate = empty.LocalesAlternate - ogdata.Images = firstNImages(ogdata.Images, MAX_IMAGES) + ogdata.Images = firstNImages(ogdata.Images, LinkMetadataMaxImages) ogdata.Audios = empty.Audios ogdata.Videos = empty.Videos } @@ -97,7 +97,7 @@ func (o *LinkMetadata) IsValid() *AppError { } switch o.Type { - case LINK_METADATA_TYPE_IMAGE: + case LinkMetadataTypeImage: if o.Data == nil { return NewAppError("LinkMetadata.IsValid", "model.link_metadata.is_valid.data.app_error", nil, "", http.StatusBadRequest) } @@ -105,11 +105,11 @@ func (o *LinkMetadata) IsValid() *AppError { if _, ok := o.Data.(*PostImage); !ok { return NewAppError("LinkMetadata.IsValid", "model.link_metadata.is_valid.data_type.app_error", nil, "", http.StatusBadRequest) } - case LINK_METADATA_TYPE_NONE: + case LinkMetadataTypeNone: if o.Data != nil { return NewAppError("LinkMetadata.IsValid", "model.link_metadata.is_valid.data_type.app_error", nil, "", http.StatusBadRequest) } - case LINK_METADATA_TYPE_OPENGRAPH: + case LinkMetadataTypeOpengraph: if o.Data == nil { return NewAppError("LinkMetadata.IsValid", "model.link_metadata.is_valid.data.app_error", nil, "", http.StatusBadRequest) } @@ -146,13 +146,13 @@ func (o *LinkMetadata) DeserializeDataToConcreteType() error { var err error switch o.Type { - case LINK_METADATA_TYPE_IMAGE: + case LinkMetadataTypeImage: image := &PostImage{} err = json.Unmarshal(b, &image) data = image - case LINK_METADATA_TYPE_OPENGRAPH: + case LinkMetadataTypeOpengraph: og := &opengraph.OpenGraph{} json.Unmarshal(b, &og) diff --git a/model/link_metadata_test.go b/model/link_metadata_test.go index 0e7798b3f8..19fbec8feb 100644 --- a/model/link_metadata_test.go +++ b/model/link_metadata_test.go @@ -38,7 +38,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: &PostImage{}, }, Expected: true, @@ -48,7 +48,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_OPENGRAPH, + Type: LinkMetadataTypeOpengraph, Data: &opengraph.OpenGraph{}, }, Expected: true, @@ -58,7 +58,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_NONE, + Type: LinkMetadataTypeNone, Data: nil, }, Expected: true, @@ -67,7 +67,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Name: "should be invalid because of empty URL", Metadata: &LinkMetadata{ Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: &PostImage{}, }, Expected: false, @@ -76,7 +76,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Name: "should be invalid because of empty timestamp", Metadata: &LinkMetadata{ URL: "http://example.com", - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: &PostImage{}, }, Expected: false, @@ -86,7 +86,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800001, - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: &PostImage{}, }, Expected: false, @@ -106,7 +106,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, }, Expected: false, }, @@ -115,7 +115,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: &opengraph.OpenGraph{}, }, Expected: false, @@ -125,7 +125,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_OPENGRAPH, + Type: LinkMetadataTypeOpengraph, Data: &PostImage{}, }, Expected: false, @@ -135,7 +135,7 @@ func TestLinkMetadataIsValid(t *testing.T) { Metadata: &LinkMetadata{ URL: "http://example.com", Timestamp: 1546300800000, - Type: LINK_METADATA_TYPE_OPENGRAPH, + Type: LinkMetadataTypeOpengraph, Data: &Channel{}, }, Expected: false, @@ -161,7 +161,7 @@ func TestLinkMetadataDeserializeDataToConcreteType(t *testing.T) { } metadata := &LinkMetadata{ - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: []byte(image.ToJson()), } @@ -190,7 +190,7 @@ func TestLinkMetadataDeserializeDataToConcreteType(t *testing.T) { require.NoError(t, err) metadata := &LinkMetadata{ - Type: LINK_METADATA_TYPE_OPENGRAPH, + Type: LinkMetadataTypeOpengraph, Data: b, } @@ -205,7 +205,7 @@ func TestLinkMetadataDeserializeDataToConcreteType(t *testing.T) { t.Run("should ignore data of the correct type", func(t *testing.T) { metadata := &LinkMetadata{ - Type: LINK_METADATA_TYPE_OPENGRAPH, + Type: LinkMetadataTypeOpengraph, Data: 1234, } @@ -227,7 +227,7 @@ func TestLinkMetadataDeserializeDataToConcreteType(t *testing.T) { t.Run("should return error for invalid data", func(t *testing.T) { metadata := &LinkMetadata{ - Type: LINK_METADATA_TYPE_IMAGE, + Type: LinkMetadataTypeImage, Data: "garbage", } @@ -283,7 +283,7 @@ func TestFirstNImages(t *testing.T) { sampleImage("fifth.ico"), sampleImage("notme.tiff"), } - assert.Len(t, firstNImages(six, -10), MAX_IMAGES, "On negative, go for defaults") + assert.Len(t, firstNImages(six, -10), LinkMetadataMaxImages, "On negative, go for defaults") }) } diff --git a/model/migration.go b/model/migration.go index 019ca7b542..2e0efb46c0 100644 --- a/model/migration.go +++ b/model/migration.go @@ -4,35 +4,35 @@ package model const ( - ADVANCED_PERMISSIONS_MIGRATION_KEY = "AdvancedPermissionsMigrationComplete" - MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2 = "migration_advanced_permissions_phase_2" + AdvancedPermissionsMigrationKey = "AdvancedPermissionsMigrationComplete" + MigrationKeyAdvancedPermissionsPhase2 = "migration_advanced_permissions_phase_2" - MIGRATION_KEY_EMOJI_PERMISSIONS_SPLIT = "emoji_permissions_split" - MIGRATION_KEY_WEBHOOK_PERMISSIONS_SPLIT = "webhook_permissions_split" - MIGRATION_KEY_LIST_JOIN_PUBLIC_PRIVATE_TEAMS = "list_join_public_private_teams" - MIGRATION_KEY_REMOVE_PERMANENT_DELETE_USER = "remove_permanent_delete_user" - MIGRATION_KEY_ADD_BOT_PERMISSIONS = "add_bot_permissions" - MIGRATION_KEY_APPLY_CHANNEL_MANAGE_DELETE_TO_CHANNEL_USER = "apply_channel_manage_delete_to_channel_user" - MIGRATION_KEY_REMOVE_CHANNEL_MANAGE_DELETE_FROM_TEAM_USER = "remove_channel_manage_delete_from_team_user" - MIGRATION_KEY_VIEW_MEMBERS_NEW_PERMISSION = "view_members_new_permission" - MIGRATION_KEY_ADD_MANAGE_GUESTS_PERMISSIONS = "add_manage_guests_permissions" - MIGRATION_KEY_CHANNEL_MODERATIONS_PERMISSIONS = "channel_moderations_permissions" - MIGRATION_KEY_ADD_USE_GROUP_MENTIONS_PERMISSION = "add_use_group_mentions_permission" - MIGRATION_KEY_ADD_SYSTEM_CONSOLE_PERMISSIONS = "add_system_console_permissions" - MIGRATION_KEY_SIDEBAR_CATEGORIES_PHASE_2 = "migration_sidebar_categories_phase_2" - MIGRATION_KEY_ADD_CONVERT_CHANNEL_PERMISSIONS = "add_convert_channel_permissions" - MIGRATION_KEY_ADD_SYSTEM_ROLES_PERMISSIONS = "add_system_roles_permissions" - MIGRATION_KEY_ADD_BILLING_PERMISSIONS = "add_billing_permissions" - MIGRATION_KEY_ADD_MANAGE_SHARED_CHANNEL_PERMISSIONS = "manage_shared_channel_permissions" - MIGRATION_KEY_ADD_MANAGE_SECURE_CONNECTIONS_PERMISSIONS = "manage_secure_connections_permissions" - MIGRATION_KEY_ADD_DOWNLOAD_COMPLIANCE_EXPORT_RESULTS = "download_compliance_export_results" - MIGRATION_KEY_ADD_COMPLIANCE_SUBSECTION_PERMISSIONS = "compliance_subsection_permissions" - MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS = "experimental_subsection_permissions" - MIGRATION_KEY_ADD_AUTHENTICATION_SUBSECTION_PERMISSIONS = "authentication_subsection_permissions" - MIGRATION_KEY_ADD_SITE_SUBSECTION_PERMISSIONS = "site_subsection_permissions" - MIGRATION_KEY_ADD_ENVIRONMENT_SUBSECTION_PERMISSIONS = "environment_subsection_permissions" - MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS = "reporting_subsection_permissions" - MIGRATION_KEY_ADD_TEST_EMAIL_ANCILLARY_PERMISSION = "test_email_ancillary_permission" - MIGRATION_KEY_ADD_ABOUT_SUBSECTION_PERMISSIONS = "about_subsection_permissions" - MIGRATION_KEY_ADD_INTEGRATIONS_SUBSECTION_PERMISSIONS = "integrations_subsection_permissions" + MigrationKeyEmojiPermissionsSplit = "emoji_permissions_split" + MigrationKeyWebhookPermissionsSplit = "webhook_permissions_split" + MigrationKeyListJoinPublicPrivateTeams = "list_join_public_private_teams" + MigrationKeyRemovePermanentDeleteUser = "remove_permanent_delete_user" + MigrationKeyAddBotPermissions = "add_bot_permissions" + MigrationKeyApplyChannelManageDeleteToChannelUser = "apply_channel_manage_delete_to_channel_user" + MigrationKeyRemoveChannelManageDeleteFromTeamUser = "remove_channel_manage_delete_from_team_user" + MigrationKeyViewMembersNewPermission = "view_members_new_permission" + MigrationKeyAddManageGuestsPermissions = "add_manage_guests_permissions" + MigrationKeyChannelModerationsPermissions = "channel_moderations_permissions" + MigrationKeyAddUseGroupMentionsPermission = "add_use_group_mentions_permission" + MigrationKeyAddSystemConsolePermissions = "add_system_console_permissions" + MigrationKeySidebarCategoriesPhase2 = "migration_sidebar_categories_phase_2" + MigrationKeyAddConvertChannelPermissions = "add_convert_channel_permissions" + MigrationKeyAddSystemRolesPermissions = "add_system_roles_permissions" + MigrationKeyAddBillingPermissions = "add_billing_permissions" + MigrationKeyAddManageSharedChannelPermissions = "manage_shared_channel_permissions" + MigrationKeyAddManageSecureConnectionsPermissions = "manage_secure_connections_permissions" + MigrationKeyAddDownloadComplianceExportResults = "download_compliance_export_results" + MigrationKeyAddComplianceSubsectionPermissions = "compliance_subsection_permissions" + MigrationKeyAddExperimentalSubsectionPermissions = "experimental_subsection_permissions" + MigrationKeyAddAuthenticationSubsectionPermissions = "authentication_subsection_permissions" + MigrationKeyAddSiteSubsectionPermissions = "site_subsection_permissions" + MigrationKeyAddEnvironmentSubsectionPermissions = "environment_subsection_permissions" + MigrationKeyAddReportingSubsectionPermissions = "reporting_subsection_permissions" + MigrationKeyAddTestEmailAncillaryPermission = "test_email_ancillary_permission" + MigrationKeyAddAboutSubsectionPermissions = "about_subsection_permissions" + MigrationKeyAddIntegrationsSubsectionPermissions = "integrations_subsection_permissions" ) diff --git a/model/oauth.go b/model/oauth.go index 0719811626..85e250cff0 100644 --- a/model/oauth.go +++ b/model/oauth.go @@ -12,11 +12,11 @@ import ( ) const ( - OAUTH_ACTION_SIGNUP = "signup" - OAUTH_ACTION_LOGIN = "login" - OAUTH_ACTION_EMAIL_TO_SSO = "email_to_sso" - OAUTH_ACTION_SSO_TO_EMAIL = "sso_to_email" - OAUTH_ACTION_MOBILE = "mobile" + OAuthActionSignup = "signup" + OAuthActionLogin = "login" + OAuthActionEmailToSSO = "email_to_sso" + OAuthActionSSOToEmail = "sso_to_email" + OAuthActionMobile = "mobile" ) type OAuthApp struct { diff --git a/model/outgoing_webhook.go b/model/outgoing_webhook.go index 0d7a88fb80..7df0189ac9 100644 --- a/model/outgoing_webhook.go +++ b/model/outgoing_webhook.go @@ -57,7 +57,7 @@ type OutgoingWebhookResponse struct { ResponseType string `json:"response_type"` } -const OUTGOING_HOOK_RESPONSE_TYPE_COMMENT = "comment" +const OutgoingHookResponseTypeComment = "comment" func (o *OutgoingWebhookPayload) ToJSON() string { b, _ := json.Marshal(o) diff --git a/model/permission.go b/model/permission.go index bc4de236f5..9a90cb0d12 100644 --- a/model/permission.go +++ b/model/permission.go @@ -16,325 +16,325 @@ type Permission struct { Scope string `json:"scope"` } -var PERMISSION_INVITE_USER *Permission -var PERMISSION_ADD_USER_TO_TEAM *Permission -var PERMISSION_USE_SLASH_COMMANDS *Permission -var PERMISSION_MANAGE_SLASH_COMMANDS *Permission -var PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS *Permission -var PERMISSION_CREATE_PUBLIC_CHANNEL *Permission -var PERMISSION_CREATE_PRIVATE_CHANNEL *Permission -var PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS *Permission -var PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS *Permission -var PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE *Permission -var PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC *Permission -var PERMISSION_ASSIGN_SYSTEM_ADMIN_ROLE *Permission -var PERMISSION_MANAGE_ROLES *Permission -var PERMISSION_MANAGE_TEAM_ROLES *Permission -var PERMISSION_MANAGE_CHANNEL_ROLES *Permission -var PERMISSION_CREATE_DIRECT_CHANNEL *Permission -var PERMISSION_CREATE_GROUP_CHANNEL *Permission -var PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES *Permission -var PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES *Permission -var PERMISSION_LIST_PUBLIC_TEAMS *Permission -var PERMISSION_JOIN_PUBLIC_TEAMS *Permission -var PERMISSION_LIST_PRIVATE_TEAMS *Permission -var PERMISSION_JOIN_PRIVATE_TEAMS *Permission -var PERMISSION_LIST_TEAM_CHANNELS *Permission -var PERMISSION_JOIN_PUBLIC_CHANNELS *Permission -var PERMISSION_DELETE_PUBLIC_CHANNEL *Permission -var PERMISSION_DELETE_PRIVATE_CHANNEL *Permission -var PERMISSION_EDIT_OTHER_USERS *Permission -var PERMISSION_READ_CHANNEL *Permission -var PERMISSION_READ_PUBLIC_CHANNEL_GROUPS *Permission -var PERMISSION_READ_PRIVATE_CHANNEL_GROUPS *Permission -var PERMISSION_READ_PUBLIC_CHANNEL *Permission -var PERMISSION_ADD_REACTION *Permission -var PERMISSION_REMOVE_REACTION *Permission -var PERMISSION_REMOVE_OTHERS_REACTIONS *Permission -var PERMISSION_PERMANENT_DELETE_USER *Permission -var PERMISSION_UPLOAD_FILE *Permission -var PERMISSION_GET_PUBLIC_LINK *Permission -var PERMISSION_MANAGE_WEBHOOKS *Permission -var PERMISSION_MANAGE_OTHERS_WEBHOOKS *Permission -var PERMISSION_MANAGE_INCOMING_WEBHOOKS *Permission -var PERMISSION_MANAGE_OUTGOING_WEBHOOKS *Permission -var PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS *Permission -var PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS *Permission -var PERMISSION_MANAGE_OAUTH *Permission -var PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH *Permission -var PERMISSION_MANAGE_EMOJIS *Permission -var PERMISSION_MANAGE_OTHERS_EMOJIS *Permission -var PERMISSION_CREATE_EMOJIS *Permission -var PERMISSION_DELETE_EMOJIS *Permission -var PERMISSION_DELETE_OTHERS_EMOJIS *Permission -var PERMISSION_CREATE_POST *Permission -var PERMISSION_CREATE_POST_PUBLIC *Permission -var PERMISSION_CREATE_POST_EPHEMERAL *Permission -var PERMISSION_EDIT_POST *Permission -var PERMISSION_EDIT_OTHERS_POSTS *Permission -var PERMISSION_DELETE_POST *Permission -var PERMISSION_DELETE_OTHERS_POSTS *Permission -var PERMISSION_REMOVE_USER_FROM_TEAM *Permission -var PERMISSION_CREATE_TEAM *Permission -var PERMISSION_MANAGE_TEAM *Permission -var PERMISSION_IMPORT_TEAM *Permission -var PERMISSION_VIEW_TEAM *Permission -var PERMISSION_LIST_USERS_WITHOUT_TEAM *Permission -var PERMISSION_READ_JOBS *Permission -var PERMISSION_MANAGE_JOBS *Permission -var PERMISSION_CREATE_USER_ACCESS_TOKEN *Permission -var PERMISSION_READ_USER_ACCESS_TOKEN *Permission -var PERMISSION_REVOKE_USER_ACCESS_TOKEN *Permission -var PERMISSION_CREATE_BOT *Permission -var PERMISSION_ASSIGN_BOT *Permission -var PERMISSION_READ_BOTS *Permission -var PERMISSION_READ_OTHERS_BOTS *Permission -var PERMISSION_MANAGE_BOTS *Permission -var PERMISSION_MANAGE_OTHERS_BOTS *Permission -var PERMISSION_VIEW_MEMBERS *Permission -var PERMISSION_INVITE_GUEST *Permission -var PERMISSION_PROMOTE_GUEST *Permission -var PERMISSION_DEMOTE_TO_GUEST *Permission -var PERMISSION_USE_CHANNEL_MENTIONS *Permission -var PERMISSION_USE_GROUP_MENTIONS *Permission -var PERMISSION_READ_OTHER_USERS_TEAMS *Permission -var PERMISSION_EDIT_BRAND *Permission -var PERMISSION_MANAGE_SHARED_CHANNELS *Permission -var PERMISSION_MANAGE_SECURE_CONNECTIONS *Permission -var PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT *Permission -var PERMISSION_CREATE_DATA_RETENTION_JOB *Permission -var PERMISSION_READ_DATA_RETENTION_JOB *Permission -var PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB *Permission -var PERMISSION_READ_COMPLIANCE_EXPORT_JOB *Permission -var PERMISSION_READ_AUDITS *Permission -var PERMISSION_TEST_ELASTICSEARCH *Permission -var PERMISSION_TEST_SITE_URL *Permission -var PERMISSION_TEST_S3 *Permission -var PERMISSION_RELOAD_CONFIG *Permission -var PERMISSION_INVALIDATE_CACHES *Permission -var PERMISSION_RECYCLE_DATABASE_CONNECTIONS *Permission -var PERMISSION_PURGE_ELASTICSEARCH_INDEXES *Permission -var PERMISSION_TEST_EMAIL *Permission -var PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB *Permission -var PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB *Permission -var PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB *Permission -var PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB *Permission -var PERMISSION_PURGE_BLEVE_INDEXES *Permission -var PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB *Permission -var PERMISSION_CREATE_LDAP_SYNC_JOB *Permission -var PERMISSION_READ_LDAP_SYNC_JOB *Permission -var PERMISSION_TEST_LDAP *Permission -var PERMISSION_INVALIDATE_EMAIL_INVITE *Permission -var PERMISSION_GET_SAML_METADATA_FROM_IDP *Permission -var PERMISSION_ADD_SAML_PUBLIC_CERT *Permission -var PERMISSION_ADD_SAML_PRIVATE_CERT *Permission -var PERMISSION_ADD_SAML_IDP_CERT *Permission -var PERMISSION_REMOVE_SAML_PUBLIC_CERT *Permission -var PERMISSION_REMOVE_SAML_PRIVATE_CERT *Permission -var PERMISSION_REMOVE_SAML_IDP_CERT *Permission -var PERMISSION_GET_SAML_CERT_STATUS *Permission -var PERMISSION_ADD_LDAP_PUBLIC_CERT *Permission -var PERMISSION_ADD_LDAP_PRIVATE_CERT *Permission -var PERMISSION_REMOVE_LDAP_PUBLIC_CERT *Permission -var PERMISSION_REMOVE_LDAP_PRIVATE_CERT *Permission -var PERMISSION_GET_LOGS *Permission -var PERMISSION_GET_ANALYTICS *Permission -var PERMISSION_READ_LICENSE_INFORMATION *Permission -var PERMISSION_MANAGE_LICENSE_INFORMATION *Permission +var PermissionInviteUser *Permission +var PermissionAddUserToTeam *Permission +var PermissionUseSlashCommands *Permission +var PermissionManageSlashCommands *Permission +var PermissionManageOthersSlashCommands *Permission +var PermissionCreatePublicChannel *Permission +var PermissionCreatePrivateChannel *Permission +var PermissionManagePublicChannelMembers *Permission +var PermissionManagePrivateChannelMembers *Permission +var PermissionConvertPublicChannelToPrivate *Permission +var PermissionConvertPrivateChannelToPublic *Permission +var PermissionAssignSystemAdminRole *Permission +var PermissionManageRoles *Permission +var PermissionManageTeamRoles *Permission +var PermissionManageChannelRoles *Permission +var PermissionCreateDirectChannel *Permission +var PermissionCreateGroupChannel *Permission +var PermissionManagePublicChannelProperties *Permission +var PermissionManagePrivateChannelProperties *Permission +var PermissionListPublicTeams *Permission +var PermissionJoinPublicTeams *Permission +var PermissionListPrivateTeams *Permission +var PermissionJoinPrivateTeams *Permission +var PermissionListTeamChannels *Permission +var PermissionJoinPublicChannels *Permission +var PermissionDeletePublicChannel *Permission +var PermissionDeletePrivateChannel *Permission +var PermissionEditOtherUsers *Permission +var PermissionReadChannel *Permission +var PermissionReadPublicChannelGroups *Permission +var PermissionReadPrivateChannelGroups *Permission +var PermissionReadPublicChannel *Permission +var PermissionAddReaction *Permission +var PermissionRemoveReaction *Permission +var PermissionRemoveOthersReactions *Permission +var PermissionPermanentDeleteUser *Permission +var PermissionUploadFile *Permission +var PermissionGetPublicLink *Permission +var PermissionManageWebhooks *Permission +var PermissionManageOthersWebhooks *Permission +var PermissionManageIncomingWebhooks *Permission +var PermissionManageOutgoingWebhooks *Permission +var PermissionManageOthersIncomingWebhooks *Permission +var PermissionManageOthersOutgoingWebhooks *Permission +var PermissionManageOAuth *Permission +var PermissionManageSystemWideOAuth *Permission +var PermissionManageEmojis *Permission +var PermissionManageOthersEmojis *Permission +var PermissionCreateEmojis *Permission +var PermissionDeleteEmojis *Permission +var PermissionDeleteOthersEmojis *Permission +var PermissionCreatePost *Permission +var PermissionCreatePostPublic *Permission +var PermissionCreatePostEphemeral *Permission +var PermissionEditPost *Permission +var PermissionEditOthersPosts *Permission +var PermissionDeletePost *Permission +var PermissionDeleteOthersPosts *Permission +var PermissionRemoveUserFromTeam *Permission +var PermissionCreateTeam *Permission +var PermissionManageTeam *Permission +var PermissionImportTeam *Permission +var PermissionViewTeam *Permission +var PermissionListUsersWithoutTeam *Permission +var PermissionReadJobs *Permission +var PermissionManageJobs *Permission +var PermissionCreateUserAccessToken *Permission +var PermissionReadUserAccessToken *Permission +var PermissionRevokeUserAccessToken *Permission +var PermissionCreateBot *Permission +var PermissionAssignBot *Permission +var PermissionReadBots *Permission +var PermissionReadOthersBots *Permission +var PermissionManageBots *Permission +var PermissionManageOthersBots *Permission +var PermissionViewMembers *Permission +var PermissionInviteGuest *Permission +var PermissionPromoteGuest *Permission +var PermissionDemoteToGuest *Permission +var PermissionUseChannelMentions *Permission +var PermissionUseGroupMentions *Permission +var PermissionReadOtherUsersTeams *Permission +var PermissionEditBrand *Permission +var PermissionManageSharedChannels *Permission +var PermissionManageSecureConnections *Permission +var PermissionDownloadComplianceExportResult *Permission +var PermissionCreateDataRetentionJob *Permission +var PermissionReadDataRetentionJob *Permission +var PermissionCreateComplianceExportJob *Permission +var PermissionReadComplianceExportJob *Permission +var PermissionReadAudits *Permission +var PermissionTestElasticsearch *Permission +var PermissionTestSiteUrl *Permission +var PermissionTestS3 *Permission +var PermissionReloadConfig *Permission +var PermissionInvalidateCaches *Permission +var PermissionRecycleDatabaseConnections *Permission +var PermissionPurgeElasticsearchIndexes *Permission +var PermissionTestEmail *Permission +var PermissionCreateElasticsearchPostIndexingJob *Permission +var PermissionCreateElasticsearchPostAggregationJob *Permission +var PermissionReadElasticsearchPostIndexingJob *Permission +var PermissionReadElasticsearchPostAggregationJob *Permission +var PermissionPurgeBleveIndexes *Permission +var PermissionCreatePostBleveIndexesJob *Permission +var PermissionCreateLdapSyncJob *Permission +var PermissionReadLdapSyncJob *Permission +var PermissionTestLdap *Permission +var PermissionInvalidateEmailInvite *Permission +var PermissionGetSamlMetadataFromIdp *Permission +var PermissionAddSamlPublicCert *Permission +var PermissionAddSamlPrivateCert *Permission +var PermissionAddSamlIdpCert *Permission +var PermissionRemoveSamlPublicCert *Permission +var PermissionRemoveSamlPrivateCert *Permission +var PermissionRemoveSamlIdpCert *Permission +var PermissionGetSamlCertStatus *Permission +var PermissionAddLdapPublicCert *Permission +var PermissionAddLdapPrivateCert *Permission +var PermissionRemoveLdapPublicCert *Permission +var PermissionRemoveLdapPrivateCert *Permission +var PermissionGetLogs *Permission +var PermissionGetAnalytics *Permission +var PermissionReadLicenseInformation *Permission +var PermissionManageLicenseInformation *Permission -var PERMISSION_SYSCONSOLE_READ_ABOUT *Permission -var PERMISSION_SYSCONSOLE_WRITE_ABOUT *Permission +var PermissionSysconsoleReadAbout *Permission +var PermissionSysconsoleWriteAbout *Permission -var PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE *Permission -var PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE *Permission +var PermissionSysconsoleReadAboutEditionAndLicense *Permission +var PermissionSysconsoleWriteAboutEditionAndLicense *Permission -var PERMISSION_SYSCONSOLE_READ_BILLING *Permission -var PERMISSION_SYSCONSOLE_WRITE_BILLING *Permission +var PermissionSysconsoleReadBilling *Permission +var PermissionSysconsoleWriteBilling *Permission -var PERMISSION_SYSCONSOLE_READ_REPORTING *Permission -var PERMISSION_SYSCONSOLE_WRITE_REPORTING *Permission +var PermissionSysconsoleReadReporting *Permission +var PermissionSysconsoleWriteReporting *Permission -var PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS *Permission -var PERMISSION_SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS *Permission +var PermissionSysconsoleReadReportingSiteStatistics *Permission +var PermissionSysconsoleWriteReportingSiteStatistics *Permission -var PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS *Permission -var PERMISSION_SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS *Permission +var PermissionSysconsoleReadReportingTeamStatistics *Permission +var PermissionSysconsoleWriteReportingTeamStatistics *Permission -var PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS *Permission -var PERMISSION_SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS *Permission +var PermissionSysconsoleReadReportingServerLogs *Permission +var PermissionSysconsoleWriteReportingServerLogs *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS *Permission +var PermissionSysconsoleReadUserManagementUsers *Permission +var PermissionSysconsoleWriteUserManagementUsers *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS *Permission +var PermissionSysconsoleReadUserManagementGroups *Permission +var PermissionSysconsoleWriteUserManagementGroups *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS *Permission +var PermissionSysconsoleReadUserManagementTeams *Permission +var PermissionSysconsoleWriteUserManagementTeams *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS *Permission +var PermissionSysconsoleReadUserManagementChannels *Permission +var PermissionSysconsoleWriteUserManagementChannels *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS *Permission +var PermissionSysconsoleReadUserManagementPermissions *Permission +var PermissionSysconsoleWriteUserManagementPermissions *Permission -var PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES *Permission -var PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES *Permission +var PermissionSysconsoleReadUserManagementSystemRoles *Permission +var PermissionSysconsoleWriteUserManagementSystemRoles *Permission // DEPRECATED -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT *Permission +var PermissionSysconsoleReadEnvironment *Permission // DEPRECATED -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT *Permission +var PermissionSysconsoleWriteEnvironment *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER *Permission +var PermissionSysconsoleReadEnvironmentWebServer *Permission +var PermissionSysconsoleWriteEnvironmentWebServer *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE *Permission +var PermissionSysconsoleReadEnvironmentDatabase *Permission +var PermissionSysconsoleWriteEnvironmentDatabase *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH *Permission +var PermissionSysconsoleReadEnvironmentElasticsearch *Permission +var PermissionSysconsoleWriteEnvironmentElasticsearch *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE *Permission +var PermissionSysconsoleReadEnvironmentFileStorage *Permission +var PermissionSysconsoleWriteEnvironmentFileStorage *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY *Permission +var PermissionSysconsoleReadEnvironmentImageProxy *Permission +var PermissionSysconsoleWriteEnvironmentImageProxy *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP *Permission +var PermissionSysconsoleReadEnvironmentSmtp *Permission +var PermissionSysconsoleWriteEnvironmentSmtp *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER *Permission +var PermissionSysconsoleReadEnvironmentPushNotificationServer *Permission +var PermissionSysconsoleWriteEnvironmentPushNotificationServer *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY *Permission +var PermissionSysconsoleReadEnvironmentHighAvailability *Permission +var PermissionSysconsoleWriteEnvironmentHighAvailability *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING *Permission +var PermissionSysconsoleReadEnvironmentRateLimiting *Permission +var PermissionSysconsoleWriteEnvironmentRateLimiting *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING *Permission +var PermissionSysconsoleReadEnvironmentLogging *Permission +var PermissionSysconsoleWriteEnvironmentLogging *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS *Permission +var PermissionSysconsoleReadEnvironmentSessionLengths *Permission +var PermissionSysconsoleWriteEnvironmentSessionLengths *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING *Permission +var PermissionSysconsoleReadEnvironmentPerformanceMonitoring *Permission +var PermissionSysconsoleWriteEnvironmentPerformanceMonitoring *Permission -var PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER *Permission -var PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER *Permission +var PermissionSysconsoleReadEnvironmentDeveloper *Permission +var PermissionSysconsoleWriteEnvironmentDeveloper *Permission -var PERMISSION_SYSCONSOLE_READ_SITE *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE *Permission +var PermissionSysconsoleReadSite *Permission +var PermissionSysconsoleWriteSite *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION *Permission +var PermissionSysconsoleReadSiteCustomization *Permission +var PermissionSysconsoleWriteSiteCustomization *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION *Permission +var PermissionSysconsoleReadSiteLocalization *Permission +var PermissionSysconsoleWriteSiteLocalization *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS *Permission +var PermissionSysconsoleReadSiteUsersAndTeams *Permission +var PermissionSysconsoleWriteSiteUsersAndTeams *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS *Permission +var PermissionSysconsoleReadSiteNotifications *Permission +var PermissionSysconsoleWriteSiteNotifications *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER *Permission +var PermissionSysconsoleReadSiteAnnouncementBanner *Permission +var PermissionSysconsoleWriteSiteAnnouncementBanner *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_EMOJI *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI *Permission +var PermissionSysconsoleReadSiteEmoji *Permission +var PermissionSysconsoleWriteSiteEmoji *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_POSTS *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS *Permission +var PermissionSysconsoleReadSitePosts *Permission +var PermissionSysconsoleWriteSitePosts *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS *Permission +var PermissionSysconsoleReadSiteFileSharingAndDownloads *Permission +var PermissionSysconsoleWriteSiteFileSharingAndDownloads *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS *Permission +var PermissionSysconsoleReadSitePublicLinks *Permission +var PermissionSysconsoleWriteSitePublicLinks *Permission -var PERMISSION_SYSCONSOLE_READ_SITE_NOTICES *Permission -var PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES *Permission +var PermissionSysconsoleReadSiteNotices *Permission +var PermissionSysconsoleWriteSiteNotices *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION *Permission +var PermissionSysconsoleReadAuthentication *Permission +var PermissionSysconsoleWriteAuthentication *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP *Permission +var PermissionSysconsoleReadAuthenticationSignup *Permission +var PermissionSysconsoleWriteAuthenticationSignup *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL *Permission +var PermissionSysconsoleReadAuthenticationEmail *Permission +var PermissionSysconsoleWriteAuthenticationEmail *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD *Permission +var PermissionSysconsoleReadAuthenticationPassword *Permission +var PermissionSysconsoleWriteAuthenticationPassword *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_MFA *Permission +var PermissionSysconsoleReadAuthenticationMfa *Permission +var PermissionSysconsoleWriteAuthenticationMfa *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP *Permission +var PermissionSysconsoleReadAuthenticationLdap *Permission +var PermissionSysconsoleWriteAuthenticationLdap *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML *Permission +var PermissionSysconsoleReadAuthenticationSaml *Permission +var PermissionSysconsoleWriteAuthenticationSaml *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_OPENID *Permission +var PermissionSysconsoleReadAuthenticationOpenid *Permission +var PermissionSysconsoleWriteAuthenticationOpenid *Permission -var PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS *Permission -var PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS *Permission +var PermissionSysconsoleReadAuthenticationGuestAccess *Permission +var PermissionSysconsoleWriteAuthenticationGuestAccess *Permission -var PERMISSION_SYSCONSOLE_READ_PLUGINS *Permission -var PERMISSION_SYSCONSOLE_WRITE_PLUGINS *Permission +var PermissionSysconsoleReadPlugins *Permission +var PermissionSysconsoleWritePlugins *Permission -var PERMISSION_SYSCONSOLE_READ_INTEGRATIONS *Permission -var PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS *Permission +var PermissionSysconsoleReadIntegrations *Permission +var PermissionSysconsoleWriteIntegrations *Permission -var PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT *Permission -var PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT *Permission +var PermissionSysconsoleReadIntegrationsIntegrationManagement *Permission +var PermissionSysconsoleWriteIntegrationsIntegrationManagement *Permission -var PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS *Permission -var PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS *Permission +var PermissionSysconsoleReadIntegrationsBotAccounts *Permission +var PermissionSysconsoleWriteIntegrationsBotAccounts *Permission -var PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF *Permission -var PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF *Permission +var PermissionSysconsoleReadIntegrationsGif *Permission +var PermissionSysconsoleWriteIntegrationsGif *Permission -var PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS *Permission -var PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS *Permission +var PermissionSysconsoleReadIntegrationsCors *Permission +var PermissionSysconsoleWriteIntegrationsCors *Permission -var PERMISSION_SYSCONSOLE_READ_COMPLIANCE *Permission -var PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE *Permission +var PermissionSysconsoleReadCompliance *Permission +var PermissionSysconsoleWriteCompliance *Permission -var PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY *Permission -var PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY *Permission +var PermissionSysconsoleReadComplianceDataRetentionPolicy *Permission +var PermissionSysconsoleWriteComplianceDataRetentionPolicy *Permission -var PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT *Permission -var PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT *Permission +var PermissionSysconsoleReadComplianceComplianceExport *Permission +var PermissionSysconsoleWriteComplianceComplianceExport *Permission -var PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING *Permission -var PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING *Permission +var PermissionSysconsoleReadComplianceComplianceMonitoring *Permission +var PermissionSysconsoleWriteComplianceComplianceMonitoring *Permission -var PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE *Permission -var PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE *Permission +var PermissionSysconsoleReadComplianceCustomTermsOfService *Permission +var PermissionSysconsoleWriteComplianceCustomTermsOfService *Permission -var PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL *Permission -var PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL *Permission +var PermissionSysconsoleReadExperimental *Permission +var PermissionSysconsoleWriteExperimental *Permission -var PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES *Permission -var PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES *Permission +var PermissionSysconsoleReadExperimentalFeatures *Permission +var PermissionSysconsoleWriteExperimentalFeatures *Permission -var PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS *Permission -var PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS *Permission +var PermissionSysconsoleReadExperimentalFeatureFlags *Permission +var PermissionSysconsoleWriteExperimentalFeatureFlags *Permission -var PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE *Permission -var PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE *Permission +var PermissionSysconsoleReadExperimentalBleve *Permission +var PermissionSysconsoleWriteExperimentalBleve *Permission // General permission that encompasses all system admin functions // in the future this could be broken up to allow access to some // admin functions but not others -var PERMISSION_MANAGE_SYSTEM *Permission +var PermissionManageSystem *Permission var AllPermissions []*Permission var DeprecatedPermissions []*Permission @@ -346,1252 +346,1252 @@ var SysconsoleReadPermissions []*Permission var SysconsoleWritePermissions []*Permission func initializePermissions() { - PERMISSION_INVITE_USER = &Permission{ + PermissionInviteUser = &Permission{ "invite_user", "authentication.permissions.team_invite_user.name", "authentication.permissions.team_invite_user.description", PermissionScopeTeam, } - PERMISSION_ADD_USER_TO_TEAM = &Permission{ + PermissionAddUserToTeam = &Permission{ "add_user_to_team", "authentication.permissions.add_user_to_team.name", "authentication.permissions.add_user_to_team.description", PermissionScopeTeam, } - PERMISSION_USE_SLASH_COMMANDS = &Permission{ + PermissionUseSlashCommands = &Permission{ "use_slash_commands", "authentication.permissions.team_use_slash_commands.name", "authentication.permissions.team_use_slash_commands.description", PermissionScopeChannel, } - PERMISSION_MANAGE_SLASH_COMMANDS = &Permission{ + PermissionManageSlashCommands = &Permission{ "manage_slash_commands", "authentication.permissions.manage_slash_commands.name", "authentication.permissions.manage_slash_commands.description", PermissionScopeTeam, } - PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS = &Permission{ + PermissionManageOthersSlashCommands = &Permission{ "manage_others_slash_commands", "authentication.permissions.manage_others_slash_commands.name", "authentication.permissions.manage_others_slash_commands.description", PermissionScopeTeam, } - PERMISSION_CREATE_PUBLIC_CHANNEL = &Permission{ + PermissionCreatePublicChannel = &Permission{ "create_public_channel", "authentication.permissions.create_public_channel.name", "authentication.permissions.create_public_channel.description", PermissionScopeTeam, } - PERMISSION_CREATE_PRIVATE_CHANNEL = &Permission{ + PermissionCreatePrivateChannel = &Permission{ "create_private_channel", "authentication.permissions.create_private_channel.name", "authentication.permissions.create_private_channel.description", PermissionScopeTeam, } - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS = &Permission{ + PermissionManagePublicChannelMembers = &Permission{ "manage_public_channel_members", "authentication.permissions.manage_public_channel_members.name", "authentication.permissions.manage_public_channel_members.description", PermissionScopeChannel, } - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS = &Permission{ + PermissionManagePrivateChannelMembers = &Permission{ "manage_private_channel_members", "authentication.permissions.manage_private_channel_members.name", "authentication.permissions.manage_private_channel_members.description", PermissionScopeChannel, } - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE = &Permission{ + PermissionConvertPublicChannelToPrivate = &Permission{ "convert_public_channel_to_private", "authentication.permissions.convert_public_channel_to_private.name", "authentication.permissions.convert_public_channel_to_private.description", PermissionScopeChannel, } - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC = &Permission{ + PermissionConvertPrivateChannelToPublic = &Permission{ "convert_private_channel_to_public", "authentication.permissions.convert_private_channel_to_public.name", "authentication.permissions.convert_private_channel_to_public.description", PermissionScopeChannel, } - PERMISSION_ASSIGN_SYSTEM_ADMIN_ROLE = &Permission{ + PermissionAssignSystemAdminRole = &Permission{ "assign_system_admin_role", "authentication.permissions.assign_system_admin_role.name", "authentication.permissions.assign_system_admin_role.description", PermissionScopeSystem, } - PERMISSION_MANAGE_ROLES = &Permission{ + PermissionManageRoles = &Permission{ "manage_roles", "authentication.permissions.manage_roles.name", "authentication.permissions.manage_roles.description", PermissionScopeSystem, } - PERMISSION_MANAGE_TEAM_ROLES = &Permission{ + PermissionManageTeamRoles = &Permission{ "manage_team_roles", "authentication.permissions.manage_team_roles.name", "authentication.permissions.manage_team_roles.description", PermissionScopeTeam, } - PERMISSION_MANAGE_CHANNEL_ROLES = &Permission{ + PermissionManageChannelRoles = &Permission{ "manage_channel_roles", "authentication.permissions.manage_channel_roles.name", "authentication.permissions.manage_channel_roles.description", PermissionScopeChannel, } - PERMISSION_MANAGE_SYSTEM = &Permission{ + PermissionManageSystem = &Permission{ "manage_system", "authentication.permissions.manage_system.name", "authentication.permissions.manage_system.description", PermissionScopeSystem, } - PERMISSION_CREATE_DIRECT_CHANNEL = &Permission{ + PermissionCreateDirectChannel = &Permission{ "create_direct_channel", "authentication.permissions.create_direct_channel.name", "authentication.permissions.create_direct_channel.description", PermissionScopeSystem, } - PERMISSION_CREATE_GROUP_CHANNEL = &Permission{ + PermissionCreateGroupChannel = &Permission{ "create_group_channel", "authentication.permissions.create_group_channel.name", "authentication.permissions.create_group_channel.description", PermissionScopeSystem, } - PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES = &Permission{ + PermissionManagePublicChannelProperties = &Permission{ "manage_public_channel_properties", "authentication.permissions.manage_public_channel_properties.name", "authentication.permissions.manage_public_channel_properties.description", PermissionScopeChannel, } - PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES = &Permission{ + PermissionManagePrivateChannelProperties = &Permission{ "manage_private_channel_properties", "authentication.permissions.manage_private_channel_properties.name", "authentication.permissions.manage_private_channel_properties.description", PermissionScopeChannel, } - PERMISSION_LIST_PUBLIC_TEAMS = &Permission{ + PermissionListPublicTeams = &Permission{ "list_public_teams", "authentication.permissions.list_public_teams.name", "authentication.permissions.list_public_teams.description", PermissionScopeSystem, } - PERMISSION_JOIN_PUBLIC_TEAMS = &Permission{ + PermissionJoinPublicTeams = &Permission{ "join_public_teams", "authentication.permissions.join_public_teams.name", "authentication.permissions.join_public_teams.description", PermissionScopeSystem, } - PERMISSION_LIST_PRIVATE_TEAMS = &Permission{ + PermissionListPrivateTeams = &Permission{ "list_private_teams", "authentication.permissions.list_private_teams.name", "authentication.permissions.list_private_teams.description", PermissionScopeSystem, } - PERMISSION_JOIN_PRIVATE_TEAMS = &Permission{ + PermissionJoinPrivateTeams = &Permission{ "join_private_teams", "authentication.permissions.join_private_teams.name", "authentication.permissions.join_private_teams.description", PermissionScopeSystem, } - PERMISSION_LIST_TEAM_CHANNELS = &Permission{ + PermissionListTeamChannels = &Permission{ "list_team_channels", "authentication.permissions.list_team_channels.name", "authentication.permissions.list_team_channels.description", PermissionScopeTeam, } - PERMISSION_JOIN_PUBLIC_CHANNELS = &Permission{ + PermissionJoinPublicChannels = &Permission{ "join_public_channels", "authentication.permissions.join_public_channels.name", "authentication.permissions.join_public_channels.description", PermissionScopeTeam, } - PERMISSION_DELETE_PUBLIC_CHANNEL = &Permission{ + PermissionDeletePublicChannel = &Permission{ "delete_public_channel", "authentication.permissions.delete_public_channel.name", "authentication.permissions.delete_public_channel.description", PermissionScopeChannel, } - PERMISSION_DELETE_PRIVATE_CHANNEL = &Permission{ + PermissionDeletePrivateChannel = &Permission{ "delete_private_channel", "authentication.permissions.delete_private_channel.name", "authentication.permissions.delete_private_channel.description", PermissionScopeChannel, } - PERMISSION_EDIT_OTHER_USERS = &Permission{ + PermissionEditOtherUsers = &Permission{ "edit_other_users", "authentication.permissions.edit_other_users.name", "authentication.permissions.edit_other_users.description", PermissionScopeSystem, } - PERMISSION_READ_CHANNEL = &Permission{ + PermissionReadChannel = &Permission{ "read_channel", "authentication.permissions.read_channel.name", "authentication.permissions.read_channel.description", PermissionScopeChannel, } - PERMISSION_READ_PUBLIC_CHANNEL_GROUPS = &Permission{ + PermissionReadPublicChannelGroups = &Permission{ "read_public_channel_groups", "authentication.permissions.read_public_channel_groups.name", "authentication.permissions.read_public_channel_groups.description", PermissionScopeChannel, } - PERMISSION_READ_PRIVATE_CHANNEL_GROUPS = &Permission{ + PermissionReadPrivateChannelGroups = &Permission{ "read_private_channel_groups", "authentication.permissions.read_private_channel_groups.name", "authentication.permissions.read_private_channel_groups.description", PermissionScopeChannel, } - PERMISSION_READ_PUBLIC_CHANNEL = &Permission{ + PermissionReadPublicChannel = &Permission{ "read_public_channel", "authentication.permissions.read_public_channel.name", "authentication.permissions.read_public_channel.description", PermissionScopeTeam, } - PERMISSION_ADD_REACTION = &Permission{ + PermissionAddReaction = &Permission{ "add_reaction", "authentication.permissions.add_reaction.name", "authentication.permissions.add_reaction.description", PermissionScopeChannel, } - PERMISSION_REMOVE_REACTION = &Permission{ + PermissionRemoveReaction = &Permission{ "remove_reaction", "authentication.permissions.remove_reaction.name", "authentication.permissions.remove_reaction.description", PermissionScopeChannel, } - PERMISSION_REMOVE_OTHERS_REACTIONS = &Permission{ + PermissionRemoveOthersReactions = &Permission{ "remove_others_reactions", "authentication.permissions.remove_others_reactions.name", "authentication.permissions.remove_others_reactions.description", PermissionScopeChannel, } // DEPRECATED - PERMISSION_PERMANENT_DELETE_USER = &Permission{ + PermissionPermanentDeleteUser = &Permission{ "permanent_delete_user", "authentication.permissions.permanent_delete_user.name", "authentication.permissions.permanent_delete_user.description", PermissionScopeSystem, } - PERMISSION_UPLOAD_FILE = &Permission{ + PermissionUploadFile = &Permission{ "upload_file", "authentication.permissions.upload_file.name", "authentication.permissions.upload_file.description", PermissionScopeChannel, } - PERMISSION_GET_PUBLIC_LINK = &Permission{ + PermissionGetPublicLink = &Permission{ "get_public_link", "authentication.permissions.get_public_link.name", "authentication.permissions.get_public_link.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_MANAGE_WEBHOOKS = &Permission{ + PermissionManageWebhooks = &Permission{ "manage_webhooks", "authentication.permissions.manage_webhooks.name", "authentication.permissions.manage_webhooks.description", PermissionScopeTeam, } // DEPRECATED - PERMISSION_MANAGE_OTHERS_WEBHOOKS = &Permission{ + PermissionManageOthersWebhooks = &Permission{ "manage_others_webhooks", "authentication.permissions.manage_others_webhooks.name", "authentication.permissions.manage_others_webhooks.description", PermissionScopeTeam, } - PERMISSION_MANAGE_INCOMING_WEBHOOKS = &Permission{ + PermissionManageIncomingWebhooks = &Permission{ "manage_incoming_webhooks", "authentication.permissions.manage_incoming_webhooks.name", "authentication.permissions.manage_incoming_webhooks.description", PermissionScopeTeam, } - PERMISSION_MANAGE_OUTGOING_WEBHOOKS = &Permission{ + PermissionManageOutgoingWebhooks = &Permission{ "manage_outgoing_webhooks", "authentication.permissions.manage_outgoing_webhooks.name", "authentication.permissions.manage_outgoing_webhooks.description", PermissionScopeTeam, } - PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS = &Permission{ + PermissionManageOthersIncomingWebhooks = &Permission{ "manage_others_incoming_webhooks", "authentication.permissions.manage_others_incoming_webhooks.name", "authentication.permissions.manage_others_incoming_webhooks.description", PermissionScopeTeam, } - PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS = &Permission{ + PermissionManageOthersOutgoingWebhooks = &Permission{ "manage_others_outgoing_webhooks", "authentication.permissions.manage_others_outgoing_webhooks.name", "authentication.permissions.manage_others_outgoing_webhooks.description", PermissionScopeTeam, } - PERMISSION_MANAGE_OAUTH = &Permission{ + PermissionManageOAuth = &Permission{ "manage_oauth", "authentication.permissions.manage_oauth.name", "authentication.permissions.manage_oauth.description", PermissionScopeSystem, } - PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH = &Permission{ + PermissionManageSystemWideOAuth = &Permission{ "manage_system_wide_oauth", "authentication.permissions.manage_system_wide_oauth.name", "authentication.permissions.manage_system_wide_oauth.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_MANAGE_EMOJIS = &Permission{ + PermissionManageEmojis = &Permission{ "manage_emojis", "authentication.permissions.manage_emojis.name", "authentication.permissions.manage_emojis.description", PermissionScopeTeam, } // DEPRECATED - PERMISSION_MANAGE_OTHERS_EMOJIS = &Permission{ + PermissionManageOthersEmojis = &Permission{ "manage_others_emojis", "authentication.permissions.manage_others_emojis.name", "authentication.permissions.manage_others_emojis.description", PermissionScopeTeam, } - PERMISSION_CREATE_EMOJIS = &Permission{ + PermissionCreateEmojis = &Permission{ "create_emojis", "authentication.permissions.create_emojis.name", "authentication.permissions.create_emojis.description", PermissionScopeTeam, } - PERMISSION_DELETE_EMOJIS = &Permission{ + PermissionDeleteEmojis = &Permission{ "delete_emojis", "authentication.permissions.delete_emojis.name", "authentication.permissions.delete_emojis.description", PermissionScopeTeam, } - PERMISSION_DELETE_OTHERS_EMOJIS = &Permission{ + PermissionDeleteOthersEmojis = &Permission{ "delete_others_emojis", "authentication.permissions.delete_others_emojis.name", "authentication.permissions.delete_others_emojis.description", PermissionScopeTeam, } - PERMISSION_CREATE_POST = &Permission{ + PermissionCreatePost = &Permission{ "create_post", "authentication.permissions.create_post.name", "authentication.permissions.create_post.description", PermissionScopeChannel, } - PERMISSION_CREATE_POST_PUBLIC = &Permission{ + PermissionCreatePostPublic = &Permission{ "create_post_public", "authentication.permissions.create_post_public.name", "authentication.permissions.create_post_public.description", PermissionScopeChannel, } - PERMISSION_CREATE_POST_EPHEMERAL = &Permission{ + PermissionCreatePostEphemeral = &Permission{ "create_post_ephemeral", "authentication.permissions.create_post_ephemeral.name", "authentication.permissions.create_post_ephemeral.description", PermissionScopeChannel, } - PERMISSION_EDIT_POST = &Permission{ + PermissionEditPost = &Permission{ "edit_post", "authentication.permissions.edit_post.name", "authentication.permissions.edit_post.description", PermissionScopeChannel, } - PERMISSION_EDIT_OTHERS_POSTS = &Permission{ + PermissionEditOthersPosts = &Permission{ "edit_others_posts", "authentication.permissions.edit_others_posts.name", "authentication.permissions.edit_others_posts.description", PermissionScopeChannel, } - PERMISSION_DELETE_POST = &Permission{ + PermissionDeletePost = &Permission{ "delete_post", "authentication.permissions.delete_post.name", "authentication.permissions.delete_post.description", PermissionScopeChannel, } - PERMISSION_DELETE_OTHERS_POSTS = &Permission{ + PermissionDeleteOthersPosts = &Permission{ "delete_others_posts", "authentication.permissions.delete_others_posts.name", "authentication.permissions.delete_others_posts.description", PermissionScopeChannel, } - PERMISSION_MANAGE_SHARED_CHANNELS = &Permission{ + PermissionManageSharedChannels = &Permission{ "manage_shared_channels", "authentication.permissions.manage_shared_channels.name", "authentication.permissions.manage_shared_channels.description", PermissionScopeSystem, } - PERMISSION_MANAGE_SECURE_CONNECTIONS = &Permission{ + PermissionManageSecureConnections = &Permission{ "manage_secure_connections", "authentication.permissions.manage_secure_connections.name", "authentication.permissions.manage_secure_connections.description", PermissionScopeSystem, } - PERMISSION_CREATE_DATA_RETENTION_JOB = &Permission{ + PermissionCreateDataRetentionJob = &Permission{ "create_data_retention_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_DATA_RETENTION_JOB = &Permission{ + PermissionReadDataRetentionJob = &Permission{ "read_data_retention_job", "", "", PermissionScopeSystem, } - PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB = &Permission{ + PermissionCreateComplianceExportJob = &Permission{ "create_compliance_export_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_COMPLIANCE_EXPORT_JOB = &Permission{ + PermissionReadComplianceExportJob = &Permission{ "read_compliance_export_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_AUDITS = &Permission{ + PermissionReadAudits = &Permission{ "read_audits", "", "", PermissionScopeSystem, } - PERMISSION_PURGE_BLEVE_INDEXES = &Permission{ + PermissionPurgeBleveIndexes = &Permission{ "purge_bleve_indexes", "", "", PermissionScopeSystem, } - PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB = &Permission{ + PermissionCreatePostBleveIndexesJob = &Permission{ "create_post_bleve_indexes_job", "", "", PermissionScopeSystem, } - PERMISSION_CREATE_LDAP_SYNC_JOB = &Permission{ + PermissionCreateLdapSyncJob = &Permission{ "create_ldap_sync_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_LDAP_SYNC_JOB = &Permission{ + PermissionReadLdapSyncJob = &Permission{ "read_ldap_sync_job", "", "", PermissionScopeSystem, } - PERMISSION_TEST_LDAP = &Permission{ + PermissionTestLdap = &Permission{ "test_ldap", "", "", PermissionScopeSystem, } - PERMISSION_INVALIDATE_EMAIL_INVITE = &Permission{ + PermissionInvalidateEmailInvite = &Permission{ "invalidate_email_invite", "", "", PermissionScopeSystem, } - PERMISSION_GET_SAML_METADATA_FROM_IDP = &Permission{ + PermissionGetSamlMetadataFromIdp = &Permission{ "get_saml_metadata_from_idp", "", "", PermissionScopeSystem, } - PERMISSION_ADD_SAML_PUBLIC_CERT = &Permission{ + PermissionAddSamlPublicCert = &Permission{ "add_saml_public_cert", "", "", PermissionScopeSystem, } - PERMISSION_ADD_SAML_PRIVATE_CERT = &Permission{ + PermissionAddSamlPrivateCert = &Permission{ "add_saml_private_cert", "", "", PermissionScopeSystem, } - PERMISSION_ADD_SAML_IDP_CERT = &Permission{ + PermissionAddSamlIdpCert = &Permission{ "add_saml_idp_cert", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_SAML_PUBLIC_CERT = &Permission{ + PermissionRemoveSamlPublicCert = &Permission{ "remove_saml_public_cert", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_SAML_PRIVATE_CERT = &Permission{ + PermissionRemoveSamlPrivateCert = &Permission{ "remove_saml_private_cert", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_SAML_IDP_CERT = &Permission{ + PermissionRemoveSamlIdpCert = &Permission{ "remove_saml_idp_cert", "", "", PermissionScopeSystem, } - PERMISSION_GET_SAML_CERT_STATUS = &Permission{ + PermissionGetSamlCertStatus = &Permission{ "get_saml_cert_status", "", "", PermissionScopeSystem, } - PERMISSION_ADD_LDAP_PUBLIC_CERT = &Permission{ + PermissionAddLdapPublicCert = &Permission{ "add_ldap_public_cert", "", "", PermissionScopeSystem, } - PERMISSION_ADD_LDAP_PRIVATE_CERT = &Permission{ + PermissionAddLdapPrivateCert = &Permission{ "add_ldap_private_cert", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_LDAP_PUBLIC_CERT = &Permission{ + PermissionRemoveLdapPublicCert = &Permission{ "remove_ldap_public_cert", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_LDAP_PRIVATE_CERT = &Permission{ + PermissionRemoveLdapPrivateCert = &Permission{ "remove_ldap_private_cert", "", "", PermissionScopeSystem, } - PERMISSION_GET_LOGS = &Permission{ + PermissionGetLogs = &Permission{ "get_logs", "", "", PermissionScopeSystem, } - PERMISSION_READ_LICENSE_INFORMATION = &Permission{ + PermissionReadLicenseInformation = &Permission{ "read_license_information", "", "", PermissionScopeSystem, } - PERMISSION_GET_ANALYTICS = &Permission{ + PermissionGetAnalytics = &Permission{ "get_analytics", "", "", PermissionScopeSystem, } - PERMISSION_MANAGE_LICENSE_INFORMATION = &Permission{ + PermissionManageLicenseInformation = &Permission{ "manage_license_information", "", "", PermissionScopeSystem, } - PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT = &Permission{ + PermissionDownloadComplianceExportResult = &Permission{ "download_compliance_export_result", "authentication.permissions.download_compliance_export_result.name", "authentication.permissions.download_compliance_export_result.description", PermissionScopeSystem, } - PERMISSION_TEST_SITE_URL = &Permission{ + PermissionTestSiteUrl = &Permission{ "test_site_url", "", "", PermissionScopeSystem, } - PERMISSION_TEST_ELASTICSEARCH = &Permission{ + PermissionTestElasticsearch = &Permission{ "test_elasticsearch", "", "", PermissionScopeSystem, } - PERMISSION_TEST_S3 = &Permission{ + PermissionTestS3 = &Permission{ "test_s3", "", "", PermissionScopeSystem, } - PERMISSION_RELOAD_CONFIG = &Permission{ + PermissionReloadConfig = &Permission{ "reload_config", "", "", PermissionScopeSystem, } - PERMISSION_INVALIDATE_CACHES = &Permission{ + PermissionInvalidateCaches = &Permission{ "invalidate_caches", "", "", PermissionScopeSystem, } - PERMISSION_RECYCLE_DATABASE_CONNECTIONS = &Permission{ + PermissionRecycleDatabaseConnections = &Permission{ "recycle_database_connections", "", "", PermissionScopeSystem, } - PERMISSION_PURGE_ELASTICSEARCH_INDEXES = &Permission{ + PermissionPurgeElasticsearchIndexes = &Permission{ "purge_elasticsearch_indexes", "", "", PermissionScopeSystem, } - PERMISSION_TEST_EMAIL = &Permission{ + PermissionTestEmail = &Permission{ "test_email", "", "", PermissionScopeSystem, } - PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB = &Permission{ + PermissionCreateElasticsearchPostIndexingJob = &Permission{ "create_elasticsearch_post_indexing_job", "", "", PermissionScopeSystem, } - PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB = &Permission{ + PermissionCreateElasticsearchPostAggregationJob = &Permission{ "create_elasticsearch_post_aggregation_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB = &Permission{ + PermissionReadElasticsearchPostIndexingJob = &Permission{ "read_elasticsearch_post_indexing_job", "", "", PermissionScopeSystem, } - PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB = &Permission{ + PermissionReadElasticsearchPostAggregationJob = &Permission{ "read_elasticsearch_post_aggregation_job", "", "", PermissionScopeSystem, } - PERMISSION_REMOVE_USER_FROM_TEAM = &Permission{ + PermissionRemoveUserFromTeam = &Permission{ "remove_user_from_team", "authentication.permissions.remove_user_from_team.name", "authentication.permissions.remove_user_from_team.description", PermissionScopeTeam, } - PERMISSION_CREATE_TEAM = &Permission{ + PermissionCreateTeam = &Permission{ "create_team", "authentication.permissions.create_team.name", "authentication.permissions.create_team.description", PermissionScopeSystem, } - PERMISSION_MANAGE_TEAM = &Permission{ + PermissionManageTeam = &Permission{ "manage_team", "authentication.permissions.manage_team.name", "authentication.permissions.manage_team.description", PermissionScopeTeam, } - PERMISSION_IMPORT_TEAM = &Permission{ + PermissionImportTeam = &Permission{ "import_team", "authentication.permissions.import_team.name", "authentication.permissions.import_team.description", PermissionScopeTeam, } - PERMISSION_VIEW_TEAM = &Permission{ + PermissionViewTeam = &Permission{ "view_team", "authentication.permissions.view_team.name", "authentication.permissions.view_team.description", PermissionScopeTeam, } - PERMISSION_LIST_USERS_WITHOUT_TEAM = &Permission{ + PermissionListUsersWithoutTeam = &Permission{ "list_users_without_team", "authentication.permissions.list_users_without_team.name", "authentication.permissions.list_users_without_team.description", PermissionScopeSystem, } - PERMISSION_CREATE_USER_ACCESS_TOKEN = &Permission{ + PermissionCreateUserAccessToken = &Permission{ "create_user_access_token", "authentication.permissions.create_user_access_token.name", "authentication.permissions.create_user_access_token.description", PermissionScopeSystem, } - PERMISSION_READ_USER_ACCESS_TOKEN = &Permission{ + PermissionReadUserAccessToken = &Permission{ "read_user_access_token", "authentication.permissions.read_user_access_token.name", "authentication.permissions.read_user_access_token.description", PermissionScopeSystem, } - PERMISSION_REVOKE_USER_ACCESS_TOKEN = &Permission{ + PermissionRevokeUserAccessToken = &Permission{ "revoke_user_access_token", "authentication.permissions.revoke_user_access_token.name", "authentication.permissions.revoke_user_access_token.description", PermissionScopeSystem, } - PERMISSION_CREATE_BOT = &Permission{ + PermissionCreateBot = &Permission{ "create_bot", "authentication.permissions.create_bot.name", "authentication.permissions.create_bot.description", PermissionScopeSystem, } - PERMISSION_ASSIGN_BOT = &Permission{ + PermissionAssignBot = &Permission{ "assign_bot", "authentication.permissions.assign_bot.name", "authentication.permissions.assign_bot.description", PermissionScopeSystem, } - PERMISSION_READ_BOTS = &Permission{ + PermissionReadBots = &Permission{ "read_bots", "authentication.permissions.read_bots.name", "authentication.permissions.read_bots.description", PermissionScopeSystem, } - PERMISSION_READ_OTHERS_BOTS = &Permission{ + PermissionReadOthersBots = &Permission{ "read_others_bots", "authentication.permissions.read_others_bots.name", "authentication.permissions.read_others_bots.description", PermissionScopeSystem, } - PERMISSION_MANAGE_BOTS = &Permission{ + PermissionManageBots = &Permission{ "manage_bots", "authentication.permissions.manage_bots.name", "authentication.permissions.manage_bots.description", PermissionScopeSystem, } - PERMISSION_MANAGE_OTHERS_BOTS = &Permission{ + PermissionManageOthersBots = &Permission{ "manage_others_bots", "authentication.permissions.manage_others_bots.name", "authentication.permissions.manage_others_bots.description", PermissionScopeSystem, } - PERMISSION_READ_JOBS = &Permission{ + PermissionReadJobs = &Permission{ "read_jobs", "authentication.permisssions.read_jobs.name", "authentication.permisssions.read_jobs.description", PermissionScopeSystem, } - PERMISSION_MANAGE_JOBS = &Permission{ + PermissionManageJobs = &Permission{ "manage_jobs", "authentication.permisssions.manage_jobs.name", "authentication.permisssions.manage_jobs.description", PermissionScopeSystem, } - PERMISSION_VIEW_MEMBERS = &Permission{ + PermissionViewMembers = &Permission{ "view_members", "authentication.permisssions.view_members.name", "authentication.permisssions.view_members.description", PermissionScopeTeam, } - PERMISSION_INVITE_GUEST = &Permission{ + PermissionInviteGuest = &Permission{ "invite_guest", "authentication.permissions.invite_guest.name", "authentication.permissions.invite_guest.description", PermissionScopeTeam, } - PERMISSION_PROMOTE_GUEST = &Permission{ + PermissionPromoteGuest = &Permission{ "promote_guest", "authentication.permissions.promote_guest.name", "authentication.permissions.promote_guest.description", PermissionScopeSystem, } - PERMISSION_DEMOTE_TO_GUEST = &Permission{ + PermissionDemoteToGuest = &Permission{ "demote_to_guest", "authentication.permissions.demote_to_guest.name", "authentication.permissions.demote_to_guest.description", PermissionScopeSystem, } - PERMISSION_USE_CHANNEL_MENTIONS = &Permission{ + PermissionUseChannelMentions = &Permission{ "use_channel_mentions", "authentication.permissions.use_channel_mentions.name", "authentication.permissions.use_channel_mentions.description", PermissionScopeChannel, } - PERMISSION_USE_GROUP_MENTIONS = &Permission{ + PermissionUseGroupMentions = &Permission{ "use_group_mentions", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeChannel, } - PERMISSION_READ_OTHER_USERS_TEAMS = &Permission{ + PermissionReadOtherUsersTeams = &Permission{ "read_other_users_teams", "authentication.permissions.read_other_users_teams.name", "authentication.permissions.read_other_users_teams.description", PermissionScopeSystem, } - PERMISSION_EDIT_BRAND = &Permission{ + PermissionEditBrand = &Permission{ "edit_brand", "authentication.permissions.edit_brand.name", "authentication.permissions.edit_brand.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_ABOUT = &Permission{ + PermissionSysconsoleReadAbout = &Permission{ "sysconsole_read_about", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_ABOUT = &Permission{ + PermissionSysconsoleWriteAbout = &Permission{ "sysconsole_write_about", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE = &Permission{ + PermissionSysconsoleReadAboutEditionAndLicense = &Permission{ "sysconsole_read_about_edition_and_license", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE = &Permission{ + PermissionSysconsoleWriteAboutEditionAndLicense = &Permission{ "sysconsole_write_about_edition_and_license", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_BILLING = &Permission{ + PermissionSysconsoleReadBilling = &Permission{ "sysconsole_read_billing", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_BILLING = &Permission{ + PermissionSysconsoleWriteBilling = &Permission{ "sysconsole_write_billing", "", "", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_REPORTING = &Permission{ + PermissionSysconsoleReadReporting = &Permission{ "sysconsole_read_reporting", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_REPORTING = &Permission{ + PermissionSysconsoleWriteReporting = &Permission{ "sysconsole_write_reporting", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS = &Permission{ + PermissionSysconsoleReadReportingSiteStatistics = &Permission{ "sysconsole_read_reporting_site_statistics", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS = &Permission{ + PermissionSysconsoleWriteReportingSiteStatistics = &Permission{ "sysconsole_write_reporting_site_statistics", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS = &Permission{ + PermissionSysconsoleReadReportingTeamStatistics = &Permission{ "sysconsole_read_reporting_team_statistics", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS = &Permission{ + PermissionSysconsoleWriteReportingTeamStatistics = &Permission{ "sysconsole_write_reporting_team_statistics", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS = &Permission{ + PermissionSysconsoleReadReportingServerLogs = &Permission{ "sysconsole_read_reporting_server_logs", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS = &Permission{ + PermissionSysconsoleWriteReportingServerLogs = &Permission{ "sysconsole_write_reporting_server_logs", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS = &Permission{ + PermissionSysconsoleReadUserManagementUsers = &Permission{ "sysconsole_read_user_management_users", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS = &Permission{ + PermissionSysconsoleWriteUserManagementUsers = &Permission{ "sysconsole_write_user_management_users", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS = &Permission{ + PermissionSysconsoleReadUserManagementGroups = &Permission{ "sysconsole_read_user_management_groups", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS = &Permission{ + PermissionSysconsoleWriteUserManagementGroups = &Permission{ "sysconsole_write_user_management_groups", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS = &Permission{ + PermissionSysconsoleReadUserManagementTeams = &Permission{ "sysconsole_read_user_management_teams", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS = &Permission{ + PermissionSysconsoleWriteUserManagementTeams = &Permission{ "sysconsole_write_user_management_teams", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS = &Permission{ + PermissionSysconsoleReadUserManagementChannels = &Permission{ "sysconsole_read_user_management_channels", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS = &Permission{ + PermissionSysconsoleWriteUserManagementChannels = &Permission{ "sysconsole_write_user_management_channels", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS = &Permission{ + PermissionSysconsoleReadUserManagementPermissions = &Permission{ "sysconsole_read_user_management_permissions", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS = &Permission{ + PermissionSysconsoleWriteUserManagementPermissions = &Permission{ "sysconsole_write_user_management_permissions", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES = &Permission{ + PermissionSysconsoleReadUserManagementSystemRoles = &Permission{ "sysconsole_read_user_management_system_roles", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES = &Permission{ + PermissionSysconsoleWriteUserManagementSystemRoles = &Permission{ "sysconsole_write_user_management_system_roles", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT = &Permission{ + PermissionSysconsoleReadEnvironment = &Permission{ "sysconsole_read_environment", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT = &Permission{ + PermissionSysconsoleWriteEnvironment = &Permission{ "sysconsole_write_environment", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER = &Permission{ + PermissionSysconsoleReadEnvironmentWebServer = &Permission{ "sysconsole_read_environment_web_server", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER = &Permission{ + PermissionSysconsoleWriteEnvironmentWebServer = &Permission{ "sysconsole_write_environment_web_server", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE = &Permission{ + PermissionSysconsoleReadEnvironmentDatabase = &Permission{ "sysconsole_read_environment_database", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE = &Permission{ + PermissionSysconsoleWriteEnvironmentDatabase = &Permission{ "sysconsole_write_environment_database", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH = &Permission{ + PermissionSysconsoleReadEnvironmentElasticsearch = &Permission{ "sysconsole_read_environment_elasticsearch", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH = &Permission{ + PermissionSysconsoleWriteEnvironmentElasticsearch = &Permission{ "sysconsole_write_environment_elasticsearch", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE = &Permission{ + PermissionSysconsoleReadEnvironmentFileStorage = &Permission{ "sysconsole_read_environment_file_storage", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE = &Permission{ + PermissionSysconsoleWriteEnvironmentFileStorage = &Permission{ "sysconsole_write_environment_file_storage", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY = &Permission{ + PermissionSysconsoleReadEnvironmentImageProxy = &Permission{ "sysconsole_read_environment_image_proxy", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY = &Permission{ + PermissionSysconsoleWriteEnvironmentImageProxy = &Permission{ "sysconsole_write_environment_image_proxy", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP = &Permission{ + PermissionSysconsoleReadEnvironmentSmtp = &Permission{ "sysconsole_read_environment_smtp", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP = &Permission{ + PermissionSysconsoleWriteEnvironmentSmtp = &Permission{ "sysconsole_write_environment_smtp", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER = &Permission{ + PermissionSysconsoleReadEnvironmentPushNotificationServer = &Permission{ "sysconsole_read_environment_push_notification_server", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER = &Permission{ + PermissionSysconsoleWriteEnvironmentPushNotificationServer = &Permission{ "sysconsole_write_environment_push_notification_server", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY = &Permission{ + PermissionSysconsoleReadEnvironmentHighAvailability = &Permission{ "sysconsole_read_environment_high_availability", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY = &Permission{ + PermissionSysconsoleWriteEnvironmentHighAvailability = &Permission{ "sysconsole_write_environment_high_availability", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING = &Permission{ + PermissionSysconsoleReadEnvironmentRateLimiting = &Permission{ "sysconsole_read_environment_rate_limiting", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING = &Permission{ + PermissionSysconsoleWriteEnvironmentRateLimiting = &Permission{ "sysconsole_write_environment_rate_limiting", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING = &Permission{ + PermissionSysconsoleReadEnvironmentLogging = &Permission{ "sysconsole_read_environment_logging", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING = &Permission{ + PermissionSysconsoleWriteEnvironmentLogging = &Permission{ "sysconsole_write_environment_logging", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS = &Permission{ + PermissionSysconsoleReadEnvironmentSessionLengths = &Permission{ "sysconsole_read_environment_session_lengths", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS = &Permission{ + PermissionSysconsoleWriteEnvironmentSessionLengths = &Permission{ "sysconsole_write_environment_session_lengths", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING = &Permission{ + PermissionSysconsoleReadEnvironmentPerformanceMonitoring = &Permission{ "sysconsole_read_environment_performance_monitoring", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING = &Permission{ + PermissionSysconsoleWriteEnvironmentPerformanceMonitoring = &Permission{ "sysconsole_write_environment_performance_monitoring", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER = &Permission{ + PermissionSysconsoleReadEnvironmentDeveloper = &Permission{ "sysconsole_read_environment_developer", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER = &Permission{ + PermissionSysconsoleWriteEnvironmentDeveloper = &Permission{ "sysconsole_write_environment_developer", "", "", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_SITE = &Permission{ + PermissionSysconsoleReadSite = &Permission{ "sysconsole_read_site", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_SITE = &Permission{ + PermissionSysconsoleWriteSite = &Permission{ "sysconsole_write_site", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION = &Permission{ + PermissionSysconsoleReadSiteCustomization = &Permission{ "sysconsole_read_site_customization", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION = &Permission{ + PermissionSysconsoleWriteSiteCustomization = &Permission{ "sysconsole_write_site_customization", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION = &Permission{ + PermissionSysconsoleReadSiteLocalization = &Permission{ "sysconsole_read_site_localization", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION = &Permission{ + PermissionSysconsoleWriteSiteLocalization = &Permission{ "sysconsole_write_site_localization", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS = &Permission{ + PermissionSysconsoleReadSiteUsersAndTeams = &Permission{ "sysconsole_read_site_users_and_teams", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS = &Permission{ + PermissionSysconsoleWriteSiteUsersAndTeams = &Permission{ "sysconsole_write_site_users_and_teams", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS = &Permission{ + PermissionSysconsoleReadSiteNotifications = &Permission{ "sysconsole_read_site_notifications", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS = &Permission{ + PermissionSysconsoleWriteSiteNotifications = &Permission{ "sysconsole_write_site_notifications", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER = &Permission{ + PermissionSysconsoleReadSiteAnnouncementBanner = &Permission{ "sysconsole_read_site_announcement_banner", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER = &Permission{ + PermissionSysconsoleWriteSiteAnnouncementBanner = &Permission{ "sysconsole_write_site_announcement_banner", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_EMOJI = &Permission{ + PermissionSysconsoleReadSiteEmoji = &Permission{ "sysconsole_read_site_emoji", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI = &Permission{ + PermissionSysconsoleWriteSiteEmoji = &Permission{ "sysconsole_write_site_emoji", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_POSTS = &Permission{ + PermissionSysconsoleReadSitePosts = &Permission{ "sysconsole_read_site_posts", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS = &Permission{ + PermissionSysconsoleWriteSitePosts = &Permission{ "sysconsole_write_site_posts", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS = &Permission{ + PermissionSysconsoleReadSiteFileSharingAndDownloads = &Permission{ "sysconsole_read_site_file_sharing_and_downloads", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS = &Permission{ + PermissionSysconsoleWriteSiteFileSharingAndDownloads = &Permission{ "sysconsole_write_site_file_sharing_and_downloads", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS = &Permission{ + PermissionSysconsoleReadSitePublicLinks = &Permission{ "sysconsole_read_site_public_links", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS = &Permission{ + PermissionSysconsoleWriteSitePublicLinks = &Permission{ "sysconsole_write_site_public_links", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_SITE_NOTICES = &Permission{ + PermissionSysconsoleReadSiteNotices = &Permission{ "sysconsole_read_site_notices", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES = &Permission{ + PermissionSysconsoleWriteSiteNotices = &Permission{ "sysconsole_write_site_notices", "", "", @@ -1599,296 +1599,296 @@ func initializePermissions() { } // Deprecated - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION = &Permission{ + PermissionSysconsoleReadAuthentication = &Permission{ "sysconsole_read_authentication", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // Deprecated - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION = &Permission{ + PermissionSysconsoleWriteAuthentication = &Permission{ "sysconsole_write_authentication", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP = &Permission{ + PermissionSysconsoleReadAuthenticationSignup = &Permission{ "sysconsole_read_authentication_signup", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP = &Permission{ + PermissionSysconsoleWriteAuthenticationSignup = &Permission{ "sysconsole_write_authentication_signup", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL = &Permission{ + PermissionSysconsoleReadAuthenticationEmail = &Permission{ "sysconsole_read_authentication_email", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL = &Permission{ + PermissionSysconsoleWriteAuthenticationEmail = &Permission{ "sysconsole_write_authentication_email", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD = &Permission{ + PermissionSysconsoleReadAuthenticationPassword = &Permission{ "sysconsole_read_authentication_password", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD = &Permission{ + PermissionSysconsoleWriteAuthenticationPassword = &Permission{ "sysconsole_write_authentication_password", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA = &Permission{ + PermissionSysconsoleReadAuthenticationMfa = &Permission{ "sysconsole_read_authentication_mfa", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_MFA = &Permission{ + PermissionSysconsoleWriteAuthenticationMfa = &Permission{ "sysconsole_write_authentication_mfa", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP = &Permission{ + PermissionSysconsoleReadAuthenticationLdap = &Permission{ "sysconsole_read_authentication_ldap", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP = &Permission{ + PermissionSysconsoleWriteAuthenticationLdap = &Permission{ "sysconsole_write_authentication_ldap", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML = &Permission{ + PermissionSysconsoleReadAuthenticationSaml = &Permission{ "sysconsole_read_authentication_saml", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML = &Permission{ + PermissionSysconsoleWriteAuthenticationSaml = &Permission{ "sysconsole_write_authentication_saml", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID = &Permission{ + PermissionSysconsoleReadAuthenticationOpenid = &Permission{ "sysconsole_read_authentication_openid", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_OPENID = &Permission{ + PermissionSysconsoleWriteAuthenticationOpenid = &Permission{ "sysconsole_write_authentication_openid", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS = &Permission{ + PermissionSysconsoleReadAuthenticationGuestAccess = &Permission{ "sysconsole_read_authentication_guest_access", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS = &Permission{ + PermissionSysconsoleWriteAuthenticationGuestAccess = &Permission{ "sysconsole_write_authentication_guest_access", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_PLUGINS = &Permission{ + PermissionSysconsoleReadPlugins = &Permission{ "sysconsole_read_plugins", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_PLUGINS = &Permission{ + PermissionSysconsoleWritePlugins = &Permission{ "sysconsole_write_plugins", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS = &Permission{ + PermissionSysconsoleReadIntegrations = &Permission{ "sysconsole_read_integrations", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS = &Permission{ + PermissionSysconsoleWriteIntegrations = &Permission{ "sysconsole_write_integrations", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT = &Permission{ + PermissionSysconsoleReadIntegrationsIntegrationManagement = &Permission{ "sysconsole_read_integrations_integration_management", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT = &Permission{ + PermissionSysconsoleWriteIntegrationsIntegrationManagement = &Permission{ "sysconsole_write_integrations_integration_management", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS = &Permission{ + PermissionSysconsoleReadIntegrationsBotAccounts = &Permission{ "sysconsole_read_integrations_bot_accounts", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS = &Permission{ + PermissionSysconsoleWriteIntegrationsBotAccounts = &Permission{ "sysconsole_write_integrations_bot_accounts", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF = &Permission{ + PermissionSysconsoleReadIntegrationsGif = &Permission{ "sysconsole_read_integrations_gif", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF = &Permission{ + PermissionSysconsoleWriteIntegrationsGif = &Permission{ "sysconsole_write_integrations_gif", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS = &Permission{ + PermissionSysconsoleReadIntegrationsCors = &Permission{ "sysconsole_read_integrations_cors", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS = &Permission{ + PermissionSysconsoleWriteIntegrationsCors = &Permission{ "sysconsole_write_integrations_cors", "", "", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_COMPLIANCE = &Permission{ + PermissionSysconsoleReadCompliance = &Permission{ "sysconsole_read_compliance", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE = &Permission{ + PermissionSysconsoleWriteCompliance = &Permission{ "sysconsole_write_compliance", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY = &Permission{ + PermissionSysconsoleReadComplianceDataRetentionPolicy = &Permission{ "sysconsole_read_compliance_data_retention_policy", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY = &Permission{ + PermissionSysconsoleWriteComplianceDataRetentionPolicy = &Permission{ "sysconsole_write_compliance_data_retention_policy", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT = &Permission{ + PermissionSysconsoleReadComplianceComplianceExport = &Permission{ "sysconsole_read_compliance_compliance_export", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT = &Permission{ + PermissionSysconsoleWriteComplianceComplianceExport = &Permission{ "sysconsole_write_compliance_compliance_export", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING = &Permission{ + PermissionSysconsoleReadComplianceComplianceMonitoring = &Permission{ "sysconsole_read_compliance_compliance_monitoring", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING = &Permission{ + PermissionSysconsoleWriteComplianceComplianceMonitoring = &Permission{ "sysconsole_write_compliance_compliance_monitoring", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE = &Permission{ + PermissionSysconsoleReadComplianceCustomTermsOfService = &Permission{ "sysconsole_read_compliance_custom_terms_of_service", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE = &Permission{ + PermissionSysconsoleWriteComplianceCustomTermsOfService = &Permission{ "sysconsole_write_compliance_custom_terms_of_service", "", "", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL = &Permission{ + PermissionSysconsoleReadExperimental = &Permission{ "sysconsole_read_experimental", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } // DEPRECATED - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL = &Permission{ + PermissionSysconsoleWriteExperimental = &Permission{ "sysconsole_write_experimental", "authentication.permissions.use_group_mentions.name", "authentication.permissions.use_group_mentions.description", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES = &Permission{ + PermissionSysconsoleReadExperimentalFeatures = &Permission{ "sysconsole_read_experimental_features", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES = &Permission{ + PermissionSysconsoleWriteExperimentalFeatures = &Permission{ "sysconsole_write_experimental_features", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS = &Permission{ + PermissionSysconsoleReadExperimentalFeatureFlags = &Permission{ "sysconsole_read_experimental_feature_flags", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS = &Permission{ + PermissionSysconsoleWriteExperimentalFeatureFlags = &Permission{ "sysconsole_write_experimental_feature_flags", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE = &Permission{ + PermissionSysconsoleReadExperimentalBleve = &Permission{ "sysconsole_read_experimental_bleve", "", "", PermissionScopeSystem, } - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE = &Permission{ + PermissionSysconsoleWriteExperimentalBleve = &Permission{ "sysconsole_write_experimental_bleve", "", "", @@ -1896,271 +1896,271 @@ func initializePermissions() { } SysconsoleReadPermissions = []*Permission{ - PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE, - PERMISSION_SYSCONSOLE_READ_BILLING, - PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS, - PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS, - PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER, - PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION, - PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION, - PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS, - PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS, - PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER, - PERMISSION_SYSCONSOLE_READ_SITE_EMOJI, - PERMISSION_SYSCONSOLE_READ_SITE_POSTS, - PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS, - PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS, - PERMISSION_SYSCONSOLE_READ_SITE_NOTICES, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS, - PERMISSION_SYSCONSOLE_READ_PLUGINS, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE, + PermissionSysconsoleReadAboutEditionAndLicense, + PermissionSysconsoleReadBilling, + PermissionSysconsoleReadReportingSiteStatistics, + PermissionSysconsoleReadReportingTeamStatistics, + PermissionSysconsoleReadReportingServerLogs, + PermissionSysconsoleReadUserManagementUsers, + PermissionSysconsoleReadUserManagementGroups, + PermissionSysconsoleReadUserManagementTeams, + PermissionSysconsoleReadUserManagementChannels, + PermissionSysconsoleReadUserManagementPermissions, + PermissionSysconsoleReadUserManagementSystemRoles, + PermissionSysconsoleReadEnvironmentWebServer, + PermissionSysconsoleReadEnvironmentDatabase, + PermissionSysconsoleReadEnvironmentElasticsearch, + PermissionSysconsoleReadEnvironmentFileStorage, + PermissionSysconsoleReadEnvironmentImageProxy, + PermissionSysconsoleReadEnvironmentSmtp, + PermissionSysconsoleReadEnvironmentPushNotificationServer, + PermissionSysconsoleReadEnvironmentHighAvailability, + PermissionSysconsoleReadEnvironmentRateLimiting, + PermissionSysconsoleReadEnvironmentLogging, + PermissionSysconsoleReadEnvironmentSessionLengths, + PermissionSysconsoleReadEnvironmentPerformanceMonitoring, + PermissionSysconsoleReadEnvironmentDeveloper, + PermissionSysconsoleReadSiteCustomization, + PermissionSysconsoleReadSiteLocalization, + PermissionSysconsoleReadSiteUsersAndTeams, + PermissionSysconsoleReadSiteNotifications, + PermissionSysconsoleReadSiteAnnouncementBanner, + PermissionSysconsoleReadSiteEmoji, + PermissionSysconsoleReadSitePosts, + PermissionSysconsoleReadSiteFileSharingAndDownloads, + PermissionSysconsoleReadSitePublicLinks, + PermissionSysconsoleReadSiteNotices, + PermissionSysconsoleReadAuthenticationSignup, + PermissionSysconsoleReadAuthenticationEmail, + PermissionSysconsoleReadAuthenticationPassword, + PermissionSysconsoleReadAuthenticationMfa, + PermissionSysconsoleReadAuthenticationLdap, + PermissionSysconsoleReadAuthenticationSaml, + PermissionSysconsoleReadAuthenticationOpenid, + PermissionSysconsoleReadAuthenticationGuestAccess, + PermissionSysconsoleReadPlugins, + PermissionSysconsoleReadIntegrationsIntegrationManagement, + PermissionSysconsoleReadIntegrationsBotAccounts, + PermissionSysconsoleReadIntegrationsGif, + PermissionSysconsoleReadIntegrationsCors, + PermissionSysconsoleReadComplianceDataRetentionPolicy, + PermissionSysconsoleReadComplianceComplianceExport, + PermissionSysconsoleReadComplianceComplianceMonitoring, + PermissionSysconsoleReadComplianceCustomTermsOfService, + PermissionSysconsoleReadExperimentalFeatures, + PermissionSysconsoleReadExperimentalFeatureFlags, + PermissionSysconsoleReadExperimentalBleve, } SysconsoleWritePermissions = []*Permission{ - PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE, - PERMISSION_SYSCONSOLE_WRITE_BILLING, - PERMISSION_SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS, - PERMISSION_SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS, - PERMISSION_SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER, - PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION, - PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION, - PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS, - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS, - PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER, - PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI, - PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS, - PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS, - PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS, - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_MFA, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_OPENID, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS, - PERMISSION_SYSCONSOLE_WRITE_PLUGINS, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE, - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES, - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS, - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE, + PermissionSysconsoleWriteAboutEditionAndLicense, + PermissionSysconsoleWriteBilling, + PermissionSysconsoleWriteReportingSiteStatistics, + PermissionSysconsoleWriteReportingTeamStatistics, + PermissionSysconsoleWriteReportingServerLogs, + PermissionSysconsoleWriteUserManagementUsers, + PermissionSysconsoleWriteUserManagementGroups, + PermissionSysconsoleWriteUserManagementTeams, + PermissionSysconsoleWriteUserManagementChannels, + PermissionSysconsoleWriteUserManagementPermissions, + PermissionSysconsoleWriteUserManagementSystemRoles, + PermissionSysconsoleWriteEnvironmentWebServer, + PermissionSysconsoleWriteEnvironmentDatabase, + PermissionSysconsoleWriteEnvironmentElasticsearch, + PermissionSysconsoleWriteEnvironmentFileStorage, + PermissionSysconsoleWriteEnvironmentImageProxy, + PermissionSysconsoleWriteEnvironmentSmtp, + PermissionSysconsoleWriteEnvironmentPushNotificationServer, + PermissionSysconsoleWriteEnvironmentHighAvailability, + PermissionSysconsoleWriteEnvironmentRateLimiting, + PermissionSysconsoleWriteEnvironmentLogging, + PermissionSysconsoleWriteEnvironmentSessionLengths, + PermissionSysconsoleWriteEnvironmentPerformanceMonitoring, + PermissionSysconsoleWriteEnvironmentDeveloper, + PermissionSysconsoleWriteSiteCustomization, + PermissionSysconsoleWriteSiteLocalization, + PermissionSysconsoleWriteSiteUsersAndTeams, + PermissionSysconsoleWriteSiteNotifications, + PermissionSysconsoleWriteSiteAnnouncementBanner, + PermissionSysconsoleWriteSiteEmoji, + PermissionSysconsoleWriteSitePosts, + PermissionSysconsoleWriteSiteFileSharingAndDownloads, + PermissionSysconsoleWriteSitePublicLinks, + PermissionSysconsoleWriteSiteNotices, + PermissionSysconsoleWriteAuthenticationSignup, + PermissionSysconsoleWriteAuthenticationEmail, + PermissionSysconsoleWriteAuthenticationPassword, + PermissionSysconsoleWriteAuthenticationMfa, + PermissionSysconsoleWriteAuthenticationLdap, + PermissionSysconsoleWriteAuthenticationSaml, + PermissionSysconsoleWriteAuthenticationOpenid, + PermissionSysconsoleWriteAuthenticationGuestAccess, + PermissionSysconsoleWritePlugins, + PermissionSysconsoleWriteIntegrationsIntegrationManagement, + PermissionSysconsoleWriteIntegrationsBotAccounts, + PermissionSysconsoleWriteIntegrationsGif, + PermissionSysconsoleWriteIntegrationsCors, + PermissionSysconsoleWriteComplianceDataRetentionPolicy, + PermissionSysconsoleWriteComplianceComplianceExport, + PermissionSysconsoleWriteComplianceComplianceMonitoring, + PermissionSysconsoleWriteComplianceCustomTermsOfService, + PermissionSysconsoleWriteExperimentalFeatures, + PermissionSysconsoleWriteExperimentalFeatureFlags, + PermissionSysconsoleWriteExperimentalBleve, } SystemScopedPermissionsMinusSysconsole := []*Permission{ - PERMISSION_ASSIGN_SYSTEM_ADMIN_ROLE, - PERMISSION_MANAGE_ROLES, - PERMISSION_MANAGE_SYSTEM, - PERMISSION_CREATE_DIRECT_CHANNEL, - PERMISSION_CREATE_GROUP_CHANNEL, - PERMISSION_LIST_PUBLIC_TEAMS, - PERMISSION_JOIN_PUBLIC_TEAMS, - PERMISSION_LIST_PRIVATE_TEAMS, - PERMISSION_JOIN_PRIVATE_TEAMS, - PERMISSION_EDIT_OTHER_USERS, - PERMISSION_READ_OTHER_USERS_TEAMS, - PERMISSION_GET_PUBLIC_LINK, - PERMISSION_MANAGE_OAUTH, - PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH, - PERMISSION_CREATE_TEAM, - PERMISSION_LIST_USERS_WITHOUT_TEAM, - PERMISSION_CREATE_USER_ACCESS_TOKEN, - PERMISSION_READ_USER_ACCESS_TOKEN, - PERMISSION_REVOKE_USER_ACCESS_TOKEN, - PERMISSION_CREATE_BOT, - PERMISSION_ASSIGN_BOT, - PERMISSION_READ_BOTS, - PERMISSION_READ_OTHERS_BOTS, - PERMISSION_MANAGE_BOTS, - PERMISSION_MANAGE_OTHERS_BOTS, - PERMISSION_READ_JOBS, - PERMISSION_MANAGE_JOBS, - PERMISSION_PROMOTE_GUEST, - PERMISSION_DEMOTE_TO_GUEST, - PERMISSION_EDIT_BRAND, - PERMISSION_MANAGE_SHARED_CHANNELS, - PERMISSION_MANAGE_SECURE_CONNECTIONS, - PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT, - PERMISSION_CREATE_DATA_RETENTION_JOB, - PERMISSION_READ_DATA_RETENTION_JOB, - PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB, - PERMISSION_READ_COMPLIANCE_EXPORT_JOB, - PERMISSION_READ_AUDITS, - PERMISSION_TEST_SITE_URL, - PERMISSION_TEST_ELASTICSEARCH, - PERMISSION_TEST_S3, - PERMISSION_RELOAD_CONFIG, - PERMISSION_INVALIDATE_CACHES, - PERMISSION_RECYCLE_DATABASE_CONNECTIONS, - PERMISSION_PURGE_ELASTICSEARCH_INDEXES, - PERMISSION_TEST_EMAIL, - PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB, - PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB, - PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB, - PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB, - PERMISSION_PURGE_BLEVE_INDEXES, - PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB, - PERMISSION_CREATE_LDAP_SYNC_JOB, - PERMISSION_READ_LDAP_SYNC_JOB, - PERMISSION_TEST_LDAP, - PERMISSION_INVALIDATE_EMAIL_INVITE, - PERMISSION_GET_SAML_METADATA_FROM_IDP, - PERMISSION_ADD_SAML_PUBLIC_CERT, - PERMISSION_ADD_SAML_PRIVATE_CERT, - PERMISSION_ADD_SAML_IDP_CERT, - PERMISSION_REMOVE_SAML_PUBLIC_CERT, - PERMISSION_REMOVE_SAML_PRIVATE_CERT, - PERMISSION_REMOVE_SAML_IDP_CERT, - PERMISSION_GET_SAML_CERT_STATUS, - PERMISSION_ADD_LDAP_PUBLIC_CERT, - PERMISSION_ADD_LDAP_PRIVATE_CERT, - PERMISSION_REMOVE_LDAP_PUBLIC_CERT, - PERMISSION_REMOVE_LDAP_PRIVATE_CERT, - PERMISSION_GET_ANALYTICS, - PERMISSION_GET_LOGS, - PERMISSION_READ_LICENSE_INFORMATION, - PERMISSION_MANAGE_LICENSE_INFORMATION, + PermissionAssignSystemAdminRole, + PermissionManageRoles, + PermissionManageSystem, + PermissionCreateDirectChannel, + PermissionCreateGroupChannel, + PermissionListPublicTeams, + PermissionJoinPublicTeams, + PermissionListPrivateTeams, + PermissionJoinPrivateTeams, + PermissionEditOtherUsers, + PermissionReadOtherUsersTeams, + PermissionGetPublicLink, + PermissionManageOAuth, + PermissionManageSystemWideOAuth, + PermissionCreateTeam, + PermissionListUsersWithoutTeam, + PermissionCreateUserAccessToken, + PermissionReadUserAccessToken, + PermissionRevokeUserAccessToken, + PermissionCreateBot, + PermissionAssignBot, + PermissionReadBots, + PermissionReadOthersBots, + PermissionManageBots, + PermissionManageOthersBots, + PermissionReadJobs, + PermissionManageJobs, + PermissionPromoteGuest, + PermissionDemoteToGuest, + PermissionEditBrand, + PermissionManageSharedChannels, + PermissionManageSecureConnections, + PermissionDownloadComplianceExportResult, + PermissionCreateDataRetentionJob, + PermissionReadDataRetentionJob, + PermissionCreateComplianceExportJob, + PermissionReadComplianceExportJob, + PermissionReadAudits, + PermissionTestSiteUrl, + PermissionTestElasticsearch, + PermissionTestS3, + PermissionReloadConfig, + PermissionInvalidateCaches, + PermissionRecycleDatabaseConnections, + PermissionPurgeElasticsearchIndexes, + PermissionTestEmail, + PermissionCreateElasticsearchPostIndexingJob, + PermissionCreateElasticsearchPostAggregationJob, + PermissionReadElasticsearchPostIndexingJob, + PermissionReadElasticsearchPostAggregationJob, + PermissionPurgeBleveIndexes, + PermissionCreatePostBleveIndexesJob, + PermissionCreateLdapSyncJob, + PermissionReadLdapSyncJob, + PermissionTestLdap, + PermissionInvalidateEmailInvite, + PermissionGetSamlMetadataFromIdp, + PermissionAddSamlPublicCert, + PermissionAddSamlPrivateCert, + PermissionAddSamlIdpCert, + PermissionRemoveSamlPublicCert, + PermissionRemoveSamlPrivateCert, + PermissionRemoveSamlIdpCert, + PermissionGetSamlCertStatus, + PermissionAddLdapPublicCert, + PermissionAddLdapPrivateCert, + PermissionRemoveLdapPublicCert, + PermissionRemoveLdapPrivateCert, + PermissionGetAnalytics, + PermissionGetLogs, + PermissionReadLicenseInformation, + PermissionManageLicenseInformation, } TeamScopedPermissions := []*Permission{ - PERMISSION_INVITE_USER, - PERMISSION_ADD_USER_TO_TEAM, - PERMISSION_MANAGE_SLASH_COMMANDS, - PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS, - PERMISSION_CREATE_PUBLIC_CHANNEL, - PERMISSION_CREATE_PRIVATE_CHANNEL, - PERMISSION_MANAGE_TEAM_ROLES, - PERMISSION_LIST_TEAM_CHANNELS, - PERMISSION_JOIN_PUBLIC_CHANNELS, - PERMISSION_READ_PUBLIC_CHANNEL, - PERMISSION_MANAGE_INCOMING_WEBHOOKS, - PERMISSION_MANAGE_OUTGOING_WEBHOOKS, - PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS, - PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS, - PERMISSION_CREATE_EMOJIS, - PERMISSION_DELETE_EMOJIS, - PERMISSION_DELETE_OTHERS_EMOJIS, - PERMISSION_REMOVE_USER_FROM_TEAM, - PERMISSION_MANAGE_TEAM, - PERMISSION_IMPORT_TEAM, - PERMISSION_VIEW_TEAM, - PERMISSION_VIEW_MEMBERS, - PERMISSION_INVITE_GUEST, + PermissionInviteUser, + PermissionAddUserToTeam, + PermissionManageSlashCommands, + PermissionManageOthersSlashCommands, + PermissionCreatePublicChannel, + PermissionCreatePrivateChannel, + PermissionManageTeamRoles, + PermissionListTeamChannels, + PermissionJoinPublicChannels, + PermissionReadPublicChannel, + PermissionManageIncomingWebhooks, + PermissionManageOutgoingWebhooks, + PermissionManageOthersIncomingWebhooks, + PermissionManageOthersOutgoingWebhooks, + PermissionCreateEmojis, + PermissionDeleteEmojis, + PermissionDeleteOthersEmojis, + PermissionRemoveUserFromTeam, + PermissionManageTeam, + PermissionImportTeam, + PermissionViewTeam, + PermissionViewMembers, + PermissionInviteGuest, } ChannelScopedPermissions := []*Permission{ - PERMISSION_USE_SLASH_COMMANDS, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS, - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS, - PERMISSION_MANAGE_CHANNEL_ROLES, - PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES, - PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES, - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE, - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC, - PERMISSION_DELETE_PUBLIC_CHANNEL, - PERMISSION_DELETE_PRIVATE_CHANNEL, - PERMISSION_READ_CHANNEL, - PERMISSION_READ_PUBLIC_CHANNEL_GROUPS, - PERMISSION_READ_PRIVATE_CHANNEL_GROUPS, - PERMISSION_ADD_REACTION, - PERMISSION_REMOVE_REACTION, - PERMISSION_REMOVE_OTHERS_REACTIONS, - PERMISSION_UPLOAD_FILE, - PERMISSION_CREATE_POST, - PERMISSION_CREATE_POST_PUBLIC, - PERMISSION_CREATE_POST_EPHEMERAL, - PERMISSION_EDIT_POST, - PERMISSION_EDIT_OTHERS_POSTS, - PERMISSION_DELETE_POST, - PERMISSION_DELETE_OTHERS_POSTS, - PERMISSION_USE_CHANNEL_MENTIONS, - PERMISSION_USE_GROUP_MENTIONS, + PermissionUseSlashCommands, + PermissionManagePublicChannelMembers, + PermissionManagePrivateChannelMembers, + PermissionManageChannelRoles, + PermissionManagePublicChannelProperties, + PermissionManagePrivateChannelProperties, + PermissionConvertPublicChannelToPrivate, + PermissionConvertPrivateChannelToPublic, + PermissionDeletePublicChannel, + PermissionDeletePrivateChannel, + PermissionReadChannel, + PermissionReadPublicChannelGroups, + PermissionReadPrivateChannelGroups, + PermissionAddReaction, + PermissionRemoveReaction, + PermissionRemoveOthersReactions, + PermissionUploadFile, + PermissionCreatePost, + PermissionCreatePostPublic, + PermissionCreatePostEphemeral, + PermissionEditPost, + PermissionEditOthersPosts, + PermissionDeletePost, + PermissionDeleteOthersPosts, + PermissionUseChannelMentions, + PermissionUseGroupMentions, } DeprecatedPermissions = []*Permission{ - PERMISSION_PERMANENT_DELETE_USER, - PERMISSION_MANAGE_WEBHOOKS, - PERMISSION_MANAGE_OTHERS_WEBHOOKS, - PERMISSION_MANAGE_EMOJIS, - PERMISSION_MANAGE_OTHERS_EMOJIS, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION, - PERMISSION_SYSCONSOLE_READ_SITE, - PERMISSION_SYSCONSOLE_WRITE_SITE, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT, - PERMISSION_SYSCONSOLE_READ_REPORTING, - PERMISSION_SYSCONSOLE_WRITE_REPORTING, - PERMISSION_SYSCONSOLE_READ_ABOUT, - PERMISSION_SYSCONSOLE_WRITE_ABOUT, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL, - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE, + PermissionPermanentDeleteUser, + PermissionManageWebhooks, + PermissionManageOthersWebhooks, + PermissionManageEmojis, + PermissionManageOthersEmojis, + PermissionSysconsoleReadAuthentication, + PermissionSysconsoleWriteAuthentication, + PermissionSysconsoleReadSite, + PermissionSysconsoleWriteSite, + PermissionSysconsoleReadEnvironment, + PermissionSysconsoleWriteEnvironment, + PermissionSysconsoleReadReporting, + PermissionSysconsoleWriteReporting, + PermissionSysconsoleReadAbout, + PermissionSysconsoleWriteAbout, + PermissionSysconsoleReadExperimental, + PermissionSysconsoleWriteExperimental, + PermissionSysconsoleReadIntegrations, + PermissionSysconsoleWriteIntegrations, + PermissionSysconsoleReadCompliance, + PermissionSysconsoleWriteCompliance, } AllPermissions = []*Permission{} @@ -2171,19 +2171,19 @@ func initializePermissions() { AllPermissions = append(AllPermissions, SysconsoleWritePermissions...) ChannelModeratedPermissions = []string{ - PERMISSION_CREATE_POST.Id, + PermissionCreatePost.Id, "create_reactions", "manage_members", - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionUseChannelMentions.Id, } ChannelModeratedPermissionsMap = map[string]string{ - PERMISSION_CREATE_POST.Id: ChannelModeratedPermissions[0], - PERMISSION_ADD_REACTION.Id: ChannelModeratedPermissions[1], - PERMISSION_REMOVE_REACTION.Id: ChannelModeratedPermissions[1], - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id: ChannelModeratedPermissions[2], - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id: ChannelModeratedPermissions[2], - PERMISSION_USE_CHANNEL_MENTIONS.Id: ChannelModeratedPermissions[3], + PermissionCreatePost.Id: ChannelModeratedPermissions[0], + PermissionAddReaction.Id: ChannelModeratedPermissions[1], + PermissionRemoveReaction.Id: ChannelModeratedPermissions[1], + PermissionManagePublicChannelMembers.Id: ChannelModeratedPermissions[2], + PermissionManagePrivateChannelMembers.Id: ChannelModeratedPermissions[2], + PermissionUseChannelMentions.Id: ChannelModeratedPermissions[3], } } diff --git a/model/plugin_cluster_event.go b/model/plugin_cluster_event.go index ba5c805278..9e227447e3 100644 --- a/model/plugin_cluster_event.go +++ b/model/plugin_cluster_event.go @@ -4,8 +4,8 @@ package model const ( - PluginClusterEventSendTypeReliable = CLUSTER_SEND_RELIABLE - PluginClusterEventSendTypeBestEffort = CLUSTER_SEND_BEST_EFFORT + PluginClusterEventSendTypeReliable = ClusterSendReliable + PluginClusterEventSendTypeBestEffort = ClusterSendBestEffort ) // PluginClusterEvent is used to allow intra-cluster plugin communication. diff --git a/model/plugin_key_value.go b/model/plugin_key_value.go index 73ef2d2321..ad5971dd54 100644 --- a/model/plugin_key_value.go +++ b/model/plugin_key_value.go @@ -9,8 +9,8 @@ import ( ) const ( - KEY_VALUE_PLUGIN_ID_MAX_RUNES = 190 - KEY_VALUE_KEY_MAX_RUNES = 50 + KeyValuePluginIdMaxRunes = 190 + KeyValueKeyMaxRunes = 50 ) type PluginKeyValue struct { @@ -21,12 +21,12 @@ type PluginKeyValue struct { } func (kv *PluginKeyValue) IsValid() *AppError { - if kv.PluginId == "" || utf8.RuneCountInString(kv.PluginId) > KEY_VALUE_PLUGIN_ID_MAX_RUNES { - return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) + if kv.PluginId == "" || utf8.RuneCountInString(kv.PluginId) > KeyValuePluginIdMaxRunes { + return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.plugin_id.app_error", map[string]interface{}{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } - if kv.Key == "" || utf8.RuneCountInString(kv.Key) > KEY_VALUE_KEY_MAX_RUNES { - return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KEY_VALUE_KEY_MAX_RUNES, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) + if kv.Key == "" || utf8.RuneCountInString(kv.Key) > KeyValueKeyMaxRunes { + return NewAppError("PluginKeyValue.IsValid", "model.plugin_key_value.is_valid.key.app_error", map[string]interface{}{"Max": KeyValueKeyMaxRunes, "Min": 0}, "key="+kv.Key, http.StatusBadRequest) } return nil diff --git a/model/post.go b/model/post.go index 74bd1e813d..9ac73e0423 100644 --- a/model/post.go +++ b/model/post.go @@ -18,56 +18,58 @@ import ( ) const ( - POST_SYSTEM_MESSAGE_PREFIX = "system_" - POST_DEFAULT = "" - POST_SLACK_ATTACHMENT = "slack_attachment" - POST_SYSTEM_GENERIC = "system_generic" - POST_JOIN_LEAVE = "system_join_leave" // Deprecated, use POST_JOIN_CHANNEL or POST_LEAVE_CHANNEL instead - POST_JOIN_CHANNEL = "system_join_channel" - POST_GUEST_JOIN_CHANNEL = "system_guest_join_channel" - POST_LEAVE_CHANNEL = "system_leave_channel" - POST_JOIN_TEAM = "system_join_team" - POST_LEAVE_TEAM = "system_leave_team" - POST_AUTO_RESPONDER = "system_auto_responder" - POST_ADD_REMOVE = "system_add_remove" // Deprecated, use POST_ADD_TO_CHANNEL or POST_REMOVE_FROM_CHANNEL instead - POST_ADD_TO_CHANNEL = "system_add_to_channel" - POST_ADD_GUEST_TO_CHANNEL = "system_add_guest_to_chan" - POST_REMOVE_FROM_CHANNEL = "system_remove_from_channel" - POST_MOVE_CHANNEL = "system_move_channel" - POST_ADD_TO_TEAM = "system_add_to_team" - POST_REMOVE_FROM_TEAM = "system_remove_from_team" - POST_HEADER_CHANGE = "system_header_change" - POST_DISPLAYNAME_CHANGE = "system_displayname_change" - POST_CONVERT_CHANNEL = "system_convert_channel" - POST_PURPOSE_CHANGE = "system_purpose_change" - POST_CHANNEL_DELETED = "system_channel_deleted" - POST_CHANNEL_RESTORED = "system_channel_restored" - POST_EPHEMERAL = "system_ephemeral" - POST_CHANGE_CHANNEL_PRIVACY = "system_change_chan_privacy" - POST_ADD_BOT_TEAMS_CHANNELS = "add_bot_teams_channels" - POST_FILEIDS_MAX_RUNES = 300 - POST_FILENAMES_MAX_RUNES = 4000 - POST_HASHTAGS_MAX_RUNES = 1000 - POST_MESSAGE_MAX_RUNES_V1 = 4000 - POST_MESSAGE_MAX_BYTES_V2 = 65535 // Maximum size of a TEXT column in MySQL - POST_MESSAGE_MAX_RUNES_V2 = POST_MESSAGE_MAX_BYTES_V2 / 4 // Assume a worst-case representation - POST_PROPS_MAX_RUNES = 8000 - POST_PROPS_MAX_USER_RUNES = POST_PROPS_MAX_RUNES - 400 // Leave some room for system / pre-save modifications - POST_CUSTOM_TYPE_PREFIX = "custom_" - POST_ME = "me" - PROPS_ADD_CHANNEL_MEMBER = "add_channel_member" + PostSystemMessagePrefix = "system_" + PostTypeDefault = "" + PostTypeSlackAttachment = "slack_attachment" + PostTypeSystemGeneric = "system_generic" + PostTypeJoinLeave = "system_join_leave" // Deprecated, use PostJoinChannel or PostLeaveChannel instead + PostTypeJoinChannel = "system_join_channel" + PostTypeGuestJoinChannel = "system_guest_join_channel" + PostTypeLeaveChannel = "system_leave_channel" + PostTypeJoinTeam = "system_join_team" + PostTypeLeaveTeam = "system_leave_team" + PostTypeAutoResponder = "system_auto_responder" + PostTypeAddRemove = "system_add_remove" // Deprecated, use PostAddToChannel or PostRemoveFromChannel instead + PostTypeAddToChannel = "system_add_to_channel" + PostTypeAddGuestToChannel = "system_add_guest_to_chan" + PostTypeRemoveFromChannel = "system_remove_from_channel" + PostTypeMoveChannel = "system_move_channel" + PostTypeAddToTeam = "system_add_to_team" + PostTypeRemoveFromTeam = "system_remove_from_team" + PostTypeHeaderChange = "system_header_change" + PostTypeDisplaynameChange = "system_displayname_change" + PostTypeConvertChannel = "system_convert_channel" + PostTypePurposeChange = "system_purpose_change" + PostTypeChannelDeleted = "system_channel_deleted" + PostTypeChannelRestored = "system_channel_restored" + PostTypeEphemeral = "system_ephemeral" + PostTypeChangeChannelPrivacy = "system_change_chan_privacy" + PostTypeAddBotTeamsChannels = "add_bot_teams_channels" + PostTypeSystemWarnMetricStatus = "warn_metric_status" + PostTypeMe = "me" + PostCustomTypePrefix = "custom_" - POST_PROPS_ADDED_USER_ID = "addedUserId" - POST_PROPS_DELETE_BY = "deleteBy" - POST_PROPS_OVERRIDE_ICON_URL = "override_icon_url" - POST_PROPS_OVERRIDE_ICON_EMOJI = "override_icon_emoji" + PostFileidsMaxRunes = 300 + PostFilenamesMaxRunes = 4000 + PostHashtagsMaxRunes = 1000 + PostMessageMaxRunesV1 = 4000 + PostMessageMaxBytesV2 = 65535 // Maximum size of a TEXT column in MySQL + PostMessageMaxRunesV2 = PostMessageMaxBytesV2 / 4 // Assume a worst-case representation + PostPropsMaxRunes = 8000 + PostPropsMaxUserRunes = PostPropsMaxRunes - 400 // Leave some room for system / pre-save modifications - POST_PROPS_MENTION_HIGHLIGHT_DISABLED = "mentionHighlightDisabled" - POST_PROPS_GROUP_HIGHLIGHT_DISABLED = "disable_group_highlight" - POST_SYSTEM_WARN_METRIC_STATUS = "warn_metric_status" + PropsAddChannelMember = "add_channel_member" + + PostPropsAddedUserId = "addedUserId" + PostPropsDeleteBy = "deleteBy" + PostPropsOverrideIconUrl = "override_icon_url" + PostPropsOverrideIconEmoji = "override_icon_emoji" + + PostPropsMentionHighlightDisabled = "mentionHighlightDisabled" + PostPropsGroupHighlightDisabled = "disable_group_highlight" ) -var AT_MENTION_PATTEN = regexp.MustCompile(`\B@`) +var AtMentionPattern = regexp.MustCompile(`\B@`) type Post struct { Id string `json:"id"` @@ -316,54 +318,54 @@ func (o *Post) IsValid(maxPostSize int) *AppError { return NewAppError("Post.IsValid", "model.post.is_valid.msg.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(o.Hashtags) > POST_HASHTAGS_MAX_RUNES { + if utf8.RuneCountInString(o.Hashtags) > PostHashtagsMaxRunes { return NewAppError("Post.IsValid", "model.post.is_valid.hashtags.app_error", nil, "id="+o.Id, http.StatusBadRequest) } switch o.Type { case - POST_DEFAULT, - POST_SYSTEM_GENERIC, - POST_JOIN_LEAVE, - POST_AUTO_RESPONDER, - POST_ADD_REMOVE, - POST_JOIN_CHANNEL, - POST_GUEST_JOIN_CHANNEL, - POST_LEAVE_CHANNEL, - POST_JOIN_TEAM, - POST_LEAVE_TEAM, - POST_ADD_TO_CHANNEL, - POST_ADD_GUEST_TO_CHANNEL, - POST_REMOVE_FROM_CHANNEL, - POST_MOVE_CHANNEL, - POST_ADD_TO_TEAM, - POST_REMOVE_FROM_TEAM, - POST_SLACK_ATTACHMENT, - POST_HEADER_CHANGE, - POST_PURPOSE_CHANGE, - POST_DISPLAYNAME_CHANGE, - POST_CONVERT_CHANNEL, - POST_CHANNEL_DELETED, - POST_CHANNEL_RESTORED, - POST_CHANGE_CHANNEL_PRIVACY, - POST_ME, - POST_ADD_BOT_TEAMS_CHANNELS, - POST_SYSTEM_WARN_METRIC_STATUS: + PostTypeDefault, + PostTypeSystemGeneric, + PostTypeJoinLeave, + PostTypeAutoResponder, + PostTypeAddRemove, + PostTypeJoinChannel, + PostTypeGuestJoinChannel, + PostTypeLeaveChannel, + PostTypeJoinTeam, + PostTypeLeaveTeam, + PostTypeAddToChannel, + PostTypeAddGuestToChannel, + PostTypeRemoveFromChannel, + PostTypeMoveChannel, + PostTypeAddToTeam, + PostTypeRemoveFromTeam, + PostTypeSlackAttachment, + PostTypeHeaderChange, + PostTypePurposeChange, + PostTypeDisplaynameChange, + PostTypeConvertChannel, + PostTypeChannelDeleted, + PostTypeChannelRestored, + PostTypeChangeChannelPrivacy, + PostTypeAddBotTeamsChannels, + PostTypeSystemWarnMetricStatus, + PostTypeMe: default: - if !strings.HasPrefix(o.Type, POST_CUSTOM_TYPE_PREFIX) { + if !strings.HasPrefix(o.Type, PostCustomTypePrefix) { return NewAppError("Post.IsValid", "model.post.is_valid.type.app_error", nil, "id="+o.Type, http.StatusBadRequest) } } - if utf8.RuneCountInString(ArrayToJson(o.Filenames)) > POST_FILENAMES_MAX_RUNES { + if utf8.RuneCountInString(ArrayToJson(o.Filenames)) > PostFilenamesMaxRunes { return NewAppError("Post.IsValid", "model.post.is_valid.filenames.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(ArrayToJson(o.FileIds)) > POST_FILEIDS_MAX_RUNES { + if utf8.RuneCountInString(ArrayToJson(o.FileIds)) > PostFileidsMaxRunes { return NewAppError("Post.IsValid", "model.post.is_valid.file_ids.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(StringInterfaceToJson(o.GetProps())) > POST_PROPS_MAX_RUNES { + if utf8.RuneCountInString(StringInterfaceToJson(o.GetProps())) > PostPropsMaxRunes { return NewAppError("Post.IsValid", "model.post.is_valid.props.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -375,7 +377,7 @@ func (o *Post) SanitizeProps() { return } membersToSanitize := []string{ - PROPS_ADD_CHANNEL_MEMBER, + PropsAddChannelMember, } for _, member := range membersToSanitize { @@ -469,7 +471,7 @@ func (o *Post) GetProp(key string) interface{} { } func (o *Post) IsSystemMessage() bool { - return len(o.Type) >= len(POST_SYSTEM_MESSAGE_PREFIX) && o.Type[:len(POST_SYSTEM_MESSAGE_PREFIX)] == POST_SYSTEM_MESSAGE_PREFIX + return len(o.Type) >= len(PostSystemMessagePrefix) && o.Type[:len(PostSystemMessagePrefix)] == PostSystemMessagePrefix } // IsRemote returns true if the post originated on a remote cluster. @@ -486,16 +488,16 @@ func (o *Post) GetRemoteID() string { } func (o *Post) IsJoinLeaveMessage() bool { - return o.Type == POST_JOIN_LEAVE || - o.Type == POST_ADD_REMOVE || - o.Type == POST_JOIN_CHANNEL || - o.Type == POST_LEAVE_CHANNEL || - o.Type == POST_JOIN_TEAM || - o.Type == POST_LEAVE_TEAM || - o.Type == POST_ADD_TO_CHANNEL || - o.Type == POST_REMOVE_FROM_CHANNEL || - o.Type == POST_ADD_TO_TEAM || - o.Type == POST_REMOVE_FROM_TEAM + return o.Type == PostTypeJoinLeave || + o.Type == PostTypeAddRemove || + o.Type == PostTypeJoinChannel || + o.Type == PostTypeLeaveChannel || + o.Type == PostTypeJoinTeam || + o.Type == PostTypeLeaveTeam || + o.Type == PostTypeAddToChannel || + o.Type == PostTypeRemoveFromChannel || + o.Type == PostTypeAddToTeam || + o.Type == PostTypeRemoveFromTeam } func (o *Post) Patch(patch *PostPatch) { @@ -568,7 +570,7 @@ func (o *Post) ChannelMentions() []string { func (o *Post) DisableMentionHighlights() string { mention, hasMentions := findAtChannelMention(o.Message) if hasMentions { - o.AddProp(POST_PROPS_MENTION_HIGHLIGHT_DISABLED, true) + o.AddProp(PostPropsMentionHighlightDisabled, true) } return mention } @@ -582,7 +584,7 @@ func (o *PostPatch) DisableMentionHighlights() { if o.Props == nil { o.Props = &StringInterface{} } - (*o.Props)[POST_PROPS_MENTION_HIGHLIGHT_DISABLED] = true + (*o.Props)[PostPropsMentionHighlightDisabled] = true } } diff --git a/model/post_embed.go b/model/post_embed.go index 5c6efec1f3..8df923d256 100644 --- a/model/post_embed.go +++ b/model/post_embed.go @@ -4,10 +4,10 @@ package model const ( - POST_EMBED_IMAGE PostEmbedType = "image" - POST_EMBED_MESSAGE_ATTACHMENT PostEmbedType = "message_attachment" - POST_EMBED_OPENGRAPH PostEmbedType = "opengraph" - POST_EMBED_LINK PostEmbedType = "link" + PostEmbedImage PostEmbedType = "image" + PostEmbedMessageAttachment PostEmbedType = "message_attachment" + PostEmbedOpengraph PostEmbedType = "opengraph" + PostEmbedLink PostEmbedType = "link" ) type PostEmbedType string diff --git a/model/post_test.go b/model/post_test.go index 12f049b288..44281deef3 100644 --- a/model/post_test.go +++ b/model/post_test.go @@ -81,7 +81,7 @@ func TestPostIsValid(t *testing.T) { err = o.IsValid(maxPostSize) require.NotNil(t, err) - o.Type = POST_CUSTOM_TYPE_PREFIX + "type" + o.Type = PostCustomTypePrefix + "type" err = o.IsValid(maxPostSize) require.Nil(t, err) } @@ -107,7 +107,7 @@ func TestPostIsSystemMessage(t *testing.T) { require.False(t, post1.IsSystemMessage()) - post2 := Post{Message: "test_2", Type: POST_JOIN_LEAVE} + post2 := Post{Message: "test_2", Type: PostTypeJoinLeave} post2.PreSave() require.True(t, post2.IsSystemMessage()) @@ -125,30 +125,30 @@ func TestPostSanitizeProps(t *testing.T) { post1.SanitizeProps() - require.Nil(t, post1.GetProp(PROPS_ADD_CHANNEL_MEMBER)) + require.Nil(t, post1.GetProp(PropsAddChannelMember)) post2 := &Post{ Message: "test", Props: StringInterface{ - PROPS_ADD_CHANNEL_MEMBER: "test", + PropsAddChannelMember: "test", }, } post2.SanitizeProps() - require.Nil(t, post2.GetProp(PROPS_ADD_CHANNEL_MEMBER)) + require.Nil(t, post2.GetProp(PropsAddChannelMember)) post3 := &Post{ Message: "test", Props: StringInterface{ - PROPS_ADD_CHANNEL_MEMBER: "no good", - "attachments": "good", + PropsAddChannelMember: "no good", + "attachments": "good", }, } post3.SanitizeProps() - require.Nil(t, post3.GetProp(PROPS_ADD_CHANNEL_MEMBER)) + require.Nil(t, post3.GetProp(PropsAddChannelMember)) require.NotNil(t, post3.GetProp("attachments")) } @@ -778,21 +778,21 @@ func TestPostDisableMentionHighlights(t *testing.T) { "", }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED and returns mention", + "Sets PostPropsMentionHighlightDisabled and returns mention", "Sample message with @here", - StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + StringInterface{PostPropsMentionHighlightDisabled: true}, "@here", }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED and returns mention", + "Sets PostPropsMentionHighlightDisabled and returns mention", "Sample message with @channel", - StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + StringInterface{PostPropsMentionHighlightDisabled: true}, "@channel", }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED and returns mention", + "Sets PostPropsMentionHighlightDisabled and returns mention", "Sample message with @all", - StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + StringInterface{PostPropsMentionHighlightDisabled: true}, "@all", }, } @@ -821,19 +821,19 @@ func TestPostPatchDisableMentionHighlights(t *testing.T) { nil, }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED", + "Sets PostPropsMentionHighlightDisabled", "Sample message with @here", - &StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + &StringInterface{PostPropsMentionHighlightDisabled: true}, }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED", + "Sets PostPropsMentionHighlightDisabled", "Sample message with @channel", - &StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + &StringInterface{PostPropsMentionHighlightDisabled: true}, }, { - "Sets POST_PROPS_MENTION_HIGHLIGHT_DISABLED", + "Sets PostPropsMentionHighlightDisabled", "Sample message with @all", - &StringInterface{POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true}, + &StringInterface{PostPropsMentionHighlightDisabled: true}, }, } for _, tc := range testCases { diff --git a/model/preference.go b/model/preference.go index 9ba9b60b68..4335962948 100644 --- a/model/preference.go +++ b/model/preference.go @@ -13,48 +13,48 @@ import ( ) const ( - PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW = "direct_channel_show" - PREFERENCE_CATEGORY_GROUP_CHANNEL_SHOW = "group_channel_show" - PREFERENCE_CATEGORY_TUTORIAL_STEPS = "tutorial_step" - PREFERENCE_CATEGORY_ADVANCED_SETTINGS = "advanced_settings" - PREFERENCE_CATEGORY_FLAGGED_POST = "flagged_post" - PREFERENCE_CATEGORY_FAVORITE_CHANNEL = "favorite_channel" - PREFERENCE_CATEGORY_SIDEBAR_SETTINGS = "sidebar_settings" + PreferenceCategoryDirectChannelShow = "direct_channel_show" + PreferenceCategoryGroupChannelShow = "group_channel_show" + PreferenceCategoryTutorialSteps = "tutorial_step" + PreferenceCategoryAdvancedSettings = "advanced_settings" + PreferenceCategoryFlaggedPost = "flagged_post" + PreferenceCategoryFavoriteChannel = "favorite_channel" + PreferenceCategorySidebarSettings = "sidebar_settings" - PREFERENCE_CATEGORY_DISPLAY_SETTINGS = "display_settings" - PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED = "collapsed_reply_threads" - PREFERENCE_NAME_CHANNEL_DISPLAY_MODE = "channel_display_mode" - PREFERENCE_NAME_COLLAPSE_SETTING = "collapse_previews" - PREFERENCE_NAME_MESSAGE_DISPLAY = "message_display" - PREFERENCE_NAME_NAME_FORMAT = "name_format" - PREFERENCE_NAME_USE_MILITARY_TIME = "use_military_time" + PreferenceCategoryDisplaySettings = "display_settings" + PreferenceNameCollapsedThreadsEnabled = "collapsed_reply_threads" + PreferenceNameChannelDisplayMode = "channel_display_mode" + PreferenceNameCollapseSetting = "collapse_previews" + PreferenceNameMessageDisplay = "message_display" + PreferenceNameNameFormat = "name_format" + PreferenceNameUseMilitaryTime = "use_military_time" - PREFERENCE_CATEGORY_THEME = "theme" + PreferenceCategoryTheme = "theme" // the name for theme props is the team id - PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP = "oauth_app" + PreferenceCategoryAuthorizedOAuthApp = "oauth_app" // the name for oauth_app is the client_id and value is the current scope - PREFERENCE_CATEGORY_LAST = "last" - PREFERENCE_NAME_LAST_CHANNEL = "channel" - PREFERENCE_NAME_LAST_TEAM = "team" + PreferenceCategoryLast = "last" + PreferenceNameLastChannel = "channel" + PreferenceNameLastTeam = "team" - PREFERENCE_CATEGORY_CUSTOM_STATUS = "custom_status" - PREFERENCE_NAME_RECENT_CUSTOM_STATUSES = "recent_custom_statuses" - PREFERENCE_NAME_CUSTOM_STATUS_TUTORIAL_STATE = "custom_status_tutorial_state" + PreferenceCategoryCustomStatus = "custom_status" + PreferenceNameRecentCustomStatuses = "recent_custom_statuses" + PreferenceNameCustomStatusTutorialState = "custom_status_tutorial_state" - PREFERENCE_CUSTOM_STATUS_MODAL_VIEWED = "custom_status_modal_viewed" + PreferenceCustomStatusModalViewed = "custom_status_modal_viewed" - PREFERENCE_CATEGORY_NOTIFICATIONS = "notifications" - PREFERENCE_NAME_EMAIL_INTERVAL = "email_interval" + PreferenceCategoryNotifications = "notifications" + PreferenceNameEmailInterval = "email_interval" - PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS = "30" // the "immediate" setting is actually 30s - PREFERENCE_EMAIL_INTERVAL_BATCHING_SECONDS = "900" // fifteen minutes is 900 seconds - PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY = "immediately" - PREFERENCE_EMAIL_INTERVAL_FIFTEEN = "fifteen" - PREFERENCE_EMAIL_INTERVAL_FIFTEEN_AS_SECONDS = "900" - PREFERENCE_EMAIL_INTERVAL_HOUR = "hour" - PREFERENCE_EMAIL_INTERVAL_HOUR_AS_SECONDS = "3600" + PreferenceEmailIntervalNoBatchingSeconds = "30" // the "immediate" setting is actually 30s + PreferenceEmailIntervalBatchingSeconds = "900" // fifteen minutes is 900 seconds + PreferenceEmailIntervalImmediately = "immediately" + PreferenceEmailIntervalFifteen = "fifteen" + PreferenceEmailIntervalFifteenAsSeconds = "900" + PreferenceEmailIntervalHour = "hour" + PreferenceEmailIntervalHourAsSeconds = "3600" ) type Preference struct { @@ -92,7 +92,7 @@ func (o *Preference) IsValid() *AppError { return NewAppError("Preference.IsValid", "model.preference.is_valid.value.app_error", nil, "value="+o.Value, http.StatusBadRequest) } - if o.Category == PREFERENCE_CATEGORY_THEME { + if o.Category == PreferenceCategoryTheme { var unused map[string]string if err := json.NewDecoder(strings.NewReader(o.Value)).Decode(&unused); err != nil { return NewAppError("Preference.IsValid", "model.preference.is_valid.theme.app_error", nil, "value="+o.Value, http.StatusBadRequest) @@ -103,7 +103,7 @@ func (o *Preference) IsValid() *AppError { } func (o *Preference) PreUpdate() { - if o.Category == PREFERENCE_CATEGORY_THEME { + if o.Category == PreferenceCategoryTheme { // decode the value of theme (a map of strings to string) and eliminate any invalid values var props map[string]string if err := json.NewDecoder(strings.NewReader(o.Value)).Decode(&props); err != nil { diff --git a/model/preference_test.go b/model/preference_test.go index 58da91fa03..b922ac19b1 100644 --- a/model/preference_test.go +++ b/model/preference_test.go @@ -14,7 +14,7 @@ import ( func TestPreferenceIsValid(t *testing.T) { preference := Preference{ UserId: "1234garbage", - Category: PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: PreferenceCategoryDirectChannelShow, Name: NewId(), } @@ -26,7 +26,7 @@ func TestPreferenceIsValid(t *testing.T) { preference.Category = strings.Repeat("01234567890", 20) require.NotNil(t, preference.IsValid()) - preference.Category = PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW + preference.Category = PreferenceCategoryDirectChannelShow require.Nil(t, preference.IsValid()) preference.Name = strings.Repeat("01234567890", 20) @@ -41,7 +41,7 @@ func TestPreferenceIsValid(t *testing.T) { preference.Value = "1234garbage" require.Nil(t, preference.IsValid()) - preference.Category = PREFERENCE_CATEGORY_THEME + preference.Category = PreferenceCategoryTheme require.NotNil(t, preference.IsValid()) preference.Value = `{"color": "#ff0000", "color2": "#faf"}` @@ -50,7 +50,7 @@ func TestPreferenceIsValid(t *testing.T) { func TestPreferencePreUpdate(t *testing.T) { preference := Preference{ - Category: PREFERENCE_CATEGORY_THEME, + Category: PreferenceCategoryTheme, Value: `{"color": "#ff0000", "color2": "#faf", "codeTheme": "github", "invalid": "invalid"}`, } diff --git a/model/product_notices.go b/model/product_notices.go index 455ae47568..94343cb4c4 100644 --- a/model/product_notices.go +++ b/model/product_notices.go @@ -32,11 +32,11 @@ type ProductNotice struct { } func (n *ProductNotice) SysAdminOnly() bool { - return n.Conditions.Audience != nil && *n.Conditions.Audience == NoticeAudience_Sysadmin + return n.Conditions.Audience != nil && *n.Conditions.Audience == NoticeAudienceSysadmin } func (n *ProductNotice) TeamAdminOnly() bool { - return n.Conditions.Audience != nil && *n.Conditions.Audience == NoticeAudience_TeamAdmin + return n.Conditions.Audience != nil && *n.Conditions.Audience == NoticeAudienceTeamAdmin } type Conditions struct { @@ -91,23 +91,23 @@ func NewNoticeAudience(s NoticeAudience) *NoticeAudience { func (a *NoticeAudience) Matches(sysAdmin bool, teamAdmin bool) bool { switch *a { - case NoticeAudience_All: + case NoticeAudienceAll: return true - case NoticeAudience_Member: + case NoticeAudienceMember: return !sysAdmin && !teamAdmin - case NoticeAudience_Sysadmin: + case NoticeAudienceSysadmin: return sysAdmin - case NoticeAudience_TeamAdmin: + case NoticeAudienceTeamAdmin: return teamAdmin } return false } const ( - NoticeAudience_All NoticeAudience = "all" - NoticeAudience_Member NoticeAudience = "member" - NoticeAudience_Sysadmin NoticeAudience = "sysadmin" - NoticeAudience_TeamAdmin NoticeAudience = "teamadmin" + NoticeAudienceAll NoticeAudience = "all" + NoticeAudienceMember NoticeAudience = "member" + NoticeAudienceSysadmin NoticeAudience = "sysadmin" + NoticeAudienceTeamAdmin NoticeAudience = "teamadmin" ) // Only show the notice on specific clients. Defaults to 'all' @@ -119,36 +119,36 @@ func NewNoticeClientType(s NoticeClientType) *NoticeClientType { return &s } func (c *NoticeClientType) Matches(other NoticeClientType) bool { switch *c { - case NoticeClientType_All: + case NoticeClientTypeAll: return true - case NoticeClientType_Mobile: - return other == NoticeClientType_MobileIos || other == NoticeClientType_MobileAndroid + case NoticeClientTypeMobile: + return other == NoticeClientTypeMobileIos || other == NoticeClientTypeMobileAndroid default: return *c == other } } const ( - NoticeClientType_All NoticeClientType = "all" - NoticeClientType_Desktop NoticeClientType = "desktop" - NoticeClientType_Mobile NoticeClientType = "mobile" - NoticeClientType_MobileAndroid NoticeClientType = "mobile-android" - NoticeClientType_MobileIos NoticeClientType = "mobile-ios" - NoticeClientType_Web NoticeClientType = "web" + NoticeClientTypeAll NoticeClientType = "all" + NoticeClientTypeDesktop NoticeClientType = "desktop" + NoticeClientTypeMobile NoticeClientType = "mobile" + NoticeClientTypeMobileAndroid NoticeClientType = "mobile-android" + NoticeClientTypeMobileIos NoticeClientType = "mobile-ios" + NoticeClientTypeWeb NoticeClientType = "web" ) func NoticeClientTypeFromString(s string) (NoticeClientType, error) { switch s { case "web": - return NoticeClientType_Web, nil + return NoticeClientTypeWeb, nil case "mobile-ios": - return NoticeClientType_MobileIos, nil + return NoticeClientTypeMobileIos, nil case "mobile-android": - return NoticeClientType_MobileAndroid, nil + return NoticeClientTypeMobileAndroid, nil case "desktop": - return NoticeClientType_Desktop, nil + return NoticeClientTypeDesktop, nil } - return NoticeClientType_All, errors.New("Invalid client type supplied") + return NoticeClientTypeAll, errors.New("Invalid client type supplied") } // Instance type. Defaults to "both" @@ -156,22 +156,22 @@ type NoticeInstanceType string func NewNoticeInstanceType(n NoticeInstanceType) *NoticeInstanceType { return &n } func (t *NoticeInstanceType) Matches(isCloud bool) bool { - if *t == NoticeInstanceType_Both { + if *t == NoticeInstanceTypeBoth { return true } - if *t == NoticeInstanceType_Cloud && !isCloud { + if *t == NoticeInstanceTypeCloud && !isCloud { return false } - if *t == NoticeInstanceType_OnPrem && isCloud { + if *t == NoticeInstanceTypeOnPrem && isCloud { return false } return true } const ( - NoticeInstanceType_Both NoticeInstanceType = "both" - NoticeInstanceType_Cloud NoticeInstanceType = "cloud" - NoticeInstanceType_OnPrem NoticeInstanceType = "onprem" + NoticeInstanceTypeBoth NoticeInstanceType = "both" + NoticeInstanceTypeCloud NoticeInstanceType = "cloud" + NoticeInstanceTypeOnPrem NoticeInstanceType = "onprem" ) // SKU. Defaults to "all" @@ -180,9 +180,9 @@ type NoticeSKU string func NewNoticeSKU(s NoticeSKU) *NoticeSKU { return &s } func (c *NoticeSKU) Matches(s string) bool { switch *c { - case NoticeSKU_All: + case NoticeSKUAll: return true - case NoticeSKU_E0, NoticeSKU_Team: + case NoticeSKUE0, NoticeSKUTeam: return s == "" default: return s == string(*c) @@ -190,11 +190,11 @@ func (c *NoticeSKU) Matches(s string) bool { } const ( - NoticeSKU_E0 NoticeSKU = "e0" - NoticeSKU_E10 NoticeSKU = "e10" - NoticeSKU_E20 NoticeSKU = "e20" - NoticeSKU_All NoticeSKU = "all" - NoticeSKU_Team NoticeSKU = "team" + NoticeSKUE0 NoticeSKU = "e0" + NoticeSKUE10 NoticeSKU = "e10" + NoticeSKUE20 NoticeSKU = "e20" + NoticeSKUAll NoticeSKU = "all" + NoticeSKUTeam NoticeSKU = "team" ) // Optional action to perform on action button click. (defaults to closing the notice) diff --git a/model/push_notification.go b/model/push_notification.go index 2a0dc65861..59bf982cb0 100644 --- a/model/push_notification.go +++ b/model/push_notification.go @@ -11,29 +11,29 @@ import ( ) const ( - PUSH_NOTIFY_APPLE = "apple" - PUSH_NOTIFY_ANDROID = "android" - PUSH_NOTIFY_APPLE_REACT_NATIVE = "apple_rn" - PUSH_NOTIFY_ANDROID_REACT_NATIVE = "android_rn" + PushNotifyApple = "apple" + PushNotifyAndroid = "android" + PushNotifyAppleReactNative = "apple_rn" + PushNotifyAndroidReactNative = "android_rn" - PUSH_TYPE_MESSAGE = "message" - PUSH_TYPE_CLEAR = "clear" - PUSH_TYPE_UPDATE_BADGE = "update_badge" - PUSH_TYPE_SESSION = "session" - PUSH_MESSAGE_V2 = "v2" + PushTypeMessage = "message" + PushTypeClear = "clear" + PushTypeUpdateBadge = "update_badge" + PushTypeSession = "session" + PushMessageV2 = "v2" - PUSH_SOUND_NONE = "none" + PushSoundNone = "none" // The category is set to handle a set of interactive Actions // with the push notifications - CATEGORY_CAN_REPLY = "CAN_REPLY" + CategoryCanReply = "CAN_REPLY" MHPNS = "https://push.mattermost.com" - PUSH_SEND_PREPARE = "Prepared to send" - PUSH_SEND_SUCCESS = "Successful" - PUSH_NOT_SENT = "Not Sent due to preferences" - PUSH_RECEIVED = "Received by device" + PushSendPrepare = "Prepared to send" + PushSendSuccess = "Successful" + PushNotSent = "Not Sent due to preferences" + PushReceived = "Received by device" ) type PushNotificationAck struct { diff --git a/model/push_response.go b/model/push_response.go index 227a089b5d..85e6b44748 100644 --- a/model/push_response.go +++ b/model/push_response.go @@ -9,31 +9,31 @@ import ( ) const ( - PUSH_STATUS = "status" - PUSH_STATUS_OK = "OK" - PUSH_STATUS_FAIL = "FAIL" - PUSH_STATUS_REMOVE = "REMOVE" - PUSH_STATUS_ERROR_MSG = "error" + PushStatus = "status" + PushStatusOk = "OK" + PushStatusFail = "FAIL" + PushStatusRemove = "REMOVE" + PushStatusErrorMsg = "error" ) type PushResponse map[string]string func NewOkPushResponse() PushResponse { m := make(map[string]string) - m[PUSH_STATUS] = PUSH_STATUS_OK + m[PushStatus] = PushStatusOk return m } func NewRemovePushResponse() PushResponse { m := make(map[string]string) - m[PUSH_STATUS] = PUSH_STATUS_REMOVE + m[PushStatus] = PushStatusRemove return m } func NewErrorPushResponse(message string) PushResponse { m := make(map[string]string) - m[PUSH_STATUS] = PUSH_STATUS_FAIL - m[PUSH_STATUS_ERROR_MSG] = message + m[PushStatus] = PushStatusFail + m[PushStatusErrorMsg] = message return m } diff --git a/model/reaction.go b/model/reaction.go index 6d0ea68d23..d0497f33b2 100644 --- a/model/reaction.go +++ b/model/reaction.go @@ -74,7 +74,7 @@ func (o *Reaction) IsValid() *AppError { validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) - if o.EmojiName == "" || len(o.EmojiName) > EMOJI_NAME_MAX_LENGTH || !validName.MatchString(o.EmojiName) { + if o.EmojiName == "" || len(o.EmojiName) > EmojiNameMaxLength || !validName.MatchString(o.EmojiName) { return NewAppError("Reaction.IsValid", "model.reaction.is_valid.emoji_name.app_error", nil, "emoji_name="+o.EmojiName, http.StatusBadRequest) } diff --git a/model/role.go b/model/role.go index fc1606cedd..6bce22e205 100644 --- a/model/role.go +++ b/model/role.go @@ -21,317 +21,317 @@ var NewSystemRoleIDs []string func init() { NewSystemRoleIDs = []string{ - SYSTEM_USER_MANAGER_ROLE_ID, - SYSTEM_READ_ONLY_ADMIN_ROLE_ID, - SYSTEM_MANAGER_ROLE_ID, + SystemUserManagerRoleId, + SystemReadOnlyAdminRoleId, + SystemManagerRoleId, } BuiltInSchemeManagedRoleIDs = append([]string{ - SYSTEM_GUEST_ROLE_ID, - SYSTEM_USER_ROLE_ID, - SYSTEM_ADMIN_ROLE_ID, - SYSTEM_POST_ALL_ROLE_ID, - SYSTEM_POST_ALL_PUBLIC_ROLE_ID, - SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, + SystemGuestRoleId, + SystemUserRoleId, + SystemAdminRoleId, + SystemPostAllRoleId, + SystemPostAllPublicRoleId, + SystemUserAccessTokenRoleId, - TEAM_GUEST_ROLE_ID, - TEAM_USER_ROLE_ID, - TEAM_ADMIN_ROLE_ID, - TEAM_POST_ALL_ROLE_ID, - TEAM_POST_ALL_PUBLIC_ROLE_ID, + TeamGuestRoleId, + TeamUserRoleId, + TeamAdminRoleId, + TeamPostAllRoleId, + TeamPostAllPublicRoleId, - CHANNEL_GUEST_ROLE_ID, - CHANNEL_USER_ROLE_ID, - CHANNEL_ADMIN_ROLE_ID, + ChannelGuestRoleId, + ChannelUserRoleId, + ChannelAdminRoleId, }, NewSystemRoleIDs...) // When updating the values here, the values in mattermost-redux must also be updated. SysconsoleAncillaryPermissions = map[string][]*Permission{ - PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id: { - PERMISSION_READ_LICENSE_INFORMATION, + PermissionSysconsoleReadAboutEditionAndLicense.Id: { + PermissionReadLicenseInformation, }, - PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id: { - PERMISSION_MANAGE_LICENSE_INFORMATION, + PermissionSysconsoleWriteAboutEditionAndLicense.Id: { + PermissionManageLicenseInformation, }, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS.Id: { - PERMISSION_READ_PUBLIC_CHANNEL, - PERMISSION_READ_CHANNEL, - PERMISSION_READ_PUBLIC_CHANNEL_GROUPS, - PERMISSION_READ_PRIVATE_CHANNEL_GROUPS, + PermissionSysconsoleReadUserManagementChannels.Id: { + PermissionReadPublicChannel, + PermissionReadChannel, + PermissionReadPublicChannelGroups, + PermissionReadPrivateChannelGroups, }, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS.Id: { - PERMISSION_READ_OTHER_USERS_TEAMS, - PERMISSION_GET_ANALYTICS, + PermissionSysconsoleReadUserManagementUsers.Id: { + PermissionReadOtherUsersTeams, + PermissionGetAnalytics, }, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS.Id: { - PERMISSION_LIST_PRIVATE_TEAMS, - PERMISSION_LIST_PUBLIC_TEAMS, - PERMISSION_VIEW_TEAM, + PermissionSysconsoleReadUserManagementTeams.Id: { + PermissionListPrivateTeams, + PermissionListPublicTeams, + PermissionViewTeam, }, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id: { - PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB, - PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB, + PermissionSysconsoleReadEnvironmentElasticsearch.Id: { + PermissionReadElasticsearchPostIndexingJob, + PermissionReadElasticsearchPostAggregationJob, }, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id: { - PERMISSION_TEST_SITE_URL, - PERMISSION_RELOAD_CONFIG, - PERMISSION_INVALIDATE_CACHES, + PermissionSysconsoleWriteEnvironmentWebServer.Id: { + PermissionTestSiteUrl, + PermissionReloadConfig, + PermissionInvalidateCaches, }, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id: { - PERMISSION_RECYCLE_DATABASE_CONNECTIONS, + PermissionSysconsoleWriteEnvironmentDatabase.Id: { + PermissionRecycleDatabaseConnections, }, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id: { - PERMISSION_TEST_ELASTICSEARCH, - PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB, - PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB, - PERMISSION_PURGE_ELASTICSEARCH_INDEXES, + PermissionSysconsoleWriteEnvironmentElasticsearch.Id: { + PermissionTestElasticsearch, + PermissionCreateElasticsearchPostIndexingJob, + PermissionCreateElasticsearchPostAggregationJob, + PermissionPurgeElasticsearchIndexes, }, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id: { - PERMISSION_TEST_S3, + PermissionSysconsoleWriteEnvironmentFileStorage.Id: { + PermissionTestS3, }, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id: { - PERMISSION_TEST_EMAIL, + PermissionSysconsoleWriteEnvironmentSmtp.Id: { + PermissionTestEmail, }, - PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id: { - PERMISSION_GET_LOGS, + PermissionSysconsoleReadReportingServerLogs.Id: { + PermissionGetLogs, }, - PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id: { - PERMISSION_GET_ANALYTICS, + PermissionSysconsoleReadReportingSiteStatistics.Id: { + PermissionGetAnalytics, }, - PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS.Id: { - PERMISSION_VIEW_TEAM, + PermissionSysconsoleReadReportingTeamStatistics.Id: { + PermissionViewTeam, }, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS.Id: { - PERMISSION_EDIT_OTHER_USERS, - PERMISSION_DEMOTE_TO_GUEST, - PERMISSION_PROMOTE_GUEST, + PermissionSysconsoleWriteUserManagementUsers.Id: { + PermissionEditOtherUsers, + PermissionDemoteToGuest, + PermissionPromoteGuest, }, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS.Id: { - PERMISSION_MANAGE_TEAM, - PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES, - PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES, - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS, - PERMISSION_DELETE_PRIVATE_CHANNEL, - PERMISSION_DELETE_PUBLIC_CHANNEL, - PERMISSION_MANAGE_CHANNEL_ROLES, - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE, - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC, + PermissionSysconsoleWriteUserManagementChannels.Id: { + PermissionManageTeam, + PermissionManagePublicChannelProperties, + PermissionManagePrivateChannelProperties, + PermissionManagePrivateChannelMembers, + PermissionManagePublicChannelMembers, + PermissionDeletePrivateChannel, + PermissionDeletePublicChannel, + PermissionManageChannelRoles, + PermissionConvertPublicChannelToPrivate, + PermissionConvertPrivateChannelToPublic, }, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS.Id: { - PERMISSION_MANAGE_TEAM, - PERMISSION_MANAGE_TEAM_ROLES, - PERMISSION_REMOVE_USER_FROM_TEAM, - PERMISSION_JOIN_PRIVATE_TEAMS, - PERMISSION_JOIN_PUBLIC_TEAMS, - PERMISSION_ADD_USER_TO_TEAM, + PermissionSysconsoleWriteUserManagementTeams.Id: { + PermissionManageTeam, + PermissionManageTeamRoles, + PermissionRemoveUserFromTeam, + PermissionJoinPrivateTeams, + PermissionJoinPublicTeams, + PermissionAddUserToTeam, }, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS.Id: { - PERMISSION_MANAGE_TEAM, - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS, - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE, - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC, + PermissionSysconsoleWriteUserManagementGroups.Id: { + PermissionManageTeam, + PermissionManagePrivateChannelMembers, + PermissionManagePublicChannelMembers, + PermissionConvertPublicChannelToPrivate, + PermissionConvertPrivateChannelToPublic, }, - PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id: { - PERMISSION_EDIT_BRAND, + PermissionSysconsoleWriteSiteCustomization.Id: { + PermissionEditBrand, }, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY.Id: { - PERMISSION_CREATE_DATA_RETENTION_JOB, + PermissionSysconsoleWriteComplianceDataRetentionPolicy.Id: { + PermissionCreateDataRetentionJob, }, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id: { - PERMISSION_READ_DATA_RETENTION_JOB, + PermissionSysconsoleReadComplianceDataRetentionPolicy.Id: { + PermissionReadDataRetentionJob, }, - PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT.Id: { - PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB, - PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT, + PermissionSysconsoleWriteComplianceComplianceExport.Id: { + PermissionCreateComplianceExportJob, + PermissionDownloadComplianceExportResult, }, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id: { - PERMISSION_READ_COMPLIANCE_EXPORT_JOB, - PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT, + PermissionSysconsoleReadComplianceComplianceExport.Id: { + PermissionReadComplianceExportJob, + PermissionDownloadComplianceExportResult, }, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id: { - PERMISSION_READ_AUDITS, + PermissionSysconsoleReadComplianceCustomTermsOfService.Id: { + PermissionReadAudits, }, - PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE.Id: { - PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB, - PERMISSION_PURGE_BLEVE_INDEXES, + PermissionSysconsoleWriteExperimentalBleve.Id: { + PermissionCreatePostBleveIndexesJob, + PermissionPurgeBleveIndexes, }, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP.Id: { - PERMISSION_CREATE_LDAP_SYNC_JOB, - PERMISSION_ADD_LDAP_PUBLIC_CERT, - PERMISSION_REMOVE_LDAP_PUBLIC_CERT, - PERMISSION_ADD_LDAP_PRIVATE_CERT, - PERMISSION_REMOVE_LDAP_PRIVATE_CERT, + PermissionSysconsoleWriteAuthenticationLdap.Id: { + PermissionCreateLdapSyncJob, + PermissionAddLdapPublicCert, + PermissionRemoveLdapPublicCert, + PermissionAddLdapPrivateCert, + PermissionRemoveLdapPrivateCert, }, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id: { - PERMISSION_TEST_LDAP, - PERMISSION_READ_LDAP_SYNC_JOB, + PermissionSysconsoleReadAuthenticationLdap.Id: { + PermissionTestLdap, + PermissionReadLdapSyncJob, }, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL.Id: { - PERMISSION_INVALIDATE_EMAIL_INVITE, + PermissionSysconsoleWriteAuthenticationEmail.Id: { + PermissionInvalidateEmailInvite, }, - PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML.Id: { - PERMISSION_GET_SAML_METADATA_FROM_IDP, - PERMISSION_ADD_SAML_PUBLIC_CERT, - PERMISSION_ADD_SAML_PRIVATE_CERT, - PERMISSION_ADD_SAML_IDP_CERT, - PERMISSION_REMOVE_SAML_PUBLIC_CERT, - PERMISSION_REMOVE_SAML_PRIVATE_CERT, - PERMISSION_REMOVE_SAML_IDP_CERT, - PERMISSION_GET_SAML_CERT_STATUS, + PermissionSysconsoleWriteAuthenticationSaml.Id: { + PermissionGetSamlMetadataFromIdp, + PermissionAddSamlPublicCert, + PermissionAddSamlPrivateCert, + PermissionAddSamlIdpCert, + PermissionRemoveSamlPublicCert, + PermissionRemoveSamlPrivateCert, + PermissionRemoveSamlIdpCert, + PermissionGetSamlCertStatus, }, } SystemUserManagerDefaultPermissions = []string{ - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS.Id, + PermissionSysconsoleReadUserManagementGroups.Id, + PermissionSysconsoleReadUserManagementTeams.Id, + PermissionSysconsoleReadUserManagementChannels.Id, + PermissionSysconsoleReadUserManagementPermissions.Id, + PermissionSysconsoleWriteUserManagementGroups.Id, + PermissionSysconsoleWriteUserManagementTeams.Id, + PermissionSysconsoleWriteUserManagementChannels.Id, + PermissionSysconsoleReadAuthenticationSignup.Id, + PermissionSysconsoleReadAuthenticationEmail.Id, + PermissionSysconsoleReadAuthenticationPassword.Id, + PermissionSysconsoleReadAuthenticationMfa.Id, + PermissionSysconsoleReadAuthenticationLdap.Id, + PermissionSysconsoleReadAuthenticationSaml.Id, + PermissionSysconsoleReadAuthenticationOpenid.Id, + PermissionSysconsoleReadAuthenticationGuestAccess.Id, } SystemReadOnlyAdminDefaultPermissions = []string{ - PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER.Id, - PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION.Id, - PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION.Id, - PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER.Id, - PERMISSION_SYSCONSOLE_READ_SITE_EMOJI.Id, - PERMISSION_SYSCONSOLE_READ_SITE_POSTS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_NOTICES.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS.Id, - PERMISSION_SYSCONSOLE_READ_PLUGINS.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING.Id, - PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES.Id, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS.Id, - PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE.Id, + PermissionSysconsoleReadAboutEditionAndLicense.Id, + PermissionSysconsoleReadReportingSiteStatistics.Id, + PermissionSysconsoleReadReportingTeamStatistics.Id, + PermissionSysconsoleReadReportingServerLogs.Id, + PermissionSysconsoleReadUserManagementUsers.Id, + PermissionSysconsoleReadUserManagementGroups.Id, + PermissionSysconsoleReadUserManagementTeams.Id, + PermissionSysconsoleReadUserManagementChannels.Id, + PermissionSysconsoleReadUserManagementPermissions.Id, + PermissionSysconsoleReadEnvironmentWebServer.Id, + PermissionSysconsoleReadEnvironmentDatabase.Id, + PermissionSysconsoleReadEnvironmentElasticsearch.Id, + PermissionSysconsoleReadEnvironmentFileStorage.Id, + PermissionSysconsoleReadEnvironmentImageProxy.Id, + PermissionSysconsoleReadEnvironmentSmtp.Id, + PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, + PermissionSysconsoleReadEnvironmentHighAvailability.Id, + PermissionSysconsoleReadEnvironmentRateLimiting.Id, + PermissionSysconsoleReadEnvironmentLogging.Id, + PermissionSysconsoleReadEnvironmentSessionLengths.Id, + PermissionSysconsoleReadEnvironmentPerformanceMonitoring.Id, + PermissionSysconsoleReadEnvironmentDeveloper.Id, + PermissionSysconsoleReadSiteCustomization.Id, + PermissionSysconsoleReadSiteLocalization.Id, + PermissionSysconsoleReadSiteUsersAndTeams.Id, + PermissionSysconsoleReadSiteNotifications.Id, + PermissionSysconsoleReadSiteAnnouncementBanner.Id, + PermissionSysconsoleReadSiteEmoji.Id, + PermissionSysconsoleReadSitePosts.Id, + PermissionSysconsoleReadSiteFileSharingAndDownloads.Id, + PermissionSysconsoleReadSitePublicLinks.Id, + PermissionSysconsoleReadSiteNotices.Id, + PermissionSysconsoleReadAuthenticationSignup.Id, + PermissionSysconsoleReadAuthenticationEmail.Id, + PermissionSysconsoleReadAuthenticationPassword.Id, + PermissionSysconsoleReadAuthenticationMfa.Id, + PermissionSysconsoleReadAuthenticationLdap.Id, + PermissionSysconsoleReadAuthenticationSaml.Id, + PermissionSysconsoleReadAuthenticationOpenid.Id, + PermissionSysconsoleReadAuthenticationGuestAccess.Id, + PermissionSysconsoleReadPlugins.Id, + PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, + PermissionSysconsoleReadIntegrationsBotAccounts.Id, + PermissionSysconsoleReadIntegrationsGif.Id, + PermissionSysconsoleReadIntegrationsCors.Id, + PermissionSysconsoleReadComplianceDataRetentionPolicy.Id, + PermissionSysconsoleReadComplianceComplianceExport.Id, + PermissionSysconsoleReadComplianceComplianceMonitoring.Id, + PermissionSysconsoleReadComplianceCustomTermsOfService.Id, + PermissionSysconsoleReadExperimentalFeatures.Id, + PermissionSysconsoleReadExperimentalFeatureFlags.Id, + PermissionSysconsoleReadExperimentalBleve.Id, } SystemManagerDefaultPermissions = []string{ - PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS.Id, - PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS.Id, - PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_TEAMS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS.Id, - PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING.Id, - PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING.Id, - PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER.Id, - PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id, - PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION.Id, - PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER.Id, - PERMISSION_SYSCONSOLE_READ_SITE_EMOJI.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI.Id, - PERMISSION_SYSCONSOLE_READ_SITE_POSTS.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS.Id, - PERMISSION_SYSCONSOLE_READ_SITE_NOTICES.Id, - PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID.Id, - PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS.Id, - PERMISSION_SYSCONSOLE_READ_PLUGINS.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF.Id, - PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS.Id, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF.Id, - PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS.Id, + PermissionSysconsoleReadAboutEditionAndLicense.Id, + PermissionSysconsoleReadReportingSiteStatistics.Id, + PermissionSysconsoleReadReportingTeamStatistics.Id, + PermissionSysconsoleReadReportingServerLogs.Id, + PermissionSysconsoleReadUserManagementGroups.Id, + PermissionSysconsoleReadUserManagementTeams.Id, + PermissionSysconsoleReadUserManagementChannels.Id, + PermissionSysconsoleReadUserManagementPermissions.Id, + PermissionSysconsoleWriteUserManagementGroups.Id, + PermissionSysconsoleWriteUserManagementTeams.Id, + PermissionSysconsoleWriteUserManagementChannels.Id, + PermissionSysconsoleWriteUserManagementPermissions.Id, + PermissionSysconsoleReadEnvironmentWebServer.Id, + PermissionSysconsoleReadEnvironmentDatabase.Id, + PermissionSysconsoleReadEnvironmentElasticsearch.Id, + PermissionSysconsoleReadEnvironmentFileStorage.Id, + PermissionSysconsoleReadEnvironmentImageProxy.Id, + PermissionSysconsoleReadEnvironmentSmtp.Id, + PermissionSysconsoleReadEnvironmentPushNotificationServer.Id, + PermissionSysconsoleReadEnvironmentHighAvailability.Id, + PermissionSysconsoleReadEnvironmentRateLimiting.Id, + PermissionSysconsoleReadEnvironmentLogging.Id, + PermissionSysconsoleReadEnvironmentSessionLengths.Id, + PermissionSysconsoleReadEnvironmentPerformanceMonitoring.Id, + PermissionSysconsoleReadEnvironmentDeveloper.Id, + PermissionSysconsoleWriteEnvironmentWebServer.Id, + PermissionSysconsoleWriteEnvironmentDatabase.Id, + PermissionSysconsoleWriteEnvironmentElasticsearch.Id, + PermissionSysconsoleWriteEnvironmentFileStorage.Id, + PermissionSysconsoleWriteEnvironmentImageProxy.Id, + PermissionSysconsoleWriteEnvironmentSmtp.Id, + PermissionSysconsoleWriteEnvironmentPushNotificationServer.Id, + PermissionSysconsoleWriteEnvironmentHighAvailability.Id, + PermissionSysconsoleWriteEnvironmentRateLimiting.Id, + PermissionSysconsoleWriteEnvironmentLogging.Id, + PermissionSysconsoleWriteEnvironmentSessionLengths.Id, + PermissionSysconsoleWriteEnvironmentPerformanceMonitoring.Id, + PermissionSysconsoleWriteEnvironmentDeveloper.Id, + PermissionSysconsoleReadSiteCustomization.Id, + PermissionSysconsoleWriteSiteCustomization.Id, + PermissionSysconsoleReadSiteLocalization.Id, + PermissionSysconsoleWriteSiteLocalization.Id, + PermissionSysconsoleReadSiteUsersAndTeams.Id, + PermissionSysconsoleWriteSiteUsersAndTeams.Id, + PermissionSysconsoleReadSiteNotifications.Id, + PermissionSysconsoleWriteSiteNotifications.Id, + PermissionSysconsoleReadSiteAnnouncementBanner.Id, + PermissionSysconsoleWriteSiteAnnouncementBanner.Id, + PermissionSysconsoleReadSiteEmoji.Id, + PermissionSysconsoleWriteSiteEmoji.Id, + PermissionSysconsoleReadSitePosts.Id, + PermissionSysconsoleWriteSitePosts.Id, + PermissionSysconsoleReadSiteFileSharingAndDownloads.Id, + PermissionSysconsoleWriteSiteFileSharingAndDownloads.Id, + PermissionSysconsoleReadSitePublicLinks.Id, + PermissionSysconsoleWriteSitePublicLinks.Id, + PermissionSysconsoleReadSiteNotices.Id, + PermissionSysconsoleWriteSiteNotices.Id, + PermissionSysconsoleReadAuthenticationSignup.Id, + PermissionSysconsoleReadAuthenticationEmail.Id, + PermissionSysconsoleReadAuthenticationPassword.Id, + PermissionSysconsoleReadAuthenticationMfa.Id, + PermissionSysconsoleReadAuthenticationLdap.Id, + PermissionSysconsoleReadAuthenticationSaml.Id, + PermissionSysconsoleReadAuthenticationOpenid.Id, + PermissionSysconsoleReadAuthenticationGuestAccess.Id, + PermissionSysconsoleReadPlugins.Id, + PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, + PermissionSysconsoleReadIntegrationsBotAccounts.Id, + PermissionSysconsoleReadIntegrationsGif.Id, + PermissionSysconsoleReadIntegrationsCors.Id, + PermissionSysconsoleWriteIntegrationsIntegrationManagement.Id, + PermissionSysconsoleWriteIntegrationsBotAccounts.Id, + PermissionSysconsoleWriteIntegrationsGif.Id, + PermissionSysconsoleWriteIntegrationsCors.Id, } // Add the ancillary permissions to each system role @@ -344,29 +344,29 @@ type RoleType string type RoleScope string const ( - SYSTEM_GUEST_ROLE_ID = "system_guest" - SYSTEM_USER_ROLE_ID = "system_user" - SYSTEM_ADMIN_ROLE_ID = "system_admin" - SYSTEM_POST_ALL_ROLE_ID = "system_post_all" - SYSTEM_POST_ALL_PUBLIC_ROLE_ID = "system_post_all_public" - SYSTEM_USER_ACCESS_TOKEN_ROLE_ID = "system_user_access_token" - SYSTEM_USER_MANAGER_ROLE_ID = "system_user_manager" - SYSTEM_READ_ONLY_ADMIN_ROLE_ID = "system_read_only_admin" - SYSTEM_MANAGER_ROLE_ID = "system_manager" + SystemGuestRoleId = "system_guest" + SystemUserRoleId = "system_user" + SystemAdminRoleId = "system_admin" + SystemPostAllRoleId = "system_post_all" + SystemPostAllPublicRoleId = "system_post_all_public" + SystemUserAccessTokenRoleId = "system_user_access_token" + SystemUserManagerRoleId = "system_user_manager" + SystemReadOnlyAdminRoleId = "system_read_only_admin" + SystemManagerRoleId = "system_manager" - TEAM_GUEST_ROLE_ID = "team_guest" - TEAM_USER_ROLE_ID = "team_user" - TEAM_ADMIN_ROLE_ID = "team_admin" - TEAM_POST_ALL_ROLE_ID = "team_post_all" - TEAM_POST_ALL_PUBLIC_ROLE_ID = "team_post_all_public" + TeamGuestRoleId = "team_guest" + TeamUserRoleId = "team_user" + TeamAdminRoleId = "team_admin" + TeamPostAllRoleId = "team_post_all" + TeamPostAllPublicRoleId = "team_post_all_public" - CHANNEL_GUEST_ROLE_ID = "channel_guest" - CHANNEL_USER_ROLE_ID = "channel_user" - CHANNEL_ADMIN_ROLE_ID = "channel_admin" + ChannelGuestRoleId = "channel_guest" + ChannelUserRoleId = "channel_user" + ChannelAdminRoleId = "channel_admin" - ROLE_NAME_MAX_LENGTH = 64 - ROLE_DISPLAY_NAME_MAX_LENGTH = 128 - ROLE_DESCRIPTION_MAX_LENGTH = 1024 + RoleNameMaxLength = 64 + RoleDisplayNameMaxLength = 128 + RoleDescriptionMaxLength = 1024 RoleScopeSystem RoleScope = "System" RoleScopeTeam RoleScope = "Team" @@ -456,7 +456,7 @@ func (r *Role) MergeChannelHigherScopedPermissions(higherScopedPermissions *Role // For the channel admin role always look to the higher scope to determine if the role has their permission. // The channel admin is a special case because they're not part of the UI to be "channel moderated", only // channel members and channel guests are. - if higherScopedPermissions.RoleID == CHANNEL_ADMIN_ROLE_ID && presentOnHigherScope { + if higherScopedPermissions.RoleID == ChannelAdminRoleId && presentOnHigherScope { mergedPermissions = append(mergedPermissions, cp.Id) continue } @@ -569,9 +569,9 @@ func (r *Role) GetChannelModeratedPermissions(channelType string) map[string]boo if moderated == permission { // Special case where the channel moderated permission for `manage_members` is different depending on whether the channel is private or public - if moderated == PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id || moderated == PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id { - canManagePublic := channelType == CHANNEL_OPEN && moderated == PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id - canManagePrivate := channelType == CHANNEL_PRIVATE && moderated == PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id + if moderated == PermissionManagePublicChannelMembers.Id || moderated == PermissionManagePrivateChannelMembers.Id { + canManagePublic := channelType == ChannelTypeOpen && moderated == PermissionManagePublicChannelMembers.Id + canManagePrivate := channelType == ChannelTypePrivate && moderated == PermissionManagePrivateChannelMembers.Id moderatedPermissions[moderatedPermissionValue] = canManagePublic || canManagePrivate } else { moderatedPermissions[moderatedPermissionValue] = true @@ -650,11 +650,11 @@ func (r *Role) IsValidWithoutId() bool { return false } - if r.DisplayName == "" || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { + if r.DisplayName == "" || len(r.DisplayName) > RoleDisplayNameMaxLength { return false } - if len(r.Description) > ROLE_DESCRIPTION_MAX_LENGTH { + if len(r.Description) > RoleDescriptionMaxLength { return false } @@ -694,7 +694,7 @@ func CleanRoleNames(roleNames []string) ([]string, bool) { } func IsValidRoleName(roleName string) bool { - if roleName == "" || len(roleName) > ROLE_NAME_MAX_LENGTH { + if roleName == "" || len(roleName) > RoleNameMaxLength { return false } @@ -708,192 +708,192 @@ func IsValidRoleName(roleName string) bool { func MakeDefaultRoles() map[string]*Role { roles := make(map[string]*Role) - roles[CHANNEL_GUEST_ROLE_ID] = &Role{ + roles[ChannelGuestRoleId] = &Role{ Name: "channel_guest", DisplayName: "authentication.roles.channel_guest.name", Description: "authentication.roles.channel_guest.description", Permissions: []string{ - PERMISSION_READ_CHANNEL.Id, - PERMISSION_ADD_REACTION.Id, - PERMISSION_REMOVE_REACTION.Id, - PERMISSION_UPLOAD_FILE.Id, - PERMISSION_EDIT_POST.Id, - PERMISSION_CREATE_POST.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, - PERMISSION_USE_SLASH_COMMANDS.Id, + PermissionReadChannel.Id, + PermissionAddReaction.Id, + PermissionRemoveReaction.Id, + PermissionUploadFile.Id, + PermissionEditPost.Id, + PermissionCreatePost.Id, + PermissionUseChannelMentions.Id, + PermissionUseSlashCommands.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[CHANNEL_USER_ROLE_ID] = &Role{ + roles[ChannelUserRoleId] = &Role{ Name: "channel_user", DisplayName: "authentication.roles.channel_user.name", Description: "authentication.roles.channel_user.description", Permissions: []string{ - PERMISSION_READ_CHANNEL.Id, - PERMISSION_ADD_REACTION.Id, - PERMISSION_REMOVE_REACTION.Id, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - PERMISSION_UPLOAD_FILE.Id, - PERMISSION_GET_PUBLIC_LINK.Id, - PERMISSION_CREATE_POST.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, - PERMISSION_USE_SLASH_COMMANDS.Id, + PermissionReadChannel.Id, + PermissionAddReaction.Id, + PermissionRemoveReaction.Id, + PermissionManagePublicChannelMembers.Id, + PermissionUploadFile.Id, + PermissionGetPublicLink.Id, + PermissionCreatePost.Id, + PermissionUseChannelMentions.Id, + PermissionUseSlashCommands.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[CHANNEL_ADMIN_ROLE_ID] = &Role{ + roles[ChannelAdminRoleId] = &Role{ Name: "channel_admin", DisplayName: "authentication.roles.channel_admin.name", Description: "authentication.roles.channel_admin.description", Permissions: []string{ - PERMISSION_MANAGE_CHANNEL_ROLES.Id, - PERMISSION_USE_GROUP_MENTIONS.Id, + PermissionManageChannelRoles.Id, + PermissionUseGroupMentions.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[TEAM_GUEST_ROLE_ID] = &Role{ + roles[TeamGuestRoleId] = &Role{ Name: "team_guest", DisplayName: "authentication.roles.team_guest.name", Description: "authentication.roles.team_guest.description", Permissions: []string{ - PERMISSION_VIEW_TEAM.Id, + PermissionViewTeam.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[TEAM_USER_ROLE_ID] = &Role{ + roles[TeamUserRoleId] = &Role{ Name: "team_user", DisplayName: "authentication.roles.team_user.name", Description: "authentication.roles.team_user.description", Permissions: []string{ - PERMISSION_LIST_TEAM_CHANNELS.Id, - PERMISSION_JOIN_PUBLIC_CHANNELS.Id, - PERMISSION_READ_PUBLIC_CHANNEL.Id, - PERMISSION_VIEW_TEAM.Id, + PermissionListTeamChannels.Id, + PermissionJoinPublicChannels.Id, + PermissionReadPublicChannel.Id, + PermissionViewTeam.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[TEAM_POST_ALL_ROLE_ID] = &Role{ + roles[TeamPostAllRoleId] = &Role{ Name: "team_post_all", DisplayName: "authentication.roles.team_post_all.name", Description: "authentication.roles.team_post_all.description", Permissions: []string{ - PERMISSION_CREATE_POST.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionCreatePost.Id, + PermissionUseChannelMentions.Id, }, SchemeManaged: false, BuiltIn: true, } - roles[TEAM_POST_ALL_PUBLIC_ROLE_ID] = &Role{ + roles[TeamPostAllPublicRoleId] = &Role{ Name: "team_post_all_public", DisplayName: "authentication.roles.team_post_all_public.name", Description: "authentication.roles.team_post_all_public.description", Permissions: []string{ - PERMISSION_CREATE_POST_PUBLIC.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionCreatePostPublic.Id, + PermissionUseChannelMentions.Id, }, SchemeManaged: false, BuiltIn: true, } - roles[TEAM_ADMIN_ROLE_ID] = &Role{ + roles[TeamAdminRoleId] = &Role{ Name: "team_admin", DisplayName: "authentication.roles.team_admin.name", Description: "authentication.roles.team_admin.description", Permissions: []string{ - PERMISSION_REMOVE_USER_FROM_TEAM.Id, - PERMISSION_MANAGE_TEAM.Id, - PERMISSION_IMPORT_TEAM.Id, - PERMISSION_MANAGE_TEAM_ROLES.Id, - PERMISSION_MANAGE_CHANNEL_ROLES.Id, - PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id, - PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id, - PERMISSION_MANAGE_SLASH_COMMANDS.Id, - PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id, - PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id, - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id, + PermissionRemoveUserFromTeam.Id, + PermissionManageTeam.Id, + PermissionImportTeam.Id, + PermissionManageTeamRoles.Id, + PermissionManageChannelRoles.Id, + PermissionManageOthersIncomingWebhooks.Id, + PermissionManageOthersOutgoingWebhooks.Id, + PermissionManageSlashCommands.Id, + PermissionManageOthersSlashCommands.Id, + PermissionManageIncomingWebhooks.Id, + PermissionManageOutgoingWebhooks.Id, + PermissionConvertPublicChannelToPrivate.Id, + PermissionConvertPrivateChannelToPublic.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[SYSTEM_GUEST_ROLE_ID] = &Role{ + roles[SystemGuestRoleId] = &Role{ Name: "system_guest", DisplayName: "authentication.roles.global_guest.name", Description: "authentication.roles.global_guest.description", Permissions: []string{ - PERMISSION_CREATE_DIRECT_CHANNEL.Id, - PERMISSION_CREATE_GROUP_CHANNEL.Id, + PermissionCreateDirectChannel.Id, + PermissionCreateGroupChannel.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[SYSTEM_USER_ROLE_ID] = &Role{ + roles[SystemUserRoleId] = &Role{ Name: "system_user", DisplayName: "authentication.roles.global_user.name", Description: "authentication.roles.global_user.description", Permissions: []string{ - PERMISSION_LIST_PUBLIC_TEAMS.Id, - PERMISSION_JOIN_PUBLIC_TEAMS.Id, - PERMISSION_CREATE_DIRECT_CHANNEL.Id, - PERMISSION_CREATE_GROUP_CHANNEL.Id, - PERMISSION_VIEW_MEMBERS.Id, + PermissionListPublicTeams.Id, + PermissionJoinPublicTeams.Id, + PermissionCreateDirectChannel.Id, + PermissionCreateGroupChannel.Id, + PermissionViewMembers.Id, }, SchemeManaged: true, BuiltIn: true, } - roles[SYSTEM_POST_ALL_ROLE_ID] = &Role{ + roles[SystemPostAllRoleId] = &Role{ Name: "system_post_all", DisplayName: "authentication.roles.system_post_all.name", Description: "authentication.roles.system_post_all.description", Permissions: []string{ - PERMISSION_CREATE_POST.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionCreatePost.Id, + PermissionUseChannelMentions.Id, }, SchemeManaged: false, BuiltIn: true, } - roles[SYSTEM_POST_ALL_PUBLIC_ROLE_ID] = &Role{ + roles[SystemPostAllPublicRoleId] = &Role{ Name: "system_post_all_public", DisplayName: "authentication.roles.system_post_all_public.name", Description: "authentication.roles.system_post_all_public.description", Permissions: []string{ - PERMISSION_CREATE_POST_PUBLIC.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionCreatePostPublic.Id, + PermissionUseChannelMentions.Id, }, SchemeManaged: false, BuiltIn: true, } - roles[SYSTEM_USER_ACCESS_TOKEN_ROLE_ID] = &Role{ + roles[SystemUserAccessTokenRoleId] = &Role{ Name: "system_user_access_token", DisplayName: "authentication.roles.system_user_access_token.name", Description: "authentication.roles.system_user_access_token.description", Permissions: []string{ - PERMISSION_CREATE_USER_ACCESS_TOKEN.Id, - PERMISSION_READ_USER_ACCESS_TOKEN.Id, - PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id, + PermissionCreateUserAccessToken.Id, + PermissionReadUserAccessToken.Id, + PermissionRevokeUserAccessToken.Id, }, SchemeManaged: false, BuiltIn: true, } - roles[SYSTEM_USER_MANAGER_ROLE_ID] = &Role{ + roles[SystemUserManagerRoleId] = &Role{ Name: "system_user_manager", DisplayName: "authentication.roles.system_user_manager.name", Description: "authentication.roles.system_user_manager.description", @@ -902,7 +902,7 @@ func MakeDefaultRoles() map[string]*Role { BuiltIn: true, } - roles[SYSTEM_READ_ONLY_ADMIN_ROLE_ID] = &Role{ + roles[SystemReadOnlyAdminRoleId] = &Role{ Name: "system_read_only_admin", DisplayName: "authentication.roles.system_read_only_admin.name", Description: "authentication.roles.system_read_only_admin.description", @@ -911,7 +911,7 @@ func MakeDefaultRoles() map[string]*Role { BuiltIn: true, } - roles[SYSTEM_MANAGER_ROLE_ID] = &Role{ + roles[SystemManagerRoleId] = &Role{ Name: "system_manager", DisplayName: "authentication.roles.system_manager.name", Description: "authentication.roles.system_manager.description", @@ -925,7 +925,7 @@ func MakeDefaultRoles() map[string]*Role { allPermissionIDs = append(allPermissionIDs, permission.Id) } - roles[SYSTEM_ADMIN_ROLE_ID] = &Role{ + roles[SystemAdminRoleId] = &Role{ Name: "system_admin", DisplayName: "authentication.roles.global_admin.name", Description: "authentication.roles.global_admin.description", diff --git a/model/role_test.go b/model/role_test.go index 081707e1b4..562b3112e8 100644 --- a/model/role_test.go +++ b/model/role_test.go @@ -25,25 +25,25 @@ func TestChannelModeratedPermissionsChangedByPatch(t *testing.T) { { "Adds permissions to empty initial permissions list", []string{}, - []string{PERMISSION_CREATE_POST.Id, PERMISSION_ADD_REACTION.Id}, + []string{PermissionCreatePost.Id, PermissionAddReaction.Id}, []string{ChannelModeratedPermissions[0], ChannelModeratedPermissions[1]}, }, { "Ignores non moderated permissions in initial permissions list", - []string{PERMISSION_ASSIGN_BOT.Id}, - []string{PERMISSION_CREATE_POST.Id, PERMISSION_REMOVE_REACTION.Id}, + []string{PermissionAssignBot.Id}, + []string{PermissionCreatePost.Id, PermissionRemoveReaction.Id}, []string{ChannelModeratedPermissions[0], ChannelModeratedPermissions[1]}, }, { "Adds removed moderated permissions from initial permissions list", - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id}, []string{}, - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id}, }, { "No changes returns empty slice", - []string{PERMISSION_CREATE_POST.Id, PERMISSION_ASSIGN_BOT.Id}, - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id, PermissionAssignBot.Id}, + []string{PermissionCreatePost.Id}, []string{}, }, } @@ -64,22 +64,22 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { channelMentions := ChannelModeratedPermissions[3] basePermissions := []string{ - PERMISSION_ADD_REACTION.Id, - PERMISSION_REMOVE_REACTION.Id, - PERMISSION_CREATE_POST.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - PERMISSION_UPLOAD_FILE.Id, - PERMISSION_GET_PUBLIC_LINK.Id, - PERMISSION_USE_SLASH_COMMANDS.Id, + PermissionAddReaction.Id, + PermissionRemoveReaction.Id, + PermissionCreatePost.Id, + PermissionUseChannelMentions.Id, + PermissionManagePublicChannelMembers.Id, + PermissionUploadFile.Id, + PermissionGetPublicLink.Id, + PermissionUseSlashCommands.Id, } baseModeratedPermissions := []string{ - PERMISSION_ADD_REACTION.Id, - PERMISSION_REMOVE_REACTION.Id, - PERMISSION_CREATE_POST.Id, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - PERMISSION_USE_CHANNEL_MENTIONS.Id, + PermissionAddReaction.Id, + PermissionRemoveReaction.Id, + PermissionCreatePost.Id, + PermissionManagePublicChannelMembers.Id, + PermissionUseChannelMentions.Id, } testCases := []struct { @@ -143,7 +143,7 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { }, }, "members", - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id}, }, { "Patch to guest role removing multiple channel moderated permissions", @@ -163,11 +163,11 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { }, }, "guests", - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id}, }, { "Patch enabling and removing multiple channel moderated permissions ", - []string{PERMISSION_ADD_REACTION.Id, PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id}, + []string{PermissionAddReaction.Id, PermissionManagePublicChannelMembers.Id}, []*ChannelModerationPatch{ { Name: &createReactions, @@ -187,11 +187,11 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { }, }, "members", - []string{PERMISSION_CREATE_POST.Id, PERMISSION_USE_CHANNEL_MENTIONS.Id}, + []string{PermissionCreatePost.Id, PermissionUseChannelMentions.Id}, }, { "Patch enabling a partially enabled permission", - []string{PERMISSION_ADD_REACTION.Id}, + []string{PermissionAddReaction.Id}, []*ChannelModerationPatch{ { Name: &createReactions, @@ -199,11 +199,11 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { }, }, "members", - []string{PERMISSION_ADD_REACTION.Id, PERMISSION_REMOVE_REACTION.Id}, + []string{PermissionAddReaction.Id, PermissionRemoveReaction.Id}, }, { "Patch disabling a partially disabled permission", - []string{PERMISSION_ADD_REACTION.Id}, + []string{PermissionAddReaction.Id}, []*ChannelModerationPatch{ { Name: &createReactions, @@ -215,7 +215,7 @@ func TestRolePatchFromChannelModerationsPatch(t *testing.T) { }, }, "members", - []string{PERMISSION_CREATE_POST.Id}, + []string{PermissionCreatePost.Id}, }, } for _, tc := range testCases { @@ -236,14 +236,14 @@ func TestGetChannelModeratedPermissions(t *testing.T) { }{ { "Filters non moderated permissions", - []string{PERMISSION_CREATE_BOT.Id}, - CHANNEL_OPEN, + []string{PermissionCreateBot.Id}, + ChannelTypeOpen, map[string]bool{}, }, { "Returns a map of moderated permissions", - []string{PERMISSION_CREATE_POST.Id, PERMISSION_ADD_REACTION.Id, PERMISSION_REMOVE_REACTION.Id, PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, PERMISSION_USE_CHANNEL_MENTIONS.Id}, - CHANNEL_OPEN, + []string{PermissionCreatePost.Id, PermissionAddReaction.Id, PermissionRemoveReaction.Id, PermissionManagePublicChannelMembers.Id, PermissionManagePrivateChannelMembers.Id, PermissionUseChannelMentions.Id}, + ChannelTypeOpen, map[string]bool{ ChannelModeratedPermissions[0]: true, ChannelModeratedPermissions[1]: true, @@ -253,8 +253,8 @@ func TestGetChannelModeratedPermissions(t *testing.T) { }, { "Returns a map of moderated permissions when non moderated present", - []string{PERMISSION_CREATE_POST.Id, PERMISSION_CREATE_DIRECT_CHANNEL.Id}, - CHANNEL_OPEN, + []string{PermissionCreatePost.Id, PermissionCreateDirectChannel.Id}, + ChannelTypeOpen, map[string]bool{ ChannelModeratedPermissions[0]: true, }, @@ -262,7 +262,7 @@ func TestGetChannelModeratedPermissions(t *testing.T) { { "Returns a nothing when no permissions present", []string{}, - CHANNEL_OPEN, + ChannelTypeOpen, map[string]bool{}, }, } diff --git a/model/saml.go b/model/saml.go index feaf325aeb..99b023957f 100644 --- a/model/saml.go +++ b/model/saml.go @@ -11,11 +11,11 @@ import ( ) const ( - USER_AUTH_SERVICE_SAML = "saml" - USER_AUTH_SERVICE_SAML_TEXT = "SAML" - USER_AUTH_SERVICE_IS_SAML = "isSaml" - USER_AUTH_SERVICE_IS_MOBILE = "isMobile" - USER_AUTH_SERVICE_IS_OAUTH = "isOAuthUser" + UserAuthServiceSaml = "saml" + UserAuthServiceSamlText = "SAML" + UserAuthServiceIsSaml = "isSaml" + UserAuthServiceIsMobile = "isMobile" + UserAuthServiceIsOAuth = "isOAuthUser" ) type SamlAuthRequest struct { diff --git a/model/scheduled_task_test.go b/model/scheduled_task_test.go index 90e638ff2e..a610dff6d2 100644 --- a/model/scheduled_task_test.go +++ b/model/scheduled_task_test.go @@ -13,71 +13,71 @@ import ( ) func TestCreateTask(t *testing.T) { - TASK_NAME := "Test Task" - TASK_TIME := time.Second * 2 + TaskName := "Test Task" + TaskTime := time.Second * 2 executionCount := new(int32) testFunc := func() { atomic.AddInt32(executionCount, 1) } - task := CreateTask(TASK_NAME, testFunc, TASK_TIME) + task := CreateTask(TaskName, testFunc, TaskTime) assert.EqualValues(t, 0, atomic.LoadInt32(executionCount)) - time.Sleep(TASK_TIME + time.Second) + time.Sleep(TaskTime + time.Second) assert.EqualValues(t, 1, atomic.LoadInt32(executionCount)) - assert.Equal(t, TASK_NAME, task.Name) - assert.Equal(t, TASK_TIME, task.Interval) + assert.Equal(t, TaskName, task.Name) + assert.Equal(t, TaskTime, task.Interval) assert.False(t, task.Recurring) } func TestCreateRecurringTask(t *testing.T) { - TASK_NAME := "Test Recurring Task" - TASK_TIME := time.Second * 2 + TaskName := "Test Recurring Task" + TaskTime := time.Second * 2 executionCount := new(int32) testFunc := func() { atomic.AddInt32(executionCount, 1) } - task := CreateRecurringTask(TASK_NAME, testFunc, TASK_TIME) + task := CreateRecurringTask(TaskName, testFunc, TaskTime) assert.EqualValues(t, 0, atomic.LoadInt32(executionCount)) - time.Sleep(TASK_TIME + time.Second) + time.Sleep(TaskTime + time.Second) assert.EqualValues(t, 1, atomic.LoadInt32(executionCount)) - time.Sleep(TASK_TIME) + time.Sleep(TaskTime) assert.EqualValues(t, 2, atomic.LoadInt32(executionCount)) - assert.Equal(t, TASK_NAME, task.Name) - assert.Equal(t, TASK_TIME, task.Interval) + assert.Equal(t, TaskName, task.Name) + assert.Equal(t, TaskTime, task.Interval) assert.True(t, task.Recurring) task.Cancel() } func TestCancelTask(t *testing.T) { - TASK_NAME := "Test Task" - TASK_TIME := time.Second + TaskName := "Test Task" + TaskTime := time.Second executionCount := new(int32) testFunc := func() { atomic.AddInt32(executionCount, 1) } - task := CreateTask(TASK_NAME, testFunc, TASK_TIME) + task := CreateTask(TaskName, testFunc, TaskTime) assert.EqualValues(t, 0, atomic.LoadInt32(executionCount)) task.Cancel() - time.Sleep(TASK_TIME + time.Second) + time.Sleep(TaskTime + time.Second) assert.EqualValues(t, 0, atomic.LoadInt32(executionCount)) } func TestCreateRecurringTaskFromNextIntervalTime(t *testing.T) { - TASK_NAME := "Test Recurring Task starting from next interval time" - TASK_TIME := time.Second * 2 + TaskName := "Test Recurring Task starting from next interval time" + TaskTime := time.Second * 2 var executionTime time.Time var mu sync.Mutex @@ -87,22 +87,22 @@ func TestCreateRecurringTaskFromNextIntervalTime(t *testing.T) { mu.Unlock() } - task := CreateRecurringTaskFromNextIntervalTime(TASK_NAME, testFunc, TASK_TIME) + task := CreateRecurringTaskFromNextIntervalTime(TaskName, testFunc, TaskTime) defer task.Cancel() - time.Sleep(TASK_TIME) + time.Sleep(TaskTime) mu.Lock() expectedSeconds := executionTime.Second() mu.Unlock() assert.EqualValues(t, 0, expectedSeconds%2) - time.Sleep(TASK_TIME) + time.Sleep(TaskTime) mu.Lock() expectedSeconds = executionTime.Second() mu.Unlock() assert.EqualValues(t, 0, expectedSeconds%2) - assert.Equal(t, TASK_NAME, task.Name) - assert.Equal(t, TASK_TIME, task.Interval) + assert.Equal(t, TaskName, task.Name) + assert.Equal(t, TaskTime, task.Interval) assert.True(t, task.Recurring) } diff --git a/model/scheme.go b/model/scheme.go index b5bbf34abc..d77afca134 100644 --- a/model/scheme.go +++ b/model/scheme.go @@ -11,11 +11,11 @@ import ( ) const ( - SCHEME_DISPLAY_NAME_MAX_LENGTH = 128 - SCHEME_NAME_MAX_LENGTH = 64 - SCHEME_DESCRIPTION_MAX_LENGTH = 1024 - SCHEME_SCOPE_TEAM = "team" - SCHEME_SCOPE_CHANNEL = "channel" + SchemeDisplayNameMaxLength = 128 + SchemeNameMaxLength = 64 + SchemeDescriptionMaxLength = 1024 + SchemeScopeTeam = "team" + SchemeScopeChannel = "channel" ) type Scheme struct { @@ -114,7 +114,7 @@ func (scheme *Scheme) IsValid() bool { } func (scheme *Scheme) IsValidForCreate() bool { - if scheme.DisplayName == "" || len(scheme.DisplayName) > SCHEME_DISPLAY_NAME_MAX_LENGTH { + if scheme.DisplayName == "" || len(scheme.DisplayName) > SchemeDisplayNameMaxLength { return false } @@ -122,12 +122,12 @@ func (scheme *Scheme) IsValidForCreate() bool { return false } - if len(scheme.Description) > SCHEME_DESCRIPTION_MAX_LENGTH { + if len(scheme.Description) > SchemeDescriptionMaxLength { return false } switch scheme.Scope { - case SCHEME_SCOPE_TEAM, SCHEME_SCOPE_CHANNEL: + case SchemeScopeTeam, SchemeScopeChannel: default: return false } @@ -144,7 +144,7 @@ func (scheme *Scheme) IsValidForCreate() bool { return false } - if scheme.Scope == SCHEME_SCOPE_TEAM { + if scheme.Scope == SchemeScopeTeam { if !IsValidRoleName(scheme.DefaultTeamAdminRole) { return false } @@ -158,7 +158,7 @@ func (scheme *Scheme) IsValidForCreate() bool { } } - if scheme.Scope == SCHEME_SCOPE_CHANNEL { + if scheme.Scope == SchemeScopeChannel { if scheme.DefaultTeamAdminRole != "" { return false } @@ -210,7 +210,7 @@ func (p *SchemeIDPatch) ToJson() string { } func IsValidSchemeName(name string) bool { - re := regexp.MustCompile(fmt.Sprintf("^[a-z0-9_]{2,%d}$", SCHEME_NAME_MAX_LENGTH)) + re := regexp.MustCompile(fmt.Sprintf("^[a-z0-9_]{2,%d}$", SchemeNameMaxLength)) return re.MatchString(name) } diff --git a/model/session.go b/model/session.go index 334c717501..c52a63183b 100644 --- a/model/session.go +++ b/model/session.go @@ -13,23 +13,23 @@ import ( ) const ( - SESSION_COOKIE_TOKEN = "MMAUTHTOKEN" - SESSION_COOKIE_USER = "MMUSERID" - SESSION_COOKIE_CSRF = "MMCSRF" - SESSION_CACHE_SIZE = 35000 - SESSION_PROP_PLATFORM = "platform" - SESSION_PROP_OS = "os" - SESSION_PROP_BROWSER = "browser" - SESSION_PROP_TYPE = "type" - SESSION_PROP_USER_ACCESS_TOKEN_ID = "user_access_token_id" - SESSION_PROP_IS_BOT = "is_bot" - SESSION_PROP_IS_BOT_VALUE = "true" - SESSION_TYPE_USER_ACCESS_TOKEN = "UserAccessToken" - SESSION_TYPE_CLOUD_KEY = "CloudKey" - SESSION_TYPE_REMOTECLUSTER_TOKEN = "RemoteClusterToken" - SESSION_PROP_IS_GUEST = "is_guest" - SESSION_ACTIVITY_TIMEOUT = 1000 * 60 * 5 // 5 minutes - SESSION_USER_ACCESS_TOKEN_EXPIRY = 100 * 365 // 100 years + SessionCookieToken = "MMAUTHTOKEN" + SessionCookieUser = "MMUSERID" + SessionCookieCsrf = "MMCSRF" + SessionCacheSize = 35000 + SessionPropPlatform = "platform" + SessionPropOs = "os" + SessionPropBrowser = "browser" + SessionPropType = "type" + SessionPropUserAccessTokenId = "user_access_token_id" + SessionPropIsBot = "is_bot" + SessionPropIsBotValue = "true" + SessionTypeUserAccessToken = "UserAccessToken" + SessionTypeCloudKey = "CloudKey" + SessionTypeRemoteclusterToken = "RemoteClusterToken" + SessionPropIsGuest = "is_guest" + SessionActivityTimeout = 1000 * 60 * 5 // 5 minutes + SessionUserAccessTokenExpiry = 100 * 365 // 100 years ) //msgp StringMap @@ -160,7 +160,7 @@ func (s *Session) IsMobileApp() bool { } func (s *Session) IsMobile() bool { - val, ok := s.Props[USER_AUTH_SERVICE_IS_MOBILE] + val, ok := s.Props[UserAuthServiceIsMobile] if !ok { return false } @@ -173,7 +173,7 @@ func (s *Session) IsMobile() bool { } func (s *Session) IsSaml() bool { - val, ok := s.Props[USER_AUTH_SERVICE_IS_SAML] + val, ok := s.Props[UserAuthServiceIsSaml] if !ok { return false } @@ -186,7 +186,7 @@ func (s *Session) IsSaml() bool { } func (s *Session) IsOAuthUser() bool { - val, ok := s.Props[USER_AUTH_SERVICE_IS_OAUTH] + val, ok := s.Props[UserAuthServiceIsOAuth] if !ok { return false } diff --git a/model/session_test.go b/model/session_test.go index 9f12a51514..8d293720ad 100644 --- a/model/session_test.go +++ b/model/session_test.go @@ -81,10 +81,10 @@ func TestSessionIsOAuthUser(t *testing.T) { isOAuthUser bool }{ {"False on empty props", Session{}, false}, - {"True when key is set to true", Session{Props: StringMap{USER_AUTH_SERVICE_IS_OAUTH: strconv.FormatBool(true)}}, true}, - {"False when key is set to false", Session{Props: StringMap{USER_AUTH_SERVICE_IS_OAUTH: strconv.FormatBool(false)}}, false}, - {"Not affected by Session.IsOauth being true", Session{IsOAuth: true}, false}, - {"Not affected by Session.IsOauth being false", Session{IsOAuth: false, Props: StringMap{USER_AUTH_SERVICE_IS_OAUTH: strconv.FormatBool(true)}}, true}, + {"True when key is set to true", Session{Props: StringMap{UserAuthServiceIsOAuth: strconv.FormatBool(true)}}, true}, + {"False when key is set to false", Session{Props: StringMap{UserAuthServiceIsOAuth: strconv.FormatBool(false)}}, false}, + {"Not affected by Session.IsOAuth being true", Session{IsOAuth: true}, false}, + {"Not affected by Session.IsOAuth being false", Session{IsOAuth: false, Props: StringMap{UserAuthServiceIsOAuth: strconv.FormatBool(true)}}, true}, } for _, tc := range testCases { diff --git a/model/shared_channel.go b/model/shared_channel.go index e3643812e6..9172629f7c 100644 --- a/model/shared_channel.go +++ b/model/shared_channel.go @@ -47,7 +47,7 @@ func (sc *SharedChannel) IsValid() *AppError { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.id.app_error", nil, "ChannelId="+sc.ChannelId, http.StatusBadRequest) } - if sc.Type != CHANNEL_DIRECT && !IsValidId(sc.TeamId) { + if sc.Type != ChannelTypeDirect && !IsValidId(sc.TeamId) { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.id.app_error", nil, "TeamId="+sc.TeamId, http.StatusBadRequest) } @@ -59,7 +59,7 @@ func (sc *SharedChannel) IsValid() *AppError { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.update_at.app_error", nil, "id="+sc.ChannelId, http.StatusBadRequest) } - if utf8.RuneCountInString(sc.ShareDisplayName) > CHANNEL_DISPLAY_NAME_MAX_RUNES { + if utf8.RuneCountInString(sc.ShareDisplayName) > ChannelDisplayNameMaxRunes { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.display_name.app_error", nil, "id="+sc.ChannelId, http.StatusBadRequest) } @@ -67,11 +67,11 @@ func (sc *SharedChannel) IsValid() *AppError { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.2_or_more.app_error", nil, "id="+sc.ChannelId, http.StatusBadRequest) } - if utf8.RuneCountInString(sc.ShareHeader) > CHANNEL_HEADER_MAX_RUNES { + if utf8.RuneCountInString(sc.ShareHeader) > ChannelHeaderMaxRunes { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.header.app_error", nil, "id="+sc.ChannelId, http.StatusBadRequest) } - if utf8.RuneCountInString(sc.SharePurpose) > CHANNEL_PURPOSE_MAX_RUNES { + if utf8.RuneCountInString(sc.SharePurpose) > ChannelPurposeMaxRunes { return NewAppError("SharedChannel.IsValid", "model.channel.is_valid.purpose.app_error", nil, "id="+sc.ChannelId, http.StatusBadRequest) } diff --git a/model/slack_attachment.go b/model/slack_attachment.go index a85c6be2d2..3c167b7de8 100644 --- a/model/slack_attachment.go +++ b/model/slack_attachment.go @@ -165,7 +165,7 @@ func StringifySlackFieldValue(a []*SlackAttachment) []*SlackAttachment { // all else should be set in the post which is passed func ParseSlackAttachment(post *Post, attachments []*SlackAttachment) { if post.Type == "" { - post.Type = POST_SLACK_ATTACHMENT + post.Type = PostTypeSlackAttachment } postAttachments := []*SlackAttachment{} diff --git a/model/slack_attachment_test.go b/model/slack_attachment_test.go index 9602809def..241fddac86 100644 --- a/model/slack_attachment_test.go +++ b/model/slack_attachment_test.go @@ -17,7 +17,7 @@ func TestParseSlackAttachment(t *testing.T) { ParseSlackAttachment(post, attachments) expectedPost := &Post{ - Type: POST_SLACK_ATTACHMENT, + Type: PostTypeSlackAttachment, Props: map[string]interface{}{ "attachments": []*SlackAttachment{}, }, @@ -34,7 +34,7 @@ func TestParseSlackAttachment(t *testing.T) { ParseSlackAttachment(post, attachments) expectedPost := &Post{ - Type: POST_SLACK_ATTACHMENT, + Type: PostTypeSlackAttachment, Props: map[string]interface{}{ "attachments": []*SlackAttachment{}, }, diff --git a/model/status.go b/model/status.go index f6f3a67ae4..167b38f1ba 100644 --- a/model/status.go +++ b/model/status.go @@ -9,14 +9,14 @@ import ( ) const ( - STATUS_OUT_OF_OFFICE = "ooo" - STATUS_OFFLINE = "offline" - STATUS_AWAY = "away" - STATUS_DND = "dnd" - STATUS_ONLINE = "online" - STATUS_CACHE_SIZE = SESSION_CACHE_SIZE - STATUS_CHANNEL_TIMEOUT = 20000 // 20 seconds - STATUS_MIN_UPDATE_TIME = 120000 // 2 minutes + StatusOutOfOffice = "ooo" + StatusOffline = "offline" + StatusAway = "away" + StatusDnd = "dnd" + StatusOnline = "online" + StatusCacheSize = SessionCacheSize + StatusChannelTimeout = 20000 // 20 seconds + StatusMinUpdateTime = 120000 // 2 minutes ) type Status struct { @@ -70,7 +70,7 @@ func StatusMapToInterfaceMap(statusMap map[string]*Status) map[string]interface{ interfaceMap := map[string]interface{}{} for _, s := range statusMap { // Omitted statues mean offline - if s.Status != STATUS_OFFLINE { + if s.Status != StatusOffline { interfaceMap[s.UserId] = s.Status } } diff --git a/model/status_test.go b/model/status_test.go index 6825c9e139..82d0b96cb3 100644 --- a/model/status_test.go +++ b/model/status_test.go @@ -12,7 +12,7 @@ import ( ) func TestStatus(t *testing.T) { - status := Status{NewId(), STATUS_ONLINE, true, 0, "123", 0, ""} + status := Status{NewId(), StatusOnline, true, 0, "123", 0, ""} json := status.ToJson() status2 := StatusFromJson(strings.NewReader(json)) @@ -29,7 +29,7 @@ func TestStatus(t *testing.T) { } func TestStatusListToJson(t *testing.T) { - statuses := []*Status{{NewId(), STATUS_ONLINE, true, 0, "123", 0, ""}, {NewId(), STATUS_OFFLINE, true, 0, "", 0, ""}} + statuses := []*Status{{NewId(), StatusOnline, true, 0, "123", 0, ""}, {NewId(), StatusOffline, true, 0, "", 0, ""}} jsonStatuses := StatusListToJson(statuses) var dat []map[string]interface{} diff --git a/model/switch_request.go b/model/switch_request.go index bdb90045c8..0a7f207808 100644 --- a/model/switch_request.go +++ b/model/switch_request.go @@ -30,26 +30,26 @@ func SwitchRequestFromJson(data io.Reader) *SwitchRequest { } func (o *SwitchRequest) EmailToOAuth() bool { - return o.CurrentService == USER_AUTH_SERVICE_EMAIL && - (o.NewService == USER_AUTH_SERVICE_SAML || - o.NewService == USER_AUTH_SERVICE_GITLAB || - o.NewService == SERVICE_GOOGLE || - o.NewService == SERVICE_OFFICE365 || - o.NewService == SERVICE_OPENID) + return o.CurrentService == UserAuthServiceEmail && + (o.NewService == UserAuthServiceSaml || + o.NewService == UserAuthServiceGitlab || + o.NewService == ServiceGoogle || + o.NewService == ServiceOffice365 || + o.NewService == ServiceOpenid) } func (o *SwitchRequest) OAuthToEmail() bool { - return (o.CurrentService == USER_AUTH_SERVICE_SAML || - o.CurrentService == USER_AUTH_SERVICE_GITLAB || - o.CurrentService == SERVICE_GOOGLE || - o.CurrentService == SERVICE_OFFICE365 || - o.CurrentService == SERVICE_OPENID) && o.NewService == USER_AUTH_SERVICE_EMAIL + return (o.CurrentService == UserAuthServiceSaml || + o.CurrentService == UserAuthServiceGitlab || + o.CurrentService == ServiceGoogle || + o.CurrentService == ServiceOffice365 || + o.CurrentService == ServiceOpenid) && o.NewService == UserAuthServiceEmail } func (o *SwitchRequest) EmailToLdap() bool { - return o.CurrentService == USER_AUTH_SERVICE_EMAIL && o.NewService == USER_AUTH_SERVICE_LDAP + return o.CurrentService == UserAuthServiceEmail && o.NewService == UserAuthServiceLdap } func (o *SwitchRequest) LdapToEmail() bool { - return o.CurrentService == USER_AUTH_SERVICE_LDAP && o.NewService == USER_AUTH_SERVICE_EMAIL + return o.CurrentService == UserAuthServiceLdap && o.NewService == UserAuthServiceEmail } diff --git a/model/system.go b/model/system.go index b7cda1ef01..0201abf831 100644 --- a/model/system.go +++ b/model/system.go @@ -10,45 +10,45 @@ import ( ) const ( - SYSTEM_TELEMETRY_ID = "DiagnosticId" - SYSTEM_RAN_UNIT_TESTS = "RanUnitTests" - SYSTEM_LAST_SECURITY_TIME = "LastSecurityTime" - SYSTEM_ACTIVE_LICENSE_ID = "ActiveLicenseId" - SYSTEM_LICENSE_RENEWAL_TOKEN = "LicenseRenewalToken" - SYSTEM_LAST_COMPLIANCE_TIME = "LastComplianceTime" - SYSTEM_ASYMMETRIC_SIGNING_KEY = "AsymmetricSigningKey" - SYSTEM_POST_ACTION_COOKIE_SECRET = "PostActionCookieSecret" - SYSTEM_INSTALLATION_DATE_KEY = "InstallationDate" - SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY = "FirstServerRunTimestamp" - SYSTEM_CLUSTER_ENCRYPTION_KEY = "ClusterEncryptionKey" - SYSTEM_UPGRADED_FROM_TE_ID = "UpgradedFromTE" - SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5 = "warn_metric_number_of_teams_5" - SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50 = "warn_metric_number_of_channels_50" - SYSTEM_WARN_METRIC_MFA = "warn_metric_mfa" - SYSTEM_WARN_METRIC_EMAIL_DOMAIN = "warn_metric_email_domain" - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100 = "warn_metric_number_of_active_users_100" - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200 = "warn_metric_number_of_active_users_200" - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300 = "warn_metric_number_of_active_users_300" - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500 = "warn_metric_number_of_active_users_500" - SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M = "warn_metric_number_of_posts_2M" - SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY = "LastWarnMetricRunTimestamp" - SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED = "warn_metric_support_email_not_configured" - SYSTEM_FIRST_ADMIN_VISIT_MARKETPLACE = "FirstAdminVisitMarketplace" - AWS_METERING_REPORT_INTERVAL = 1 - AWS_METERING_DIMENSION_USAGE_HRS = "UsageHrs" - USER_LIMIT_OVERAGE_CYCLE_END_DATE = "UserLimitOverageCycleEndDate" - OVER_USER_LIMIT_FORGIVEN_COUNT = "OverUserLimitForgivenCount" - OVER_USER_LIMIT_LAST_EMAIL_SENT = "OverUserLimitLastEmailSent" + SystemTelemetryId = "DiagnosticId" + SystemRanUnitTests = "RanUnitTests" + SystemLastSecurityTime = "LastSecurityTime" + SystemActiveLicenseId = "ActiveLicenseId" + SystemLicenseRenewalToken = "LicenseRenewalToken" + SystemLastComplianceTime = "LastComplianceTime" + SystemAsymmetricSigningKeyKey = "AsymmetricSigningKey" + SystemPostActionCookieSecretKey = "PostActionCookieSecret" + SystemInstallationDateKey = "InstallationDate" + SystemFirstServerRunTimestampKey = "FirstServerRunTimestamp" + SystemClusterEncryptionKey = "ClusterEncryptionKey" + SystemUpgradedFromTeId = "UpgradedFromTE" + SystemWarnMetricNumberOfTeams5 = "warn_metric_number_of_teams_5" + SystemWarnMetricNumberOfChannels50 = "warn_metric_number_of_channels_50" + SystemWarnMetricMfa = "warn_metric_mfa" + SystemWarnMetricEmailDomain = "warn_metric_email_domain" + SystemWarnMetricNumberOfActiveUsers100 = "warn_metric_number_of_active_users_100" + SystemWarnMetricNumberOfActiveUsers200 = "warn_metric_number_of_active_users_200" + SystemWarnMetricNumberOfActiveUsers300 = "warn_metric_number_of_active_users_300" + SystemWarnMetricNumberOfActiveUsers500 = "warn_metric_number_of_active_users_500" + SystemWarnMetricNumberOfPosts2m = "warn_metric_number_of_posts_2M" + SystemWarnMetricLastRunTimestampKey = "LastWarnMetricRunTimestamp" + SystemMetricSupportEmailNotConfigured = "warn_metric_support_email_not_configured" + SystemFirstAdminVisitMarketplace = "FirstAdminVisitMarketplace" + AwsMeteringReportInterval = 1 + AwsMeteringDimensionUsageHrs = "UsageHrs" + UserLimitOverageCycleEndDate = "UserLimitOverageCycleEndDate" + OverUserLimitForgivenCount = "OverUserLimitForgivenCount" + OverUserLimitLastEmailSent = "OverUserLimitLastEmailSent" ) const ( - WARN_METRIC_STATUS_LIMIT_REACHED = "true" - WARN_METRIC_STATUS_RUNONCE = "runonce" - WARN_METRIC_STATUS_ACK = "ack" - WARN_METRIC_STATUS_STORE_PREFIX = "warn_metric_" - WARN_METRIC_JOB_INTERVAL = 24 * 7 - WARN_METRIC_NUMBER_OF_ACTIVE_USERS_25 = 25 - WARN_METRIC_JOB_WAIT_TIME = 1000 * 3600 * 24 * 7 // 7 days + WarnMetricStatusLimitReached = "true" + WarnMetricStatusRunonce = "runonce" + WarnMetricStatusAck = "ack" + WarnMetricStatusStorePrefix = "warn_metric_" + WarnMetricJobInterval = 24 * 7 + WarnMetricNumberOfActiveUsers25 = 25 + WarnMetricJobWaitTime = 1000 * 3600 * 24 * 7 // 7 days ) type System struct { @@ -84,9 +84,9 @@ type SystemECDSAKey struct { // ServerBusyState provides serialization for app.Busy. type ServerBusyState struct { - Busy bool `json:"busy"` - Expires int64 `json:"expires"` - Expires_ts string `json:"expires_ts,omitempty"` + Busy bool `json:"busy"` + Expires int64 `json:"expires"` + ExpiresTS string `json:"expires_ts,omitempty"` } type SupportPacket struct { @@ -117,62 +117,62 @@ func ServerBusyStateFromJson(r io.Reader) *ServerBusyState { } var WarnMetricsTable = map[string]WarnMetric{ - SYSTEM_WARN_METRIC_MFA: { - Id: SYSTEM_WARN_METRIC_MFA, + SystemWarnMetricMfa: { + Id: SystemWarnMetricMfa, Limit: -1, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_EMAIL_DOMAIN: { - Id: SYSTEM_WARN_METRIC_EMAIL_DOMAIN, + SystemWarnMetricEmailDomain: { + Id: SystemWarnMetricEmailDomain, Limit: -1, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5, + SystemWarnMetricNumberOfTeams5: { + Id: SystemWarnMetricNumberOfTeams5, Limit: 5, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50, + SystemWarnMetricNumberOfChannels50: { + Id: SystemWarnMetricNumberOfChannels50, Limit: 50, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100, + SystemWarnMetricNumberOfActiveUsers100: { + Id: SystemWarnMetricNumberOfActiveUsers100, Limit: 100, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200, + SystemWarnMetricNumberOfActiveUsers200: { + Id: SystemWarnMetricNumberOfActiveUsers200, Limit: 200, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300, + SystemWarnMetricNumberOfActiveUsers300: { + Id: SystemWarnMetricNumberOfActiveUsers300, Limit: 300, IsBotOnly: true, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500, + SystemWarnMetricNumberOfActiveUsers500: { + Id: SystemWarnMetricNumberOfActiveUsers500, Limit: 500, IsBotOnly: false, IsRunOnce: true, }, - SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M: { - Id: SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M, + SystemWarnMetricNumberOfPosts2m: { + Id: SystemWarnMetricNumberOfPosts2m, Limit: 2000000, IsBotOnly: false, IsRunOnce: true, }, - SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED: { - Id: SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, + SystemMetricSupportEmailNotConfigured: { + Id: SystemMetricSupportEmailNotConfigured, Limit: -1, IsBotOnly: true, IsRunOnce: false, diff --git a/model/team.go b/model/team.go index fc752f30ed..a6de6ce8f9 100644 --- a/model/team.go +++ b/model/team.go @@ -14,15 +14,15 @@ import ( ) const ( - TEAM_OPEN = "O" - TEAM_INVITE = "I" - TEAM_ALLOWED_DOMAINS_MAX_LENGTH = 500 - TEAM_COMPANY_NAME_MAX_LENGTH = 64 - TEAM_DESCRIPTION_MAX_LENGTH = 255 - TEAM_DISPLAY_NAME_MAX_RUNES = 64 - TEAM_EMAIL_MAX_LENGTH = 128 - TEAM_NAME_MAX_LENGTH = 64 - TEAM_NAME_MIN_LENGTH = 2 + TeamOpen = "O" + TeamInvite = "I" + TeamAllowedDomainsMaxLength = 500 + TeamCompanyNameMaxLength = 64 + TeamDescriptionMaxLength = 255 + TeamDisplayNameMaxRunes = 64 + TeamEmailMaxLength = 128 + TeamNameMaxLength = 64 + TeamNameMinLength = 2 ) type Team struct { @@ -149,7 +149,7 @@ func (o *Team) IsValid() *AppError { return NewAppError("Team.IsValid", "model.team.is_valid.update_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.Email) > TEAM_EMAIL_MAX_LENGTH { + if len(o.Email) > TeamEmailMaxLength { return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -157,15 +157,15 @@ func (o *Team) IsValid() *AppError { return NewAppError("Team.IsValid", "model.team.is_valid.email.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if utf8.RuneCountInString(o.DisplayName) == 0 || utf8.RuneCountInString(o.DisplayName) > TEAM_DISPLAY_NAME_MAX_RUNES { + if utf8.RuneCountInString(o.DisplayName) == 0 || utf8.RuneCountInString(o.DisplayName) > TeamDisplayNameMaxRunes { return NewAppError("Team.IsValid", "model.team.is_valid.name.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.Name) > TEAM_NAME_MAX_LENGTH { + if len(o.Name) > TeamNameMaxLength { return NewAppError("Team.IsValid", "model.team.is_valid.url.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.Description) > TEAM_DESCRIPTION_MAX_LENGTH { + if len(o.Description) > TeamDescriptionMaxLength { return NewAppError("Team.IsValid", "model.team.is_valid.description.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -181,15 +181,15 @@ func (o *Team) IsValid() *AppError { return NewAppError("Team.IsValid", "model.team.is_valid.characters.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if !(o.Type == TEAM_OPEN || o.Type == TEAM_INVITE) { + if !(o.Type == TeamOpen || o.Type == TeamInvite) { return NewAppError("Team.IsValid", "model.team.is_valid.type.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.CompanyName) > TEAM_COMPANY_NAME_MAX_LENGTH { + if len(o.CompanyName) > TeamCompanyNameMaxLength { return NewAppError("Team.IsValid", "model.team.is_valid.company.app_error", nil, "id="+o.Id, http.StatusBadRequest) } - if len(o.AllowedDomains) > TEAM_ALLOWED_DOMAINS_MAX_LENGTH { + if len(o.AllowedDomains) > TeamAllowedDomainsMaxLength { return NewAppError("Team.IsValid", "model.team.is_valid.domains.app_error", nil, "id="+o.Id, http.StatusBadRequest) } @@ -239,7 +239,7 @@ func IsValidTeamName(s string) bool { return false } - if len(s) < TEAM_NAME_MIN_LENGTH { + if len(s) < TeamNameMinLength { return false } diff --git a/model/team_test.go b/model/team_test.go index 7d1769306c..6c05fef23c 100644 --- a/model/team_test.go +++ b/model/team_test.go @@ -52,7 +52,7 @@ func TestTeamIsValid(t *testing.T) { require.NotNil(t, err, "should be invalid") o.Name = "zzzzz" - o.Type = TEAM_OPEN + o.Type = TeamOpen o.InviteId = NewId() err = o.IsValid() require.Nil(t, err, err) diff --git a/model/terms_of_service.go b/model/terms_of_service.go index 8ce5d3504b..38f654a5d0 100644 --- a/model/terms_of_service.go +++ b/model/terms_of_service.go @@ -11,8 +11,6 @@ import ( "unicode/utf8" ) -const TERMS_OF_SERVICE_CACHE_SIZE = 1 - type TermsOfService struct { Id string `json:"id"` CreateAt int64 `json:"create_at"` @@ -33,7 +31,7 @@ func (t *TermsOfService) IsValid() *AppError { return InvalidTermsOfServiceError("user_id", t.Id) } - if utf8.RuneCountInString(t.Text) > POST_MESSAGE_MAX_RUNES_V2 { + if utf8.RuneCountInString(t.Text) > PostMessageMaxRunesV2 { return InvalidTermsOfServiceError("text", t.Id) } @@ -57,7 +55,7 @@ func InvalidTermsOfServiceError(fieldName string, termsOfServiceId string) *AppE if termsOfServiceId != "" { details = "terms_of_service_id=" + termsOfServiceId } - return NewAppError("TermsOfService.IsValid", id, map[string]interface{}{"MaxLength": POST_MESSAGE_MAX_RUNES_V2}, details, http.StatusBadRequest) + return NewAppError("TermsOfService.IsValid", id, map[string]interface{}{"MaxLength": PostMessageMaxRunesV2}, details, http.StatusBadRequest) } func (t *TermsOfService) PreSave() { diff --git a/model/terms_of_service_test.go b/model/terms_of_service_test.go index deb0e50be4..3260011926 100644 --- a/model/terms_of_service_test.go +++ b/model/terms_of_service_test.go @@ -24,10 +24,10 @@ func TestTermsOfServiceIsValid(t *testing.T) { s.UserId = NewId() assert.Nil(t, s.IsValid(), "should be valid") - s.Text = strings.Repeat("0", POST_MESSAGE_MAX_RUNES_V2+1) + s.Text = strings.Repeat("0", PostMessageMaxRunesV2+1) assert.NotNil(t, s.IsValid(), "should be invalid") - s.Text = strings.Repeat("0", POST_MESSAGE_MAX_RUNES_V2) + s.Text = strings.Repeat("0", PostMessageMaxRunesV2) assert.Nil(t, s.IsValid(), "should be valid") s.Text = "test" diff --git a/model/token.go b/model/token.go index 2dcf4143e0..90fc729fb6 100644 --- a/model/token.go +++ b/model/token.go @@ -8,9 +8,9 @@ import ( ) const ( - TOKEN_SIZE = 64 - MAX_TOKEN_EXIPRY_TIME = 1000 * 60 * 60 * 48 // 48 hour - TOKEN_TYPE_OAUTH = "oauth" + TokenSize = 64 + MaxTokenExipryTime = 1000 * 60 * 60 * 48 // 48 hour + TokenTypeOAuth = "oauth" ) type Token struct { @@ -22,7 +22,7 @@ type Token struct { func NewToken(tokentype, extra string) *Token { return &Token{ - Token: NewRandomString(TOKEN_SIZE), + Token: NewRandomString(TokenSize), CreateAt: GetMillis(), Type: tokentype, Extra: extra, @@ -30,7 +30,7 @@ func NewToken(tokentype, extra string) *Token { } func (t *Token) IsValid() *AppError { - if len(t.Token) != TOKEN_SIZE { + if len(t.Token) != TokenSize { return NewAppError("Token.IsValid", "model.token.is_valid.size", nil, "", http.StatusInternalServerError) } diff --git a/model/user.go b/model/user.go index 1745d7267a..ba48d6638c 100644 --- a/model/user.go +++ b/model/user.go @@ -23,41 +23,41 @@ import ( ) const ( - ME = "me" - USER_NOTIFY_ALL = "all" - USER_NOTIFY_HERE = "here" - USER_NOTIFY_MENTION = "mention" - USER_NOTIFY_NONE = "none" - DESKTOP_NOTIFY_PROP = "desktop" - DESKTOP_SOUND_NOTIFY_PROP = "desktop_sound" - MARK_UNREAD_NOTIFY_PROP = "mark_unread" - PUSH_NOTIFY_PROP = "push" - PUSH_STATUS_NOTIFY_PROP = "push_status" - EMAIL_NOTIFY_PROP = "email" - CHANNEL_MENTIONS_NOTIFY_PROP = "channel" - COMMENTS_NOTIFY_PROP = "comments" - MENTION_KEYS_NOTIFY_PROP = "mention_keys" - COMMENTS_NOTIFY_NEVER = "never" - COMMENTS_NOTIFY_ROOT = "root" - COMMENTS_NOTIFY_ANY = "any" - FIRST_NAME_NOTIFY_PROP = "first_name" - AUTO_RESPONDER_ACTIVE_NOTIFY_PROP = "auto_responder_active" - AUTO_RESPONDER_MESSAGE_NOTIFY_PROP = "auto_responder_message" + Me = "me" + UserNotifyAll = "all" + UserNotifyHere = "here" + UserNotifyMention = "mention" + UserNotifyNone = "none" + DesktopNotifyProp = "desktop" + DesktopSoundNotifyProp = "desktop_sound" + MarkUnreadNotifyProp = "mark_unread" + PushNotifyProp = "push" + PushStatusNotifyProp = "push_status" + EmailNotifyProp = "email" + ChannelMentionsNotifyProp = "channel" + CommentsNotifyProp = "comments" + MentionKeysNotifyProp = "mention_keys" + CommentsNotifyNever = "never" + CommentsNotifyRoot = "root" + CommentsNotifyAny = "any" + FirstNameNotifyProp = "first_name" + AutoResponderActiveNotifyProp = "auto_responder_active" + AutoResponderMessageNotifyProp = "auto_responder_message" - DEFAULT_LOCALE = "en" - USER_AUTH_SERVICE_EMAIL = "email" + DefaultLocale = "en" + UserAuthServiceEmail = "email" - USER_EMAIL_MAX_LENGTH = 128 - USER_NICKNAME_MAX_RUNES = 64 - USER_POSITION_MAX_RUNES = 128 - USER_FIRST_NAME_MAX_RUNES = 64 - USER_LAST_NAME_MAX_RUNES = 64 - USER_AUTH_DATA_MAX_LENGTH = 128 - USER_NAME_MAX_LENGTH = 64 - USER_NAME_MIN_LENGTH = 1 - USER_PASSWORD_MAX_LENGTH = 72 - USER_LOCALE_MAX_LENGTH = 5 - USER_TIMEZONE_MAX_RUNES = 256 + UserEmailMaxLength = 128 + UserNicknameMaxRunes = 64 + UserPositionMaxRunes = 128 + UserFirstNameMaxRunes = 64 + UserLastNameMaxRunes = 64 + UserAuthDataMaxLength = 128 + UserNameMaxLength = 64 + UserNameMinLength = 1 + UserPasswordMaxLength = 72 + UserLocaleMaxLength = 5 + UserTimezoneMaxRunes = 256 ) //msgp:tuple User @@ -282,27 +282,27 @@ func (u *User) IsValid() *AppError { } } - if len(u.Email) > USER_EMAIL_MAX_LENGTH || u.Email == "" || !IsValidEmail(u.Email) { + if len(u.Email) > UserEmailMaxLength || u.Email == "" || !IsValidEmail(u.Email) { return InvalidUserError("email", u.Id) } - if utf8.RuneCountInString(u.Nickname) > USER_NICKNAME_MAX_RUNES { + if utf8.RuneCountInString(u.Nickname) > UserNicknameMaxRunes { return InvalidUserError("nickname", u.Id) } - if utf8.RuneCountInString(u.Position) > USER_POSITION_MAX_RUNES { + if utf8.RuneCountInString(u.Position) > UserPositionMaxRunes { return InvalidUserError("position", u.Id) } - if utf8.RuneCountInString(u.FirstName) > USER_FIRST_NAME_MAX_RUNES { + if utf8.RuneCountInString(u.FirstName) > UserFirstNameMaxRunes { return InvalidUserError("first_name", u.Id) } - if utf8.RuneCountInString(u.LastName) > USER_LAST_NAME_MAX_RUNES { + if utf8.RuneCountInString(u.LastName) > UserLastNameMaxRunes { return InvalidUserError("last_name", u.Id) } - if u.AuthData != nil && len(*u.AuthData) > USER_AUTH_DATA_MAX_LENGTH { + if u.AuthData != nil && len(*u.AuthData) > UserAuthDataMaxLength { return InvalidUserError("auth_data", u.Id) } @@ -314,7 +314,7 @@ func (u *User) IsValid() *AppError { return InvalidUserError("auth_data_pwd", u.Id) } - if len(u.Password) > USER_PASSWORD_MAX_LENGTH { + if len(u.Password) > UserPasswordMaxLength { return InvalidUserError("password_limit", u.Id) } @@ -325,7 +325,7 @@ func (u *User) IsValid() *AppError { if len(u.Timezone) > 0 { if tzJSON, err := json.Marshal(u.Timezone); err != nil { return NewAppError("User.IsValid", "model.user.is_valid.marshal.app_error", nil, err.Error(), http.StatusInternalServerError) - } else if utf8.RuneCount(tzJSON) > USER_TIMEZONE_MAX_RUNES { + } else if utf8.RuneCount(tzJSON) > UserTimezoneMaxRunes { return InvalidUserError("timezone_limit", u.Id) } } @@ -382,7 +382,7 @@ func (u *User) PreSave() { u.MfaActive = false if u.Locale == "" { - u.Locale = DEFAULT_LOCALE + u.Locale = DefaultLocale } if u.Props == nil { @@ -425,30 +425,30 @@ func (u *User) PreUpdate() { if u.NotifyProps == nil || len(u.NotifyProps) == 0 { u.SetDefaultNotifications() - } else if _, ok := u.NotifyProps[MENTION_KEYS_NOTIFY_PROP]; ok { + } else if _, ok := u.NotifyProps[MentionKeysNotifyProp]; ok { // Remove any blank mention keys - splitKeys := strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") + splitKeys := strings.Split(u.NotifyProps[MentionKeysNotifyProp], ",") goodKeys := []string{} for _, key := range splitKeys { if key != "" { goodKeys = append(goodKeys, strings.ToLower(key)) } } - u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] = strings.Join(goodKeys, ",") + u.NotifyProps[MentionKeysNotifyProp] = strings.Join(goodKeys, ",") } } func (u *User) SetDefaultNotifications() { u.NotifyProps = make(map[string]string) - u.NotifyProps[EMAIL_NOTIFY_PROP] = "true" - u.NotifyProps[PUSH_NOTIFY_PROP] = USER_NOTIFY_MENTION - u.NotifyProps[DESKTOP_NOTIFY_PROP] = USER_NOTIFY_MENTION - u.NotifyProps[DESKTOP_SOUND_NOTIFY_PROP] = "true" - u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] = "" - u.NotifyProps[CHANNEL_MENTIONS_NOTIFY_PROP] = "true" - u.NotifyProps[PUSH_STATUS_NOTIFY_PROP] = STATUS_AWAY - u.NotifyProps[COMMENTS_NOTIFY_PROP] = COMMENTS_NOTIFY_NEVER - u.NotifyProps[FIRST_NAME_NOTIFY_PROP] = "false" + u.NotifyProps[EmailNotifyProp] = "true" + u.NotifyProps[PushNotifyProp] = UserNotifyMention + u.NotifyProps[DesktopNotifyProp] = UserNotifyMention + u.NotifyProps[DesktopSoundNotifyProp] = "true" + u.NotifyProps[MentionKeysNotifyProp] = "" + u.NotifyProps[ChannelMentionsNotifyProp] = "true" + u.NotifyProps[PushStatusNotifyProp] = StatusAway + u.NotifyProps[CommentsNotifyProp] = CommentsNotifyNever + u.NotifyProps[FirstNameNotifyProp] = "false" } func (u *User) UpdateMentionKeysFromUsername(oldUsername string) { @@ -459,16 +459,16 @@ func (u *User) UpdateMentionKeysFromUsername(oldUsername string) { } } - u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] = "" + u.NotifyProps[MentionKeysNotifyProp] = "" if len(nonUsernameKeys) > 0 { - u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] += "," + strings.Join(nonUsernameKeys, ",") + u.NotifyProps[MentionKeysNotifyProp] += "," + strings.Join(nonUsernameKeys, ",") } } func (u *User) GetMentionKeys() []string { var keys []string - for _, key := range strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") { + for _, key := range strings.Split(u.NotifyProps[MentionKeysNotifyProp], ",") { trimmedKey := strings.TrimSpace(key) if trimmedKey == "" { @@ -642,13 +642,13 @@ func (u *User) GetFullName() string { func (u *User) getDisplayName(baseName, nameFormat string) string { displayName := baseName - if nameFormat == SHOW_NICKNAME_FULLNAME { + if nameFormat == ShowNicknameFullName { if u.Nickname != "" { displayName = u.Nickname } else if fullName := u.GetFullName(); fullName != "" { displayName = fullName } - } else if nameFormat == SHOW_FULLNAME { + } else if nameFormat == ShowFullName { if fullName := u.GetFullName(); fullName != "" { displayName = fullName } @@ -698,11 +698,11 @@ func IsValidUserRoles(userRoles string) bool { // Make sure you acually want to use this function. In context.go there are functions to check permissions // This function should not be used to check permissions. func (u *User) IsGuest() bool { - return IsInRole(u.Roles, SYSTEM_GUEST_ROLE_ID) + return IsInRole(u.Roles, SystemGuestRoleId) } func (u *User) IsSystemAdmin() bool { - return IsInRole(u.Roles, SYSTEM_ADMIN_ROLE_ID) + return IsInRole(u.Roles, SystemAdminRoleId) } // Make sure you acually want to use this function. In context.go there are functions to check permissions @@ -726,22 +726,22 @@ func IsInRole(userRoles string, inRole string) bool { } func (u *User) IsSSOUser() bool { - return u.AuthService != "" && u.AuthService != USER_AUTH_SERVICE_EMAIL + return u.AuthService != "" && u.AuthService != UserAuthServiceEmail } func (u *User) IsOAuthUser() bool { - return u.AuthService == SERVICE_GITLAB || - u.AuthService == SERVICE_GOOGLE || - u.AuthService == SERVICE_OFFICE365 || - u.AuthService == SERVICE_OPENID + return u.AuthService == ServiceGitlab || + u.AuthService == ServiceGoogle || + u.AuthService == ServiceOffice365 || + u.AuthService == ServiceOpenid } func (u *User) IsLDAPUser() bool { - return u.AuthService == USER_AUTH_SERVICE_LDAP + return u.AuthService == UserAuthServiceLdap } func (u *User) IsSAMLUser() bool { - return u.AuthService == USER_AUTH_SERVICE_SAML + return u.AuthService == UserAuthServiceSaml } func (u *User) GetPreferredTimezone() string { @@ -877,7 +877,7 @@ var restrictedUsernames = map[string]struct{}{ } func IsValidUsername(s string) bool { - if len(s) < USER_NAME_MIN_LENGTH || len(s) > USER_NAME_MAX_LENGTH { + if len(s) < UserNameMinLength || len(s) > UserNameMaxLength { return false } @@ -890,7 +890,7 @@ func IsValidUsername(s string) bool { } func IsValidUsernameAllowRemote(s string) bool { - if len(s) < USER_NAME_MIN_LENGTH || len(s) > USER_NAME_MAX_LENGTH { + if len(s) < UserNameMinLength || len(s) > UserNameMaxLength { return false } @@ -932,32 +932,32 @@ func CleanUsername(username string) string { } func IsValidUserNotifyLevel(notifyLevel string) bool { - return notifyLevel == CHANNEL_NOTIFY_ALL || - notifyLevel == CHANNEL_NOTIFY_MENTION || - notifyLevel == CHANNEL_NOTIFY_NONE + return notifyLevel == ChannelNotifyAll || + notifyLevel == ChannelNotifyMention || + notifyLevel == ChannelNotifyNone } func IsValidPushStatusNotifyLevel(notifyLevel string) bool { - return notifyLevel == STATUS_ONLINE || - notifyLevel == STATUS_AWAY || - notifyLevel == STATUS_OFFLINE + return notifyLevel == StatusOnline || + notifyLevel == StatusAway || + notifyLevel == StatusOffline } func IsValidCommentsNotifyLevel(notifyLevel string) bool { - return notifyLevel == COMMENTS_NOTIFY_ANY || - notifyLevel == COMMENTS_NOTIFY_ROOT || - notifyLevel == COMMENTS_NOTIFY_NEVER + return notifyLevel == CommentsNotifyAny || + notifyLevel == CommentsNotifyRoot || + notifyLevel == CommentsNotifyNever } func IsValidEmailBatchingInterval(emailInterval string) bool { - return emailInterval == PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY || - emailInterval == PREFERENCE_EMAIL_INTERVAL_FIFTEEN || - emailInterval == PREFERENCE_EMAIL_INTERVAL_HOUR + return emailInterval == PreferenceEmailIntervalImmediately || + emailInterval == PreferenceEmailIntervalFifteen || + emailInterval == PreferenceEmailIntervalHour } func IsValidLocale(locale string) bool { if locale != "" { - if len(locale) > USER_LOCALE_MAX_LENGTH { + if len(locale) > UserLocaleMaxLength { return false } else if _, err := language.Parse(locale); err != nil { return false diff --git a/model/user_search.go b/model/user_search.go index 0a721eacb0..cefeb41a22 100644 --- a/model/user_search.go +++ b/model/user_search.go @@ -8,8 +8,8 @@ import ( "io" ) -const USER_SEARCH_MAX_LIMIT = 1000 -const USER_SEARCH_DEFAULT_LIMIT = 100 +const UserSearchMaxLimit = 1000 +const UserSearchDefaultLimit = 100 // UserSearch captures the parameters provided by a client for initiating a user search. type UserSearch struct { @@ -41,7 +41,7 @@ func UserSearchFromJson(data io.Reader) *UserSearch { json.NewDecoder(data).Decode(&us) if us.Limit == 0 { - us.Limit = USER_SEARCH_DEFAULT_LIMIT + us.Limit = UserSearchDefaultLimit } return &us diff --git a/model/user_test.go b/model/user_test.go index fc5f35dcb7..32f271a867 100644 --- a/model/user_test.go +++ b/model/user_test.go @@ -178,37 +178,37 @@ func TestUserGetFullName(t *testing.T) { func TestUserGetDisplayName(t *testing.T) { user := User{Username: "username"} - assert.Equal(t, user.GetDisplayName(SHOW_FULLNAME), "username", "Display name should be username") - assert.Equal(t, user.GetDisplayName(SHOW_NICKNAME_FULLNAME), "username", "Display name should be username") - assert.Equal(t, user.GetDisplayName(SHOW_USERNAME), "username", "Display name should be username") + assert.Equal(t, user.GetDisplayName(ShowFullName), "username", "Display name should be username") + assert.Equal(t, user.GetDisplayName(ShowNicknameFullName), "username", "Display name should be username") + assert.Equal(t, user.GetDisplayName(ShowUsername), "username", "Display name should be username") user.FirstName = "first" user.LastName = "last" - assert.Equal(t, user.GetDisplayName(SHOW_FULLNAME), "first last", "Display name should be full name") - assert.Equal(t, user.GetDisplayName(SHOW_NICKNAME_FULLNAME), "first last", "Display name should be full name since there is no nickname") - assert.Equal(t, user.GetDisplayName(SHOW_USERNAME), "username", "Display name should be username") + assert.Equal(t, user.GetDisplayName(ShowFullName), "first last", "Display name should be full name") + assert.Equal(t, user.GetDisplayName(ShowNicknameFullName), "first last", "Display name should be full name since there is no nickname") + assert.Equal(t, user.GetDisplayName(ShowUsername), "username", "Display name should be username") user.Nickname = "nickname" - assert.Equal(t, user.GetDisplayName(SHOW_NICKNAME_FULLNAME), "nickname", "Display name should be nickname") + assert.Equal(t, user.GetDisplayName(ShowNicknameFullName), "nickname", "Display name should be nickname") } func TestUserGetDisplayNameWithPrefix(t *testing.T) { user := User{Username: "username"} - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_FULLNAME, "@"), "@username", "Display name should be username") - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_NICKNAME_FULLNAME, "@"), "@username", "Display name should be username") - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_USERNAME, "@"), "@username", "Display name should be username") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowFullName, "@"), "@username", "Display name should be username") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowNicknameFullName, "@"), "@username", "Display name should be username") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowUsername, "@"), "@username", "Display name should be username") user.FirstName = "first" user.LastName = "last" - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_FULLNAME, "@"), "first last", "Display name should be full name") - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_NICKNAME_FULLNAME, "@"), "first last", "Display name should be full name since there is no nickname") - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_USERNAME, "@"), "@username", "Display name should be username") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowFullName, "@"), "first last", "Display name should be full name") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowNicknameFullName, "@"), "first last", "Display name should be full name since there is no nickname") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowUsername, "@"), "@username", "Display name should be username") user.Nickname = "nickname" - assert.Equal(t, user.GetDisplayNameWithPrefix(SHOW_NICKNAME_FULLNAME, "@"), "nickname", "Display name should be nickname") + assert.Equal(t, user.GetDisplayNameWithPrefix(ShowNicknameFullName, "@"), "nickname", "Display name should be nickname") } type usernamesTest struct { diff --git a/model/utils.go b/model/utils.go index 0c5a272c26..a5f90b14cb 100644 --- a/model/utils.go +++ b/model/utils.go @@ -27,11 +27,11 @@ import ( ) const ( - LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz" - UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - NUMBERS = "0123456789" - SYMBOLS = " !\"\\#$%&'()*+,-./:;<=>?@[]^_`|~" - MB = 1 << 20 + LowercaseLetters = "abcdefghijklmnopqrstuvwxyz" + UppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + NUMBERS = "0123456789" + SYMBOLS = " !\"\\#$%&'()*+,-./:;<=>?@[]^_`|~" + MB = 1 << 20 ) type StringInterface map[string]interface{} @@ -415,7 +415,7 @@ func IsValidChannelIdentifier(s string) bool { return false } - if len(s) < CHANNEL_NAME_MIN_LENGTH { + if len(s) < ChannelNameMinLength { return false } diff --git a/model/websocket_client.go b/model/websocket_client.go index cd89e2d8c2..2132d47813 100644 --- a/model/websocket_client.go +++ b/model/websocket_client.go @@ -14,8 +14,8 @@ import ( ) const ( - SOCKET_MAX_MESSAGE_SIZE_KB = 8 * 1024 // 8KB - PING_TIMEOUT_BUFFER_SECONDS = 5 + SocketMaxMessageSizeKb = 8 * 1024 // 8KB + PingTimeoutBufferSeconds = 5 ) type msgType int @@ -66,15 +66,15 @@ func NewWebSocketClient(url, authToken string) (*WebSocketClient, *AppError) { // NewWebSocketClientWithDialer constructs a new WebSocket client with convenience // methods for talking to the server using a custom dialer. func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, *AppError) { - conn, _, err := dialer.Dial(url+API_URL_SUFFIX+"/websocket", nil) + conn, _, err := dialer.Dial(url+ApiUrlSuffix+"/websocket", nil) if err != nil { return nil, NewAppError("NewWebSocketClient", "model.websocket_client.connect_fail.app_error", nil, err.Error(), http.StatusInternalServerError) } client := &WebSocketClient{ Url: url, - ApiUrl: url + API_URL_SUFFIX, - ConnectUrl: url + API_URL_SUFFIX + "/websocket", + ApiUrl: url + ApiUrlSuffix, + ConnectUrl: url + ApiUrlSuffix + "/websocket", Conn: conn, AuthToken: authToken, Sequence: 1, @@ -90,7 +90,7 @@ func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken strin client.configurePingHandling() go client.writer() - client.SendMessage(WEBSOCKET_AUTHENTICATION_CHALLENGE, map[string]interface{}{"token": authToken}) + client.SendMessage(WebsocketAuthenticationChallenge, map[string]interface{}{"token": authToken}) return client, nil } @@ -136,7 +136,7 @@ func (wsc *WebSocketClient) ConnectWithDialer(dialer *websocket.Dialer) *AppErro wsc.EventChannel = make(chan *WebSocketEvent, 100) wsc.ResponseChannel = make(chan *WebSocketResponse, 100) - wsc.SendMessage(WEBSOCKET_AUTHENTICATION_CHALLENGE, map[string]interface{}{"token": wsc.AuthToken}) + wsc.SendMessage(WebsocketAuthenticationChallenge, map[string]interface{}{"token": wsc.AuthToken}) return nil } @@ -282,7 +282,7 @@ func (wsc *WebSocketClient) GetStatusesByIds(userIds []string) { func (wsc *WebSocketClient) configurePingHandling() { wsc.Conn.SetPingHandler(wsc.pingHandler) - wsc.pingTimeoutTimer = time.NewTimer(time.Second * (60 + PING_TIMEOUT_BUFFER_SECONDS)) + wsc.pingTimeoutTimer = time.NewTimer(time.Second * (60 + PingTimeoutBufferSeconds)) go wsc.pingWatchdog() } @@ -309,11 +309,11 @@ func (wsc *WebSocketClient) pingWatchdog() { if !wsc.pingTimeoutTimer.Stop() { <-wsc.pingTimeoutTimer.C } - wsc.pingTimeoutTimer.Reset(time.Second * (60 + PING_TIMEOUT_BUFFER_SECONDS)) + wsc.pingTimeoutTimer.Reset(time.Second * (60 + PingTimeoutBufferSeconds)) case <-wsc.pingTimeoutTimer.C: wsc.PingTimeoutChannel <- true - wsc.pingTimeoutTimer.Reset(time.Second * (60 + PING_TIMEOUT_BUFFER_SECONDS)) + wsc.pingTimeoutTimer.Reset(time.Second * (60 + PingTimeoutBufferSeconds)) case <-wsc.quitPingWatchdog: return } diff --git a/model/websocket_message.go b/model/websocket_message.go index 9a845d36bd..6621a29315 100644 --- a/model/websocket_message.go +++ b/model/websocket_message.go @@ -11,69 +11,69 @@ import ( ) const ( - WEBSOCKET_EVENT_TYPING = "typing" - WEBSOCKET_EVENT_POSTED = "posted" - WEBSOCKET_EVENT_POST_EDITED = "post_edited" - WEBSOCKET_EVENT_POST_DELETED = "post_deleted" - WEBSOCKET_EVENT_POST_UNREAD = "post_unread" - WEBSOCKET_EVENT_CHANNEL_CONVERTED = "channel_converted" - WEBSOCKET_EVENT_CHANNEL_CREATED = "channel_created" - WEBSOCKET_EVENT_CHANNEL_DELETED = "channel_deleted" - WEBSOCKET_EVENT_CHANNEL_RESTORED = "channel_restored" - WEBSOCKET_EVENT_CHANNEL_UPDATED = "channel_updated" - WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED = "channel_member_updated" - WEBSOCKET_EVENT_CHANNEL_SCHEME_UPDATED = "channel_scheme_updated" - WEBSOCKET_EVENT_DIRECT_ADDED = "direct_added" - WEBSOCKET_EVENT_GROUP_ADDED = "group_added" - WEBSOCKET_EVENT_NEW_USER = "new_user" - WEBSOCKET_EVENT_ADDED_TO_TEAM = "added_to_team" - WEBSOCKET_EVENT_LEAVE_TEAM = "leave_team" - WEBSOCKET_EVENT_UPDATE_TEAM = "update_team" - WEBSOCKET_EVENT_DELETE_TEAM = "delete_team" - WEBSOCKET_EVENT_RESTORE_TEAM = "restore_team" - WEBSOCKET_EVENT_UPDATE_TEAM_SCHEME = "update_team_scheme" - WEBSOCKET_EVENT_USER_ADDED = "user_added" - WEBSOCKET_EVENT_USER_UPDATED = "user_updated" - WEBSOCKET_EVENT_USER_ROLE_UPDATED = "user_role_updated" - WEBSOCKET_EVENT_MEMBERROLE_UPDATED = "memberrole_updated" - WEBSOCKET_EVENT_USER_REMOVED = "user_removed" - WEBSOCKET_EVENT_PREFERENCE_CHANGED = "preference_changed" - WEBSOCKET_EVENT_PREFERENCES_CHANGED = "preferences_changed" - WEBSOCKET_EVENT_PREFERENCES_DELETED = "preferences_deleted" - WEBSOCKET_EVENT_EPHEMERAL_MESSAGE = "ephemeral_message" - WEBSOCKET_EVENT_STATUS_CHANGE = "status_change" - WEBSOCKET_EVENT_HELLO = "hello" - WEBSOCKET_AUTHENTICATION_CHALLENGE = "authentication_challenge" - WEBSOCKET_EVENT_REACTION_ADDED = "reaction_added" - WEBSOCKET_EVENT_REACTION_REMOVED = "reaction_removed" - WEBSOCKET_EVENT_RESPONSE = "response" - WEBSOCKET_EVENT_EMOJI_ADDED = "emoji_added" - WEBSOCKET_EVENT_CHANNEL_VIEWED = "channel_viewed" - WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED = "plugin_statuses_changed" - WEBSOCKET_EVENT_PLUGIN_ENABLED = "plugin_enabled" - WEBSOCKET_EVENT_PLUGIN_DISABLED = "plugin_disabled" - WEBSOCKET_EVENT_ROLE_UPDATED = "role_updated" - WEBSOCKET_EVENT_LICENSE_CHANGED = "license_changed" - WEBSOCKET_EVENT_CONFIG_CHANGED = "config_changed" - WEBSOCKET_EVENT_OPEN_DIALOG = "open_dialog" - WEBSOCKET_EVENT_GUESTS_DEACTIVATED = "guests_deactivated" - WEBSOCKET_EVENT_USER_ACTIVATION_STATUS_CHANGE = "user_activation_status_change" - WEBSOCKET_EVENT_RECEIVED_GROUP = "received_group" - WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_TEAM = "received_group_associated_to_team" - WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_TEAM = "received_group_not_associated_to_team" - WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_CHANNEL = "received_group_associated_to_channel" - WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_CHANNEL = "received_group_not_associated_to_channel" - WEBSOCKET_EVENT_SIDEBAR_CATEGORY_CREATED = "sidebar_category_created" - WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED = "sidebar_category_updated" - WEBSOCKET_EVENT_SIDEBAR_CATEGORY_DELETED = "sidebar_category_deleted" - WEBSOCKET_EVENT_SIDEBAR_CATEGORY_ORDER_UPDATED = "sidebar_category_order_updated" - WEBSOCKET_WARN_METRIC_STATUS_RECEIVED = "warn_metric_status_received" - WEBSOCKET_WARN_METRIC_STATUS_REMOVED = "warn_metric_status_removed" - WEBSOCKET_EVENT_CLOUD_PAYMENT_STATUS_UPDATED = "cloud_payment_status_updated" - WEBSOCKET_EVENT_THREAD_UPDATED = "thread_updated" - WEBSOCKET_EVENT_THREAD_FOLLOW_CHANGED = "thread_follow_changed" - WEBSOCKET_EVENT_THREAD_READ_CHANGED = "thread_read_changed" - WEBSOCKET_FIRST_ADMIN_VISIT_MARKETPLACE_STATUS_RECEIVED = "first_admin_visit_marketplace_status_received" + WebsocketEventTyping = "typing" + WebsocketEventPosted = "posted" + WebsocketEventPostEdited = "post_edited" + WebsocketEventPostDeleted = "post_deleted" + WebsocketEventPostUnread = "post_unread" + WebsocketEventChannelConverted = "channel_converted" + WebsocketEventChannelCreated = "channel_created" + WebsocketEventChannelDeleted = "channel_deleted" + WebsocketEventChannelRestored = "channel_restored" + WebsocketEventChannelUpdated = "channel_updated" + WebsocketEventChannelMemberUpdated = "channel_member_updated" + WebsocketEventChannelSchemeUpdated = "channel_scheme_updated" + WebsocketEventDirectAdded = "direct_added" + WebsocketEventGroupAdded = "group_added" + WebsocketEventNewUser = "new_user" + WebsocketEventAddedToTeam = "added_to_team" + WebsocketEventLeaveTeam = "leave_team" + WebsocketEventUpdateTeam = "update_team" + WebsocketEventDeleteTeam = "delete_team" + WebsocketEventRestoreTeam = "restore_team" + WebsocketEventUpdateTeamScheme = "update_team_scheme" + WebsocketEventUserAdded = "user_added" + WebsocketEventUserUpdated = "user_updated" + WebsocketEventUserRoleUpdated = "user_role_updated" + WebsocketEventMemberroleUpdated = "memberrole_updated" + WebsocketEventUserRemoved = "user_removed" + WebsocketEventPreferenceChanged = "preference_changed" + WebsocketEventPreferencesChanged = "preferences_changed" + WebsocketEventPreferencesDeleted = "preferences_deleted" + WebsocketEventEphemeralMessage = "ephemeral_message" + WebsocketEventStatusChange = "status_change" + WebsocketEventHello = "hello" + WebsocketAuthenticationChallenge = "authentication_challenge" + WebsocketEventReactionAdded = "reaction_added" + WebsocketEventReactionRemoved = "reaction_removed" + WebsocketEventResponse = "response" + WebsocketEventEmojiAdded = "emoji_added" + WebsocketEventChannelViewed = "channel_viewed" + WebsocketEventPluginStatusesChanged = "plugin_statuses_changed" + WebsocketEventPluginEnabled = "plugin_enabled" + WebsocketEventPluginDisabled = "plugin_disabled" + WebsocketEventRoleUpdated = "role_updated" + WebsocketEventLicenseChanged = "license_changed" + WebsocketEventConfigChanged = "config_changed" + WebsocketEventOpenDialog = "open_dialog" + WebsocketEventGuestsDeactivated = "guests_deactivated" + WebsocketEventUserActivationStatusChange = "user_activation_status_change" + WebsocketEventReceivedGroup = "received_group" + WebsocketEventReceivedGroupAssociatedToTeam = "received_group_associated_to_team" + WebsocketEventReceivedGroupNotAssociatedToTeam = "received_group_not_associated_to_team" + WebsocketEventReceivedGroupAssociatedToChannel = "received_group_associated_to_channel" + WebsocketEventReceivedGroupNotAssociatedToChannel = "received_group_not_associated_to_channel" + WebsocketEventSidebarCategoryCreated = "sidebar_category_created" + WebsocketEventSidebarCategoryUpdated = "sidebar_category_updated" + WebsocketEventSidebarCategoryDeleted = "sidebar_category_deleted" + WebsocketEventSidebarCategoryOrderUpdated = "sidebar_category_order_updated" + WebsocketWarnMetricStatusReceived = "warn_metric_status_received" + WebsocketWarnMetricStatusRemoved = "warn_metric_status_removed" + WebsocketEventCloudPaymentStatusUpdated = "cloud_payment_status_updated" + WebsocketEventThreadUpdated = "thread_updated" + WebsocketEventThreadFollowChanged = "thread_follow_changed" + WebsocketEventThreadReadChanged = "thread_read_changed" + WebsocketFirstAdminVisitMarketplaceStatusReceived = "first_admin_visit_marketplace_status_received" ) type WebSocketMessage interface { @@ -264,7 +264,7 @@ func NewWebSocketResponse(status string, seqReply int64, data map[string]interfa } func NewWebSocketError(seqReply int64, err *AppError) *WebSocketResponse { - return &WebSocketResponse{Status: STATUS_FAIL, SeqReply: seqReply, Error: err} + return &WebSocketResponse{Status: StatusFail, SeqReply: seqReply, Error: err} } func (m *WebSocketResponse) IsValid() bool { @@ -272,7 +272,7 @@ func (m *WebSocketResponse) IsValid() bool { } func (m *WebSocketResponse) EventType() string { - return WEBSOCKET_EVENT_RESPONSE + return WebsocketEventResponse } func (m *WebSocketResponse) ToJson() string { diff --git a/model/websocket_message_test.go b/model/websocket_message_test.go index cbfb830cc4..37e6c9e33d 100644 --- a/model/websocket_message_test.go +++ b/model/websocket_message_test.go @@ -105,7 +105,7 @@ func TestWebSocketResponse(t *testing.T) { } func TestWebSocketEvent_PrecomputeJSON(t *testing.T) { - event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil) + event := NewWebSocketEvent(WebsocketEventPosted, "foo", "bar", "baz", nil) event = event.SetSequence(7) before := event.ToJson() @@ -118,7 +118,7 @@ func TestWebSocketEvent_PrecomputeJSON(t *testing.T) { var stringSink string func BenchmarkWebSocketEvent_ToJson(b *testing.B) { - event := NewWebSocketEvent(WEBSOCKET_EVENT_POSTED, "foo", "bar", "baz", nil) + event := NewWebSocketEvent(WebsocketEventPosted, "foo", "bar", "baz", nil) for i := 0; i < 100; i++ { event.GetData()[NewId()] = NewId() } diff --git a/plugin/helpers_bots_test.go b/plugin/helpers_bots_test.go index 68c64b94e1..6983688a45 100644 --- a/plugin/helpers_bots_test.go +++ b/plugin/helpers_bots_test.go @@ -413,13 +413,13 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api - shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{Type: model.POST_HEADER_CHANGE, UserId: expectedBotID}, plugin.AllowSystemMessages(), plugin.AllowBots()) + shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{Type: model.PostTypeHeaderChange, UserId: expectedBotID}, plugin.AllowSystemMessages(), plugin.AllowBots()) assert.False(t, shouldProcessMessage) }) t.Run("should not process as the post is generated by system", func(t *testing.T) { - shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{Type: model.POST_HEADER_CHANGE}) + shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{Type: model.PostTypeHeaderChange}) assert.False(t, shouldProcessMessage) }) @@ -427,7 +427,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should not process as the post is sent to another channel", func(t *testing.T) { channelID := "channel-id" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) @@ -455,7 +455,7 @@ func TestShouldProcessMessage(t *testing.T) { channelID := "1" channel := model.Channel{ Name: "user1__" + expectedBotID, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } api := setupAPI() api.On("GetChannel", channelID).Return(&channel, nil) @@ -473,7 +473,7 @@ func TestShouldProcessMessage(t *testing.T) { api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api - shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, + shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.PostTypeHeaderChange, ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.FilterChannelIDs([]string{channelID}), plugin.AllowBots(), plugin.FilterUserIDs([]string{"1"})) assert.True(t, shouldProcessMessage) @@ -485,7 +485,7 @@ func TestShouldProcessMessage(t *testing.T) { api.On("KVGet", plugin.BotUserKey).Return(nil, nil) p.API = api - shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, + shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.PostTypeHeaderChange, ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.FilterChannelIDs([]string{channelID}), plugin.AllowBots(), plugin.FilterUserIDs([]string{"1"})) assert.True(t, shouldProcessMessage) @@ -496,13 +496,13 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() channel := model.Channel{ Name: "user1__" + expectedBotID, - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } api.On("GetChannel", channelID).Return(&channel, nil) api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api - shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, + shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.PostTypeHeaderChange, ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.AllowBots()) assert.True(t, shouldProcessMessage) @@ -511,7 +511,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should not process the message which have from_webhook", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) @@ -524,7 +524,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should process the message which have from_webhook with allow webhook plugin", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) @@ -537,7 +537,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should process the message where from_webhook is not set", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) @@ -550,7 +550,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should process the message which have from_webhook false", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) @@ -564,7 +564,7 @@ func TestShouldProcessMessage(t *testing.T) { userID := "user-id" channelID := "1" api := setupAPI() - api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.ChannelTypeGroup}, nil) p.API = api api.On("GetUser", userID).Return(&model.User{IsBot: false}, nil) diff --git a/plugin/scheduler/scheduler.go b/plugin/scheduler/scheduler.go index f9f97754e6..ada0133f98 100644 --- a/plugin/scheduler/scheduler.go +++ b/plugin/scheduler/scheduler.go @@ -26,7 +26,7 @@ func (scheduler *Scheduler) Name() string { } func (scheduler *Scheduler) JobType() string { - return model.JOB_TYPE_PLUGINS + return model.JobTypePlugins } func (scheduler *Scheduler) Enabled(cfg *model.Config) bool { @@ -41,7 +41,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { mlog.Debug("Scheduling Job", mlog.String("scheduler", scheduler.Name())) - job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_PLUGINS, nil) + job, err := scheduler.App.Srv().Jobs.CreateJob(model.JobTypePlugins, nil) if err != nil { return nil, err } diff --git a/scripts/config_generator/main_test.go b/scripts/config_generator/main_test.go index 6915cd9905..3bc239d3f2 100644 --- a/scripts/config_generator/main_test.go +++ b/scripts/config_generator/main_test.go @@ -29,13 +29,13 @@ func TestDefaultsGenerator(t *testing.T) { require.Equal(t, *config.SqlSettings.AtRestEncryptKey, "") require.Equal(t, *config.FileSettings.PublicLinkSalt, "") - require.Equal(t, *config.Office365Settings.Scope, model.OFFICE365_SETTINGS_DEFAULT_SCOPE) - require.Equal(t, *config.Office365Settings.AuthEndpoint, model.OFFICE365_SETTINGS_DEFAULT_AUTH_ENDPOINT) - require.Equal(t, *config.Office365Settings.UserApiEndpoint, model.OFFICE365_SETTINGS_DEFAULT_USER_API_ENDPOINT) - require.Equal(t, *config.Office365Settings.TokenEndpoint, model.OFFICE365_SETTINGS_DEFAULT_TOKEN_ENDPOINT) + require.Equal(t, *config.Office365Settings.Scope, model.Office365SettingsDefaultScope) + require.Equal(t, *config.Office365Settings.AuthEndpoint, model.Office365SettingsDefaultAuthEndpoint) + require.Equal(t, *config.Office365Settings.UserApiEndpoint, model.Office365SettingsDefaultUserApiEndpoint) + require.Equal(t, *config.Office365Settings.TokenEndpoint, model.Office365SettingsDefaultTokenEndpoint) - require.Equal(t, *config.GoogleSettings.Scope, model.GOOGLE_SETTINGS_DEFAULT_SCOPE) - require.Equal(t, *config.GoogleSettings.AuthEndpoint, model.GOOGLE_SETTINGS_DEFAULT_AUTH_ENDPOINT) - require.Equal(t, *config.GoogleSettings.UserApiEndpoint, model.GOOGLE_SETTINGS_DEFAULT_USER_API_ENDPOINT) - require.Equal(t, *config.GoogleSettings.TokenEndpoint, model.GOOGLE_SETTINGS_DEFAULT_TOKEN_ENDPOINT) + require.Equal(t, *config.GoogleSettings.Scope, model.GoogleSettingsDefaultScope) + require.Equal(t, *config.GoogleSettings.AuthEndpoint, model.GoogleSettingsDefaultAuthEndpoint) + require.Equal(t, *config.GoogleSettings.UserApiEndpoint, model.GoogleSettingsDefaultUserApiEndpoint) + require.Equal(t, *config.GoogleSettings.TokenEndpoint, model.GoogleSettingsDefaultTokenEndpoint) } diff --git a/services/awsmeter/awsmeter.go b/services/awsmeter/awsmeter.go index ebf5841790..90e6f38b68 100644 --- a/services/awsmeter/awsmeter.go +++ b/services/awsmeter/awsmeter.go @@ -98,7 +98,7 @@ func (awsm *AwsMeter) GetUserCategoryUsage(dimensions []string, startTime time.T var err error switch dimension { - case model.AWS_METERING_DIMENSION_USAGE_HRS: + case model.AwsMeteringDimensionUsageHrs: userCount, err = awsm.store.User().AnalyticsActiveCountForPeriod(model.GetMillisForTime(startTime), model.GetMillisForTime(endTime), model.UserCountOptions{}) if err != nil { mlog.Warn("Failed to obtain usage data", mlog.String("dimension", dimension), mlog.String("start", startTime.String()), mlog.Int64("count", userCount), mlog.Err(err)) diff --git a/services/awsmeter/awsmeter_test.go b/services/awsmeter/awsmeter_test.go index 6c661dbdec..9b2d551810 100644 --- a/services/awsmeter/awsmeter_test.go +++ b/services/awsmeter/awsmeter_test.go @@ -42,7 +42,7 @@ func String(i string) *string { func TestAwsMeterUsage(t *testing.T) { startTime := time.Now() endTime := time.Now() - dimensions := []string{model.AWS_METERING_DIMENSION_USAGE_HRS} + dimensions := []string{model.AwsMeteringDimensionUsageHrs} userStoreMock := mocks.UserStore{} userStoreMock.On("AnalyticsActiveCountForPeriod", model.GetMillisForTime(startTime), model.GetMillisForTime(endTime), mock.AnythingOfType("model.UserCountOptions")).Return(int64(2), nil) @@ -52,7 +52,7 @@ func TestAwsMeterUsage(t *testing.T) { reports := make([]*AWSMeterReport, 1) reports[0] = &AWSMeterReport{ - Dimension: model.AWS_METERING_DIMENSION_USAGE_HRS, + Dimension: model.AwsMeteringDimensionUsageHrs, Value: 2, Timestamp: startTime, } @@ -108,7 +108,7 @@ func TestAwsMeterUsage(t *testing.T) { func TestAwsMeterUsageWithDBError(t *testing.T) { startTime := time.Now() endTime := time.Now() - dimensions := []string{model.AWS_METERING_DIMENSION_USAGE_HRS} + dimensions := []string{model.AwsMeteringDimensionUsageHrs} userStoreMock := mocks.UserStore{} userStoreMock.On("AnalyticsActiveCountForPeriod", model.GetMillisForTime(startTime), model.GetMillisForTime(endTime), mock.AnythingOfType("model.UserCountOptions")).Return(int64(0), errors.New("error")) @@ -118,7 +118,7 @@ func TestAwsMeterUsageWithDBError(t *testing.T) { reports := make([]*AWSMeterReport, 1) reports[0] = &AWSMeterReport{ - Dimension: model.AWS_METERING_DIMENSION_USAGE_HRS, + Dimension: model.AwsMeteringDimensionUsageHrs, Value: 2, Timestamp: startTime, } diff --git a/services/imageproxy/atmos_camo_test.go b/services/imageproxy/atmos_camo_test.go index 9d9393cd05..6807415b3b 100644 --- a/services/imageproxy/atmos_camo_test.go +++ b/services/imageproxy/atmos_camo_test.go @@ -27,7 +27,7 @@ func makeTestAtmosCamoProxy() *ImageProxy { }, ImageProxySettings: model.ImageProxySettings{ Enable: model.NewBool(true), - ImageProxyType: model.NewString(model.IMAGE_PROXY_TYPE_ATMOS_CAMO), + ImageProxyType: model.NewString(model.ImageProxyTypeAtmosCamo), RemoteImageProxyURL: model.NewString("http://images.example.com"), RemoteImageProxyOptions: model.NewString("7e5f3fab20b94782b43cdb022a66985ef28ba355df2c5d5da3c9a05e4b697bac"), }, diff --git a/services/imageproxy/imageproxy.go b/services/imageproxy/imageproxy.go index 87dccf15db..8cea50c421 100644 --- a/services/imageproxy/imageproxy.go +++ b/services/imageproxy/imageproxy.go @@ -70,9 +70,9 @@ func (proxy *ImageProxy) makeBackend(enable bool, proxyType string) ImageProxyBa } switch proxyType { - case model.IMAGE_PROXY_TYPE_LOCAL: + case model.ImageProxyTypeLocal: return makeLocalBackend(proxy) - case model.IMAGE_PROXY_TYPE_ATMOS_CAMO: + case model.ImageProxyTypeAtmosCamo: return makeAtmosCamoBackend(proxy) default: return nil diff --git a/services/imageproxy/local_test.go b/services/imageproxy/local_test.go index 80a054b3f3..3065c72682 100644 --- a/services/imageproxy/local_test.go +++ b/services/imageproxy/local_test.go @@ -27,7 +27,7 @@ func makeTestLocalProxy() *ImageProxy { }, ImageProxySettings: model.ImageProxySettings{ Enable: model.NewBool(true), - ImageProxyType: model.NewString(model.IMAGE_PROXY_TYPE_LOCAL), + ImageProxyType: model.NewString(model.ImageProxyTypeLocal), }, }, } diff --git a/services/remotecluster/sendfile.go b/services/remotecluster/sendfile.go index 443835f87d..14df04c17e 100644 --- a/services/remotecluster/sendfile.go +++ b/services/remotecluster/sendfile.go @@ -98,15 +98,15 @@ func (rcs *Service) sendFileToRemote(timeout time.Duration, task sendFileTask) ( if err != nil { return nil, fmt.Errorf("invalid siteURL while sending file to remote %s: %w", task.rc.RemoteId, err) } - u.Path = path.Join(u.Path, model.API_URL_SUFFIX, "remotecluster", "upload", task.us.Id) + u.Path = path.Join(u.Path, model.ApiUrlSuffix, "remotecluster", "upload", task.us.Id) req, err := http.NewRequest("POST", u.String(), r) if err != nil { return nil, err } - req.Header.Set(model.HEADER_REMOTECLUSTER_ID, task.rc.RemoteId) - req.Header.Set(model.HEADER_REMOTECLUSTER_TOKEN, task.rc.RemoteToken) + req.Header.Set(model.HeaderRemoteclusterId, task.rc.RemoteId) + req.Header.Set(model.HeaderRemoteclusterToken, task.rc.RemoteToken) ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() diff --git a/services/remotecluster/sendmsg.go b/services/remotecluster/sendmsg.go index 81108d2d5b..5a03f0cf22 100644 --- a/services/remotecluster/sendmsg.go +++ b/services/remotecluster/sendmsg.go @@ -148,8 +148,8 @@ func (rcs *Service) sendFrameToRemote(timeout time.Duration, rc *model.RemoteClu return nil, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set(model.HEADER_REMOTECLUSTER_ID, rc.RemoteId) - req.Header.Set(model.HEADER_REMOTECLUSTER_TOKEN, rc.RemoteToken) + req.Header.Set(model.HeaderRemoteclusterId, rc.RemoteId) + req.Header.Set(model.HeaderRemoteclusterToken, rc.RemoteToken) resp, err := rcs.httpClient.Do(req.WithContext(ctx)) if metrics := rcs.server.GetMetrics(); metrics != nil { diff --git a/services/remotecluster/sendprofileImage.go b/services/remotecluster/sendprofileImage.go index d4558f47ed..85e7828929 100644 --- a/services/remotecluster/sendprofileImage.go +++ b/services/remotecluster/sendprofileImage.go @@ -99,7 +99,7 @@ func (rcs *Service) sendProfileImageToRemote(timeout time.Duration, task sendPro if err != nil { return fmt.Errorf("invalid siteURL while sending file to remote %s: %w", task.rc.RemoteId, err) } - u.Path = path.Join(u.Path, model.API_URL_SUFFIX, "remotecluster", task.userID, "image") + u.Path = path.Join(u.Path, model.ApiUrlSuffix, "remotecluster", task.userID, "image") body := &bytes.Buffer{} writer := multipart.NewWriter(body) @@ -122,8 +122,8 @@ func (rcs *Service) sendProfileImageToRemote(timeout time.Duration, task sendPro return err } req.Header.Set("Content-Type", writer.FormDataContentType()) - req.Header.Set(model.HEADER_REMOTECLUSTER_ID, task.rc.RemoteId) - req.Header.Set(model.HEADER_REMOTECLUSTER_TOKEN, task.rc.RemoteToken) + req.Header.Set(model.HeaderRemoteclusterId, task.rc.RemoteId) + req.Header.Set(model.HeaderRemoteclusterToken, task.rc.RemoteToken) ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() diff --git a/services/remotecluster/sendprofileImage_test.go b/services/remotecluster/sendprofileImage_test.go index d5680062cd..144dcda2f9 100644 --- a/services/remotecluster/sendprofileImage_test.go +++ b/services/remotecluster/sendprofileImage_test.go @@ -40,14 +40,14 @@ func TestService_sendProfileImageToRemote(t *testing.T) { if shouldError.get() { w.WriteHeader(http.StatusInternalServerError) resp := make(map[string]string) - resp[model.STATUS] = model.STATUS_FAIL + resp[model.STATUS] = model.StatusFail w.Write([]byte(model.MapToJson(resp))) return } - status := model.STATUS_OK + status := model.StatusOk defer func(s *string) { - if *s != model.STATUS_OK { + if *s != model.StatusOk { w.WriteHeader(http.StatusInternalServerError) } resp := make(map[string]string) @@ -56,20 +56,20 @@ func TestService_sendProfileImageToRemote(t *testing.T) { }(&status) if err := r.ParseMultipartForm(1024 * 1024); err != nil { - status = model.STATUS_FAIL + status = model.StatusFail assert.Fail(t, "connect parse multipart form", err) return } m := r.MultipartForm if m == nil { - status = model.STATUS_FAIL + status = model.StatusFail assert.Fail(t, "multipart form missing") return } imageArray, ok := m.File["image"] if !ok || len(imageArray) != 1 { - status = model.STATUS_FAIL + status = model.StatusFail assert.Fail(t, "image missing") return } @@ -77,7 +77,7 @@ func TestService_sendProfileImageToRemote(t *testing.T) { imageData := imageArray[0] file, err := imageData.Open() if err != nil { - status = model.STATUS_FAIL + status = model.StatusFail assert.Fail(t, "cannot open multipart form file") return } @@ -85,7 +85,7 @@ func TestService_sendProfileImageToRemote(t *testing.T) { img, err := png.Decode(file) if err != nil || imageWidth != img.Bounds().Max.X || imageHeight != img.Bounds().Max.Y { - status = model.STATUS_FAIL + status = model.StatusFail assert.Fail(t, "cannot decode png", err) return } diff --git a/services/remotecluster/service.go b/services/remotecluster/service.go index e8726bc598..397267008c 100644 --- a/services/remotecluster/service.go +++ b/services/remotecluster/service.go @@ -31,8 +31,8 @@ const ( ConfirmInviteURL = "api/v4/remotecluster/confirm_invite" InvitationTopic = "invitation" PingTopic = "ping" - ResponseStatusOK = model.STATUS_OK - ResponseStatusFail = model.STATUS_FAIL + ResponseStatusOK = model.StatusOk + ResponseStatusFail = model.StatusFail InviteExpiresAfter = time.Hour * 48 ) diff --git a/services/searchengine/bleveengine/bleve_test.go b/services/searchengine/bleveengine/bleve_test.go index e8a7aee314..acee18c1b9 100644 --- a/services/searchengine/bleveengine/bleve_test.go +++ b/services/searchengine/bleveengine/bleve_test.go @@ -47,7 +47,7 @@ func (s *BleveEngineTestSuite) setupIndexes() { func (s *BleveEngineTestSuite) setupStore() { driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") if driverName == "" { - driverName = model.DATABASE_DRIVER_POSTGRES + driverName = model.DatabaseDriverPostgres } s.SQLSettings = storetest.MakeSqlSettings(driverName, false) s.SQLStore = sqlstore.New(*s.SQLSettings, nil) diff --git a/services/searchengine/bleveengine/indexer/indexing_job_test.go b/services/searchengine/bleveengine/indexer/indexing_job_test.go index 0f47e58ad7..54dec0d137 100644 --- a/services/searchengine/bleveengine/indexer/indexing_job_test.go +++ b/services/searchengine/bleveengine/indexer/indexing_job_test.go @@ -25,12 +25,12 @@ func TestBleveIndexer(t *testing.T) { job := &model.Job{ Id: model.NewId(), CreateAt: model.GetMillis(), - Status: model.JOB_STATUS_PENDING, - Type: model.JOB_TYPE_BLEVE_POST_INDEXING, + Status: model.JobStatusPending, + Type: model.JobTypeBlevePostIndexing, } - mockStore.JobStore.On("UpdateStatusOptimistically", job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) - mockStore.JobStore.On("UpdateOptimistically", job, model.JOB_STATUS_IN_PROGRESS).Return(true, nil) + mockStore.JobStore.On("UpdateStatusOptimistically", job.Id, model.JobStatusPending, model.JobStatusInProgress).Return(true, nil) + mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) mockStore.PostStore.On("GetOldestEntityCreationTime").Return(int64(1), errors.New("")) // intentionally return error to return from function tempDir, err := ioutil.TempDir("", "setupConfigFile") diff --git a/services/searchengine/bleveengine/search.go b/services/searchengine/bleveengine/search.go index d9cf3c44af..7eab18541c 100644 --- a/services/searchengine/bleveengine/search.go +++ b/services/searchengine/bleveengine/search.go @@ -326,7 +326,7 @@ func (b *BleveEngine) SearchChannels(teamId, term string) ([]string, *model.AppE } query := bleve.NewSearchRequest(bleve.NewConjunctionQuery(queries...)) - query.Size = model.CHANNEL_SEARCH_DEFAULT_LIMIT + query.Size = model.ChannelSearchDefaultLimit results, err := b.ChannelIndex.Search(query) if err != nil { return nil, model.NewAppError("Bleveengine.SearchChannels", "bleveengine.search_channels.error", nil, err.Error(), http.StatusInternalServerError) diff --git a/services/sharedchannel/channelinvite.go b/services/sharedchannel/channelinvite.go index 5812dcf479..0115aaf9fa 100644 --- a/services/sharedchannel/channelinvite.go +++ b/services/sharedchannel/channelinvite.go @@ -180,7 +180,7 @@ func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model } func (scs *Service) handleChannelCreation(invite channelInviteMsg, rc *model.RemoteCluster) (*model.Channel, error) { - if invite.Type == model.CHANNEL_DIRECT { + if invite.Type == model.ChannelTypeDirect { return scs.createDirectChannel(invite) } diff --git a/services/sharedchannel/channelinvite_test.go b/services/sharedchannel/channelinvite_test.go index 263d7c27c6..53cee2c4d5 100644 --- a/services/sharedchannel/channelinvite_test.go +++ b/services/sharedchannel/channelinvite_test.go @@ -84,8 +84,8 @@ func TestOnReceiveChannelInvite(t *testing.T) { mockServer = scs.server.(*MockServerIface) mockServer.On("GetStore").Return(mockStore) - createPostPermission := model.ChannelModeratedPermissionsMap[model.PERMISSION_CREATE_POST.Id] - createReactionPermission := model.ChannelModeratedPermissionsMap[model.PERMISSION_ADD_REACTION.Id] + createPostPermission := model.ChannelModeratedPermissionsMap[model.PermissionCreatePost.Id] + createReactionPermission := model.ChannelModeratedPermissionsMap[model.PermissionAddReaction.Id] updateMap := model.ChannelModeratedRolesPatch{ Guests: model.NewBool(false), Members: model.NewBool(false), @@ -166,7 +166,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { ChannelId: model.NewId(), TeamId: model.NewId(), ReadOnly: false, - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, DirectParticipantIDs: []string{model.NewId(), model.NewId()}, } payload, err := json.Marshal(invitation) diff --git a/services/sharedchannel/service.go b/services/sharedchannel/service.go index bb43cdeafe..e0dc0c8d01 100644 --- a/services/sharedchannel/service.go +++ b/services/sharedchannel/service.go @@ -211,8 +211,8 @@ func (scs *Service) pause() { // Makes the remote channel to be read-only(announcement mode, only admins can create posts and reactions). func (scs *Service) makeChannelReadOnly(channel *model.Channel) *model.AppError { - createPostPermission := model.ChannelModeratedPermissionsMap[model.PERMISSION_CREATE_POST.Id] - createReactionPermission := model.ChannelModeratedPermissionsMap[model.PERMISSION_ADD_REACTION.Id] + createPostPermission := model.ChannelModeratedPermissionsMap[model.PermissionCreatePost.Id] + createReactionPermission := model.ChannelModeratedPermissionsMap[model.PermissionAddReaction.Id] updateMap := model.ChannelModeratedRolesPatch{ Guests: model.NewBool(false), Members: model.NewBool(false), diff --git a/services/sharedchannel/sync_recv.go b/services/sharedchannel/sync_recv.go index a4bf301e7b..990b34a06d 100644 --- a/services/sharedchannel/sync_recv.go +++ b/services/sharedchannel/sync_recv.go @@ -99,7 +99,7 @@ func (scs *Service) processSyncMessage(syncMsg *syncMsg, rc *model.RemoteCluster continue } - if channel.Type != model.CHANNEL_DIRECT && team == nil { + if channel.Type != model.ChannelTypeDirect && team == nil { var err2 error team, err2 = scs.server.GetStore().Channel().GetTeamForChannel(syncMsg.ChannelId) if err2 != nil { @@ -244,8 +244,8 @@ func (scs *Service) insertSyncUser(user *model.User, channel *model.Channel, rc suffix = strconv.FormatInt(int64(i), 10) } - user.Username = mungUsername(user.Username, rc.Name, suffix, model.USER_NAME_MAX_LENGTH) - user.Email = mungEmail(rc.Name, model.USER_EMAIL_MAX_LENGTH) + user.Username = mungUsername(user.Username, rc.Name, suffix, model.UserNameMaxLength) + user.Email = mungEmail(rc.Name, model.UserEmailMaxLength) if userSaved, err = scs.server.GetStore().User().Save(user); err != nil { e, ok := err.(errInvalidInput) @@ -298,8 +298,8 @@ func (scs *Service) updateSyncUser(patch *model.UserPatch, user *model.User, cha if i > 1 { suffix = strconv.FormatInt(int64(i), 10) } - user.Username = mungUsername(user.Username, rc.Name, suffix, model.USER_NAME_MAX_LENGTH) - user.Email = mungEmail(rc.Name, model.USER_EMAIL_MAX_LENGTH) + user.Username = mungUsername(user.Username, rc.Name, suffix, model.UserNameMaxLength) + user.Email = mungEmail(rc.Name, model.UserEmailMaxLength) if update, err = scs.server.GetStore().User().Update(user, false); err != nil { e, ok := err.(errInvalidInput) diff --git a/services/sharedchannel/sync_send.go b/services/sharedchannel/sync_send.go index fdcc4bf8b3..470cbd056c 100644 --- a/services/sharedchannel/sync_send.go +++ b/services/sharedchannel/sync_send.go @@ -361,7 +361,7 @@ func (scs *Service) getUserTranslations(userId string) i18n.TranslateFunc { } if locale == "" { - locale = model.DEFAULT_LOCALE + locale = model.DefaultLocale } return i18n.GetUserTranslations(locale) } diff --git a/services/slackimport/slackimport.go b/services/slackimport/slackimport.go index 34c9695d22..cbafc89e85 100644 --- a/services/slackimport/slackimport.go +++ b/services/slackimport/slackimport.go @@ -143,16 +143,16 @@ func (si *SlackImporter) SlackImport(fileData multipart.File, fileSize int64, te return model.NewAppError("SlackImport", "api.slackimport.slack_import.open.app_error", map[string]interface{}{"Filename": file.Name}, err.Error(), http.StatusInternalServerError), log } if file.Name == "channels.json" { - publicChannels, _ = slackParseChannels(reader, model.CHANNEL_OPEN) + publicChannels, _ = slackParseChannels(reader, model.ChannelTypeOpen) channels = append(channels, publicChannels...) } else if file.Name == "dms.json" { - directChannels, _ = slackParseChannels(reader, model.CHANNEL_DIRECT) + directChannels, _ = slackParseChannels(reader, model.ChannelTypeDirect) channels = append(channels, directChannels...) } else if file.Name == "groups.json" { - privateChannels, _ = slackParseChannels(reader, model.CHANNEL_PRIVATE) + privateChannels, _ = slackParseChannels(reader, model.ChannelTypePrivate) channels = append(channels, privateChannels...) } else if file.Name == "mpims.json" { - groupChannels, _ = slackParseChannels(reader, model.CHANNEL_GROUP) + groupChannels, _ = slackParseChannels(reader, model.ChannelTypeGroup) channels = append(channels, groupChannels...) } else if file.Name == "users.json" { users, _ = slackParseUsers(reader) @@ -378,7 +378,7 @@ func (si *SlackImporter) slackAddPosts(teamId string, channel *model.Channel, po ChannelId: channel.Id, CreateAt: slackConvertTimeStamp(sPost.TimeStamp), Message: sPost.Text, - Type: model.POST_SLACK_ATTACHMENT, + Type: model.PostTypeSlackAttachment, } postId := si.oldImportIncomingWebhookPost(post, props) @@ -398,9 +398,9 @@ func (si *SlackImporter) slackAddPosts(teamId string, channel *model.Channel, po var postType string if sPost.SubType == "channel_join" { - postType = model.POST_JOIN_CHANNEL + postType = model.PostTypeJoinChannel } else { - postType = model.POST_LEAVE_CHANNEL + postType = model.PostTypeLeaveChannel } newPost := model.Post{ @@ -448,7 +448,7 @@ func (si *SlackImporter) slackAddPosts(teamId string, channel *model.Channel, po ChannelId: channel.Id, Message: sPost.Text, CreateAt: slackConvertTimeStamp(sPost.TimeStamp), - Type: model.POST_HEADER_CHANGE, + Type: model.PostTypeHeaderChange, } si.oldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "channel_purpose": @@ -465,7 +465,7 @@ func (si *SlackImporter) slackAddPosts(teamId string, channel *model.Channel, po ChannelId: channel.Id, Message: sPost.Text, CreateAt: slackConvertTimeStamp(sPost.TimeStamp), - Type: model.POST_PURPOSE_CHANGE, + Type: model.PostTypePurposeChange, } si.oldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "channel_name": @@ -482,7 +482,7 @@ func (si *SlackImporter) slackAddPosts(teamId string, channel *model.Channel, po ChannelId: channel.Id, Message: sPost.Text, CreateAt: slackConvertTimeStamp(sPost.TimeStamp), - Type: model.POST_DISPLAYNAME_CHANGE, + Type: model.PostTypeDisplaynameChange, } si.oldImportPost(&newPost) default: @@ -542,24 +542,24 @@ func (si *SlackImporter) addSlackUsersToChannel(members []string, users map[stri } func slackSanitiseChannelProperties(channel model.Channel) model.Channel { - if utf8.RuneCountInString(channel.DisplayName) > model.CHANNEL_DISPLAY_NAME_MAX_RUNES { + if utf8.RuneCountInString(channel.DisplayName) > model.ChannelDisplayNameMaxRunes { mlog.Warn("Slack Import: Channel display name exceeds the maximum length. It will be truncated when imported.", mlog.String("channel_display_name", channel.DisplayName)) - channel.DisplayName = truncateRunes(channel.DisplayName, model.CHANNEL_DISPLAY_NAME_MAX_RUNES) + channel.DisplayName = truncateRunes(channel.DisplayName, model.ChannelDisplayNameMaxRunes) } - if len(channel.Name) > model.CHANNEL_NAME_MAX_LENGTH { + if len(channel.Name) > model.ChannelNameMaxLength { mlog.Warn("Slack Import: Channel handle exceeds the maximum length. It will be truncated when imported.", mlog.String("channel_display_name", channel.DisplayName)) - channel.Name = channel.Name[0:model.CHANNEL_NAME_MAX_LENGTH] + channel.Name = channel.Name[0:model.ChannelNameMaxLength] } - if utf8.RuneCountInString(channel.Purpose) > model.CHANNEL_PURPOSE_MAX_RUNES { + if utf8.RuneCountInString(channel.Purpose) > model.ChannelPurposeMaxRunes { mlog.Warn("Slack Import: Channel purpose exceeds the maximum length. It will be truncated when imported.", mlog.String("channel_display_name", channel.DisplayName)) - channel.Purpose = truncateRunes(channel.Purpose, model.CHANNEL_PURPOSE_MAX_RUNES) + channel.Purpose = truncateRunes(channel.Purpose, model.ChannelPurposeMaxRunes) } - if utf8.RuneCountInString(channel.Header) > model.CHANNEL_HEADER_MAX_RUNES { + if utf8.RuneCountInString(channel.Header) > model.ChannelHeaderMaxRunes { mlog.Warn("Slack Import: Channel header exceeds the maximum length. It will be truncated when imported.", mlog.String("channel_display_name", channel.DisplayName)) - channel.Header = truncateRunes(channel.Header, model.CHANNEL_HEADER_MAX_RUNES) + channel.Header = truncateRunes(channel.Header, model.ChannelHeaderMaxRunes) } return channel @@ -582,7 +582,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh } // Direct message channels in Slack don't have a name so we set the id as name or else the messages won't get imported. - if newChannel.Type == model.CHANNEL_DIRECT { + if newChannel.Type == model.ChannelTypeDirect { sChannel.Name = sChannel.Id } @@ -610,7 +610,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh } // Members for direct and group channels are added during the creation of the channel in the oldImportChannel function - if sChannel.Type == model.CHANNEL_OPEN || sChannel.Type == model.CHANNEL_PRIVATE { + if sChannel.Type == model.ChannelTypeOpen || sChannel.Type == model.ChannelTypePrivate { si.addSlackUsersToChannel(sChannel.Members, users, mChannel, importerLog) } importerLog.WriteString(newChannel.DisplayName + "\r\n") @@ -683,7 +683,7 @@ func (si *SlackImporter) oldImportPost(post *model.Post) string { func (si *SlackImporter) oldImportUser(team *model.Team, user *model.User) *model.User { user.MakeNonNil() - user.Roles = model.SYSTEM_USER_ROLE_ID + user.Roles = model.SystemUserRoleId ruser, nErr := si.store.User().Save(user) if nErr != nil { @@ -704,7 +704,7 @@ func (si *SlackImporter) oldImportUser(team *model.Team, user *model.User) *mode func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slackChannel, users map[string]*model.User) *model.Channel { switch { - case channel.Type == model.CHANNEL_DIRECT: + case channel.Type == model.ChannelTypeDirect: if len(sChannel.Members) < 2 { return nil } @@ -721,7 +721,7 @@ func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slack return sc // check if direct channel has less than 8 members and if not import as private channel instead - case channel.Type == model.CHANNEL_GROUP && len(sChannel.Members) < 8: + case channel.Type == model.ChannelTypeGroup && len(sChannel.Members) < 8: members := make([]string, len(sChannel.Members)) for i := range sChannel.Members { @@ -743,8 +743,8 @@ func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slack } return sc - case channel.Type == model.CHANNEL_GROUP: - channel.Type = model.CHANNEL_PRIVATE + case channel.Type == model.ChannelTypeGroup: + channel.Type = model.ChannelTypePrivate sc, err := si.actions.CreateChannel(channel, false) if err != nil { return nil @@ -791,7 +791,7 @@ func (si *SlackImporter) oldImportIncomingWebhookPost(post *model.Post, props mo post.AddProp("from_webhook", "true") if _, ok := props["override_username"]; !ok { - post.AddProp("override_username", model.DEFAULT_WEBHOOK_USERNAME) + post.AddProp("override_username", model.DefaultWebhookUsername) } if len(props) > 0 { diff --git a/services/slackimport/slackimport_test.go b/services/slackimport/slackimport_test.go index 9eac1fb3d0..b1d56a54be 100644 --- a/services/slackimport/slackimport_test.go +++ b/services/slackimport/slackimport_test.go @@ -329,7 +329,7 @@ func TestOldImportChannel(t *testing.T) { t.Run("No panic on direct channel", func(t *testing.T) { //ch := th.CreateDmChannel(u1) ch := &model.Channel{ - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, Name: "test-channel", } users := map[string]*model.User{ @@ -349,7 +349,7 @@ func TestOldImportChannel(t *testing.T) { t.Run("No panic on direct channel with 1 member", func(t *testing.T) { ch := &model.Channel{ - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, Name: "test-channel", } users := map[string]*model.User{ @@ -369,7 +369,7 @@ func TestOldImportChannel(t *testing.T) { t.Run("No panic on group channel", func(t *testing.T) { ch := &model.Channel{ - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, Name: "test-channel", } users := map[string]*model.User{ diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index 485191da25..92ee5d8465 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -44,7 +44,7 @@ const ( TrackConfigEmail = "config_email" TrackConfigPrivacy = "config_privacy" TrackConfigTheme = "config_theme" - TrackConfigOauth = "config_oauth" + TrackConfigOAuth = "config_oauth" TrackConfigLDAP = "config_ldap" TrackConfigCompliance = "config_compliance" TrackConfigLocalization = "config_localization" @@ -128,10 +128,10 @@ func (ts *TelemetryService) ensureTelemetryID() { return } - id := props[model.SYSTEM_TELEMETRY_ID] + id := props[model.SystemTelemetryId] if id == "" { id = model.NewId() - systemID := &model.System{Name: model.SYSTEM_TELEMETRY_ID, Value: id} + systemID := &model.System{Name: model.SystemTelemetryId, Value: id} ts.dbStore.System().Save(systemID) } @@ -373,8 +373,8 @@ func (ts *TelemetryService) trackConfig() { "enable_custom_emoji": *cfg.ServiceSettings.EnableCustomEmoji, "enable_emoji_picker": *cfg.ServiceSettings.EnableEmojiPicker, "enable_gif_picker": *cfg.ServiceSettings.EnableGifPicker, - "gfycat_api_key": isDefault(*cfg.ServiceSettings.GfycatApiKey, model.SERVICE_SETTINGS_DEFAULT_GFYCAT_API_KEY), - "gfycat_api_secret": isDefault(*cfg.ServiceSettings.GfycatApiSecret, model.SERVICE_SETTINGS_DEFAULT_GFYCAT_API_SECRET), + "gfycat_api_key": isDefault(*cfg.ServiceSettings.GfycatApiKey, model.ServiceSettingsDefaultGfycatApiKey), + "gfycat_api_secret": isDefault(*cfg.ServiceSettings.GfycatApiSecret, model.ServiceSettingsDefaultGfycatApiSecret), "experimental_enable_authentication_transfer": *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer, "restrict_custom_emoji_creation": *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation, "enable_testing": cfg.ServiceSettings.EnableTesting, @@ -393,14 +393,14 @@ func (ts *TelemetryService) trackConfig() { "session_length_sso_in_days": *cfg.ServiceSettings.SessionLengthSSOInDays, "session_cache_in_minutes": *cfg.ServiceSettings.SessionCacheInMinutes, "session_idle_timeout_in_minutes": *cfg.ServiceSettings.SessionIdleTimeoutInMinutes, - "isdefault_site_url": isDefault(*cfg.ServiceSettings.SiteURL, model.SERVICE_SETTINGS_DEFAULT_SITE_URL), - "isdefault_tls_cert_file": isDefault(*cfg.ServiceSettings.TLSCertFile, model.SERVICE_SETTINGS_DEFAULT_TLS_CERT_FILE), - "isdefault_tls_key_file": isDefault(*cfg.ServiceSettings.TLSKeyFile, model.SERVICE_SETTINGS_DEFAULT_TLS_KEY_FILE), - "isdefault_read_timeout": isDefault(*cfg.ServiceSettings.ReadTimeout, model.SERVICE_SETTINGS_DEFAULT_READ_TIMEOUT), - "isdefault_write_timeout": isDefault(*cfg.ServiceSettings.WriteTimeout, model.SERVICE_SETTINGS_DEFAULT_WRITE_TIMEOUT), - "isdefault_idle_timeout": isDefault(*cfg.ServiceSettings.IdleTimeout, model.SERVICE_SETTINGS_DEFAULT_IDLE_TIMEOUT), + "isdefault_site_url": isDefault(*cfg.ServiceSettings.SiteURL, model.ServiceSettingsDefaultSiteUrl), + "isdefault_tls_cert_file": isDefault(*cfg.ServiceSettings.TLSCertFile, model.ServiceSettingsDefaultTlsCertFile), + "isdefault_tls_key_file": isDefault(*cfg.ServiceSettings.TLSKeyFile, model.ServiceSettingsDefaultTlsKeyFile), + "isdefault_read_timeout": isDefault(*cfg.ServiceSettings.ReadTimeout, model.ServiceSettingsDefaultReadTimeout), + "isdefault_write_timeout": isDefault(*cfg.ServiceSettings.WriteTimeout, model.ServiceSettingsDefaultWriteTimeout), + "isdefault_idle_timeout": isDefault(*cfg.ServiceSettings.IdleTimeout, model.ServiceSettingsDefaultIdleTimeout), "isdefault_google_developer_key": isDefault(cfg.ServiceSettings.GoogleDeveloperKey, ""), - "isdefault_allow_cors_from": isDefault(*cfg.ServiceSettings.AllowCorsFrom, model.SERVICE_SETTINGS_DEFAULT_ALLOW_CORS_FROM), + "isdefault_allow_cors_from": isDefault(*cfg.ServiceSettings.AllowCorsFrom, model.ServiceSettingsDefaultAllowCorsFrom), "isdefault_cors_exposed_headers": isDefault(cfg.ServiceSettings.CorsExposedHeaders, ""), "cors_allow_credentials": *cfg.ServiceSettings.CorsAllowCredentials, "cors_debug": *cfg.ServiceSettings.CorsDebug, @@ -468,9 +468,9 @@ func (ts *TelemetryService) trackConfig() { "experimental_view_archived_channels": *cfg.TeamSettings.ExperimentalViewArchivedChannels, "lock_teammate_name_display": *cfg.TeamSettings.LockTeammateNameDisplay, "isdefault_site_name": isDefault(cfg.TeamSettings.SiteName, "Mattermost"), - "isdefault_custom_brand_text": isDefault(*cfg.TeamSettings.CustomBrandText, model.TEAM_SETTINGS_DEFAULT_CUSTOM_BRAND_TEXT), - "isdefault_custom_description_text": isDefault(*cfg.TeamSettings.CustomDescriptionText, model.TEAM_SETTINGS_DEFAULT_CUSTOM_DESCRIPTION_TEXT), - "isdefault_user_status_away_timeout": isDefault(*cfg.TeamSettings.UserStatusAwayTimeout, model.TEAM_SETTINGS_DEFAULT_USER_STATUS_AWAY_TIMEOUT), + "isdefault_custom_brand_text": isDefault(*cfg.TeamSettings.CustomBrandText, model.TeamSettingsDefaultCustomBrandText), + "isdefault_custom_description_text": isDefault(*cfg.TeamSettings.CustomDescriptionText, model.TeamSettingsDefaultCustomDescriptionText), + "isdefault_user_status_away_timeout": isDefault(*cfg.TeamSettings.UserStatusAwayTimeout, model.TeamSettingsDefaultUserStatusAwayTimeout), "restrict_private_channel_manage_members": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManageMembers, "enable_X_to_leave_channels_from_LHS": *cfg.TeamSettings.EnableXToLeaveChannelsFromLHS, "experimental_enable_automatic_replies": *cfg.TeamSettings.ExperimentalEnableAutomaticReplies, @@ -546,7 +546,7 @@ func (ts *TelemetryService) trackConfig() { ts.sendTelemetry(TrackConfigFile, map[string]interface{}{ "enable_public_links": cfg.FileSettings.EnablePublicLink, "driver_name": *cfg.FileSettings.DriverName, - "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FILE_SETTINGS_DEFAULT_DIRECTORY), + "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FileSettingsDefaultDirectory), "isabsolute_directory": filepath.IsAbs(*cfg.FileSettings.Directory), "extract_content": *cfg.FileSettings.ExtractContent, "archive_recursion": *cfg.FileSettings.ArchiveRecursion, @@ -579,7 +579,7 @@ func (ts *TelemetryService) trackConfig() { "isdefault_feedback_name": isDefault(cfg.EmailSettings.FeedbackName, ""), "isdefault_feedback_email": isDefault(cfg.EmailSettings.FeedbackEmail, ""), "isdefault_reply_to_address": isDefault(cfg.EmailSettings.ReplyToAddress, ""), - "isdefault_feedback_organization": isDefault(*cfg.EmailSettings.FeedbackOrganization, model.EMAIL_SETTINGS_DEFAULT_FEEDBACK_ORGANIZATION), + "isdefault_feedback_organization": isDefault(*cfg.EmailSettings.FeedbackOrganization, model.EmailSettingsDefaultFeedbackOrganization), "skip_server_certificate_verification": *cfg.EmailSettings.SkipServerCertificateVerification, "isdefault_login_button_color": isDefault(*cfg.EmailSettings.LoginButtonColor, ""), "isdefault_login_button_border_color": isDefault(*cfg.EmailSettings.LoginButtonBorderColor, ""), @@ -604,28 +604,28 @@ func (ts *TelemetryService) trackConfig() { ts.sendTelemetry(TrackConfigTheme, map[string]interface{}{ "enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection, - "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TEAM_SETTINGS_DEFAULT_TEAM_TEXT), + "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TeamSettingsDefaultTeamText), "allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes, "allowed_themes": len(cfg.ThemeSettings.AllowedThemes), }) - ts.sendTelemetry(TrackConfigOauth, map[string]interface{}{ + ts.sendTelemetry(TrackConfigOAuth, map[string]interface{}{ "enable_gitlab": cfg.GitLabSettings.Enable, - "openid_gitlab": *cfg.GitLabSettings.Enable && strings.Contains(*cfg.GitLabSettings.Scope, model.SERVICE_OPENID), + "openid_gitlab": *cfg.GitLabSettings.Enable && strings.Contains(*cfg.GitLabSettings.Scope, model.ServiceOpenid), "enable_google": cfg.GoogleSettings.Enable, - "openid_google": *cfg.GoogleSettings.Enable && strings.Contains(*cfg.GoogleSettings.Scope, model.SERVICE_OPENID), + "openid_google": *cfg.GoogleSettings.Enable && strings.Contains(*cfg.GoogleSettings.Scope, model.ServiceOpenid), "enable_office365": cfg.Office365Settings.Enable, - "openid_office365": *cfg.Office365Settings.Enable && strings.Contains(*cfg.Office365Settings.Scope, model.SERVICE_OPENID), + "openid_office365": *cfg.Office365Settings.Enable && strings.Contains(*cfg.Office365Settings.Scope, model.ServiceOpenid), "enable_openid": cfg.OpenIdSettings.Enable, }) ts.sendTelemetry(TrackConfigSupport, map[string]interface{}{ - "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK), - "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK), - "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK), - "isdefault_help_link": isDefault(*cfg.SupportSettings.HelpLink, model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK), - "isdefault_report_a_problem_link": isDefault(*cfg.SupportSettings.ReportAProblemLink, model.SUPPORT_SETTINGS_DEFAULT_REPORT_A_PROBLEM_LINK), - "isdefault_support_email": isDefault(*cfg.SupportSettings.SupportEmail, model.SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL), + "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SupportSettingsDefaultTermsOfServiceLink), + "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SupportSettingsDefaultPrivacyPolicyLink), + "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SupportSettingsDefaultAboutLink), + "isdefault_help_link": isDefault(*cfg.SupportSettings.HelpLink, model.SupportSettingsDefaultHelpLink), + "isdefault_report_a_problem_link": isDefault(*cfg.SupportSettings.ReportAProblemLink, model.SupportSettingsDefaultReportAProblemLink), + "isdefault_support_email": isDefault(*cfg.SupportSettings.SupportEmail, model.SupportSettingsDefaultSupportEmail), "custom_terms_of_service_enabled": *cfg.SupportSettings.CustomTermsOfServiceEnabled, "custom_terms_of_service_re_acceptance_period": *cfg.SupportSettings.CustomTermsOfServiceReAcceptancePeriod, "enable_ask_community_link": *cfg.SupportSettings.EnableAskCommunityLink, @@ -640,21 +640,21 @@ func (ts *TelemetryService) trackConfig() { "sync_interval_minutes": *cfg.LdapSettings.SyncIntervalMinutes, "query_timeout": *cfg.LdapSettings.QueryTimeout, "max_page_size": *cfg.LdapSettings.MaxPageSize, - "isdefault_first_name_attribute": isDefault(*cfg.LdapSettings.FirstNameAttribute, model.LDAP_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE), - "isdefault_last_name_attribute": isDefault(*cfg.LdapSettings.LastNameAttribute, model.LDAP_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE), - "isdefault_email_attribute": isDefault(*cfg.LdapSettings.EmailAttribute, model.LDAP_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE), - "isdefault_username_attribute": isDefault(*cfg.LdapSettings.UsernameAttribute, model.LDAP_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE), - "isdefault_nickname_attribute": isDefault(*cfg.LdapSettings.NicknameAttribute, model.LDAP_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE), - "isdefault_id_attribute": isDefault(*cfg.LdapSettings.IdAttribute, model.LDAP_SETTINGS_DEFAULT_ID_ATTRIBUTE), - "isdefault_position_attribute": isDefault(*cfg.LdapSettings.PositionAttribute, model.LDAP_SETTINGS_DEFAULT_POSITION_ATTRIBUTE), + "isdefault_first_name_attribute": isDefault(*cfg.LdapSettings.FirstNameAttribute, model.LdapSettingsDefaultFirstNameAttribute), + "isdefault_last_name_attribute": isDefault(*cfg.LdapSettings.LastNameAttribute, model.LdapSettingsDefaultLastNameAttribute), + "isdefault_email_attribute": isDefault(*cfg.LdapSettings.EmailAttribute, model.LdapSettingsDefaultEmailAttribute), + "isdefault_username_attribute": isDefault(*cfg.LdapSettings.UsernameAttribute, model.LdapSettingsDefaultUsernameAttribute), + "isdefault_nickname_attribute": isDefault(*cfg.LdapSettings.NicknameAttribute, model.LdapSettingsDefaultNicknameAttribute), + "isdefault_id_attribute": isDefault(*cfg.LdapSettings.IdAttribute, model.LdapSettingsDefaultIdAttribute), + "isdefault_position_attribute": isDefault(*cfg.LdapSettings.PositionAttribute, model.LdapSettingsDefaultPositionAttribute), "isdefault_login_id_attribute": isDefault(*cfg.LdapSettings.LoginIdAttribute, ""), - "isdefault_login_field_name": isDefault(*cfg.LdapSettings.LoginFieldName, model.LDAP_SETTINGS_DEFAULT_LOGIN_FIELD_NAME), + "isdefault_login_field_name": isDefault(*cfg.LdapSettings.LoginFieldName, model.LdapSettingsDefaultLoginFieldName), "isdefault_login_button_color": isDefault(*cfg.LdapSettings.LoginButtonColor, ""), "isdefault_login_button_border_color": isDefault(*cfg.LdapSettings.LoginButtonBorderColor, ""), "isdefault_login_button_text_color": isDefault(*cfg.LdapSettings.LoginButtonTextColor, ""), "isempty_group_filter": isDefault(*cfg.LdapSettings.GroupFilter, ""), - "isdefault_group_display_name_attribute": isDefault(*cfg.LdapSettings.GroupDisplayNameAttribute, model.LDAP_SETTINGS_DEFAULT_GROUP_DISPLAY_NAME_ATTRIBUTE), - "isdefault_group_id_attribute": isDefault(*cfg.LdapSettings.GroupIdAttribute, model.LDAP_SETTINGS_DEFAULT_GROUP_ID_ATTRIBUTE), + "isdefault_group_display_name_attribute": isDefault(*cfg.LdapSettings.GroupDisplayNameAttribute, model.LdapSettingsDefaultGroupDisplayNameAttribute), + "isdefault_group_id_attribute": isDefault(*cfg.LdapSettings.GroupIdAttribute, model.LdapSettingsDefaultGroupIdAttribute), "isempty_guest_filter": isDefault(*cfg.LdapSettings.GuestFilter, ""), "isempty_admin_filter": isDefault(*cfg.LdapSettings.AdminFilter, ""), "isnotempty_picture_attribute": !isDefault(*cfg.LdapSettings.PictureAttribute, ""), @@ -686,17 +686,17 @@ func (ts *TelemetryService) trackConfig() { "isdefault_canonical_algorithm": isDefault(*cfg.SamlSettings.CanonicalAlgorithm, ""), "isdefault_scoping_idp_provider_id": isDefault(*cfg.SamlSettings.ScopingIDPProviderId, ""), "isdefault_scoping_idp_name": isDefault(*cfg.SamlSettings.ScopingIDPName, ""), - "isdefault_id_attribute": isDefault(*cfg.SamlSettings.IdAttribute, model.SAML_SETTINGS_DEFAULT_ID_ATTRIBUTE), - "isdefault_guest_attribute": isDefault(*cfg.SamlSettings.GuestAttribute, model.SAML_SETTINGS_DEFAULT_GUEST_ATTRIBUTE), - "isdefault_admin_attribute": isDefault(*cfg.SamlSettings.AdminAttribute, model.SAML_SETTINGS_DEFAULT_ADMIN_ATTRIBUTE), - "isdefault_first_name_attribute": isDefault(*cfg.SamlSettings.FirstNameAttribute, model.SAML_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE), - "isdefault_last_name_attribute": isDefault(*cfg.SamlSettings.LastNameAttribute, model.SAML_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE), - "isdefault_email_attribute": isDefault(*cfg.SamlSettings.EmailAttribute, model.SAML_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE), - "isdefault_username_attribute": isDefault(*cfg.SamlSettings.UsernameAttribute, model.SAML_SETTINGS_DEFAULT_USERNAME_ATTRIBUTE), - "isdefault_nickname_attribute": isDefault(*cfg.SamlSettings.NicknameAttribute, model.SAML_SETTINGS_DEFAULT_NICKNAME_ATTRIBUTE), - "isdefault_locale_attribute": isDefault(*cfg.SamlSettings.LocaleAttribute, model.SAML_SETTINGS_DEFAULT_LOCALE_ATTRIBUTE), - "isdefault_position_attribute": isDefault(*cfg.SamlSettings.PositionAttribute, model.SAML_SETTINGS_DEFAULT_POSITION_ATTRIBUTE), - "isdefault_login_button_text": isDefault(*cfg.SamlSettings.LoginButtonText, model.USER_AUTH_SERVICE_SAML_TEXT), + "isdefault_id_attribute": isDefault(*cfg.SamlSettings.IdAttribute, model.SamlSettingsDefaultIdAttribute), + "isdefault_guest_attribute": isDefault(*cfg.SamlSettings.GuestAttribute, model.SamlSettingsDefaultGuestAttribute), + "isdefault_admin_attribute": isDefault(*cfg.SamlSettings.AdminAttribute, model.SamlSettingsDefaultAdminAttribute), + "isdefault_first_name_attribute": isDefault(*cfg.SamlSettings.FirstNameAttribute, model.SamlSettingsDefaultFirstNameAttribute), + "isdefault_last_name_attribute": isDefault(*cfg.SamlSettings.LastNameAttribute, model.SamlSettingsDefaultLastNameAttribute), + "isdefault_email_attribute": isDefault(*cfg.SamlSettings.EmailAttribute, model.SamlSettingsDefaultEmailAttribute), + "isdefault_username_attribute": isDefault(*cfg.SamlSettings.UsernameAttribute, model.SamlSettingsDefaultUsernameAttribute), + "isdefault_nickname_attribute": isDefault(*cfg.SamlSettings.NicknameAttribute, model.SamlSettingsDefaultNicknameAttribute), + "isdefault_locale_attribute": isDefault(*cfg.SamlSettings.LocaleAttribute, model.SamlSettingsDefaultLocaleAttribute), + "isdefault_position_attribute": isDefault(*cfg.SamlSettings.PositionAttribute, model.SamlSettingsDefaultPositionAttribute), + "isdefault_login_button_text": isDefault(*cfg.SamlSettings.LoginButtonText, model.UserAuthServiceSamlText), "isdefault_login_button_color": isDefault(*cfg.SamlSettings.LoginButtonColor, ""), "isdefault_login_button_border_color": isDefault(*cfg.SamlSettings.LoginButtonBorderColor, ""), "isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""), @@ -720,14 +720,14 @@ func (ts *TelemetryService) trackConfig() { ts.sendTelemetry(TrackConfigNativeApp, map[string]interface{}{ "isdefault_app_custom_url_schemes": isDefaultArray(cfg.NativeAppSettings.AppCustomURLSchemes, model.GetDefaultAppCustomURLSchemes()), - "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK), - "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK), - "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK), + "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NativeappSettingsDefaultAppDownloadLink), + "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NativeappSettingsDefaultAndroidAppDownloadLink), + "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NativeappSettingsDefaultIosAppDownloadLink), }) ts.sendTelemetry(TrackConfigExperimental, map[string]interface{}{ "client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable, - "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH), + "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.ClientSideCertCheckPrimaryAuth), "link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds, "enable_click_to_reply": *cfg.ExperimentalSettings.EnableClickToReply, "restrict_system_admin": *cfg.ExperimentalSettings.RestrictSystemAdmin, @@ -739,22 +739,22 @@ func (ts *TelemetryService) trackConfig() { }) ts.sendTelemetry(TrackConfigAnalytics, map[string]interface{}{ - "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS), + "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.AnalyticsSettingsDefaultMaxUsersForStatistics), }) ts.sendTelemetry(TrackConfigAnnouncement, map[string]interface{}{ "enable_banner": *cfg.AnnouncementSettings.EnableBanner, - "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR), - "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR), + "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.AnnouncementSettingsDefaultBannerColor), + "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.AnnouncementSettingsDefaultBannerTextColor), "allow_banner_dismissal": *cfg.AnnouncementSettings.AllowBannerDismissal, "admin_notices_enabled": *cfg.AnnouncementSettings.AdminNoticesEnabled, "user_notices_enabled": *cfg.AnnouncementSettings.UserNoticesEnabled, }) ts.sendTelemetry(TrackConfigElasticsearch, map[string]interface{}{ - "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL), - "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME), - "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD), + "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ElasticsearchSettingsDefaultConnectionUrl), + "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ElasticsearchSettingsDefaultUsername), + "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ElasticsearchSettingsDefaultPassword), "enable_indexing": *cfg.ElasticsearchSettings.EnableIndexing, "enable_searching": *cfg.ElasticsearchSettings.EnableSearching, "enable_autocomplete": *cfg.ElasticsearchSettings.EnableAutocomplete, @@ -765,7 +765,7 @@ func (ts *TelemetryService) trackConfig() { "channel_index_shards": *cfg.ElasticsearchSettings.ChannelIndexShards, "user_index_replicas": *cfg.ElasticsearchSettings.UserIndexReplicas, "user_index_shards": *cfg.ElasticsearchSettings.UserIndexShards, - "isdefault_index_prefix": isDefault(*cfg.ElasticsearchSettings.IndexPrefix, model.ELASTICSEARCH_SETTINGS_DEFAULT_INDEX_PREFIX), + "isdefault_index_prefix": isDefault(*cfg.ElasticsearchSettings.IndexPrefix, model.ElasticsearchSettingsDefaultIndexPrefix), "live_indexing_batch_size": *cfg.ElasticsearchSettings.LiveIndexingBatchSize, "bulk_indexing_time_window_seconds": *cfg.ElasticsearchSettings.BulkIndexingTimeWindowSeconds, "request_timeout_seconds": *cfg.ElasticsearchSettings.RequestTimeoutSeconds, @@ -773,7 +773,7 @@ func (ts *TelemetryService) trackConfig() { "trace": *cfg.ElasticsearchSettings.Trace, }) - ts.trackPluginConfig(cfg, model.PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL) + ts.trackPluginConfig(cfg, model.PluginSettingsDefaultMarketplaceUrl) ts.sendTelemetry(TrackConfigDataRetention, map[string]interface{}{ "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, @@ -943,12 +943,12 @@ func (ts *TelemetryService) trackServer() { func (ts *TelemetryService) trackPermissions() { phase1Complete := false - if _, err := ts.dbStore.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := ts.dbStore.System().GetByName(model.AdvancedPermissionsMigrationKey); err == nil { phase1Complete = true } phase2Complete := false - if _, err := ts.dbStore.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { + if _, err := ts.dbStore.System().GetByName(model.MigrationKeyAdvancedPermissionsPhase2); err == nil { phase2Complete = true } @@ -958,74 +958,74 @@ func (ts *TelemetryService) trackPermissions() { }) systemAdminPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.SystemAdminRoleId); err == nil { systemAdminPermissions = strings.Join(role.Permissions, " ") } systemUserPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.SystemUserRoleId); err == nil { systemUserPermissions = strings.Join(role.Permissions, " ") } teamAdminPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.TeamAdminRoleId); err == nil { teamAdminPermissions = strings.Join(role.Permissions, " ") } teamUserPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.TEAM_USER_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.TeamUserRoleId); err == nil { teamUserPermissions = strings.Join(role.Permissions, " ") } teamGuestPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.TeamGuestRoleId); err == nil { teamGuestPermissions = strings.Join(role.Permissions, " ") } channelAdminPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.CHANNEL_ADMIN_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.ChannelAdminRoleId); err == nil { channelAdminPermissions = strings.Join(role.Permissions, " ") } channelUserPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.CHANNEL_USER_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.ChannelUserRoleId); err == nil { channelUserPermissions = strings.Join(role.Permissions, " ") } channelGuestPermissions := "" - if role, err := ts.srv.GetRoleByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.ChannelGuestRoleId); err == nil { channelGuestPermissions = strings.Join(role.Permissions, " ") } systemManagerPermissions := "" systemManagerPermissionsModified := false - if role, err := ts.srv.GetRoleByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.SystemManagerRoleId); err == nil { systemManagerPermissionsModified = len(model.PermissionsChangedByPatch(role, &model.RolePatch{Permissions: &model.SystemManagerDefaultPermissions})) > 0 systemManagerPermissions = strings.Join(role.Permissions, " ") } - systemManagerCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SYSTEM_MANAGER_ROLE_ID}}) + systemManagerCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SystemManagerRoleId}}) if countErr != nil { systemManagerCount = 0 } systemUserManagerPermissions := "" systemUserManagerPermissionsModified := false - if role, err := ts.srv.GetRoleByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.SystemUserManagerRoleId); err == nil { systemUserManagerPermissionsModified = len(model.PermissionsChangedByPatch(role, &model.RolePatch{Permissions: &model.SystemUserManagerDefaultPermissions})) > 0 systemUserManagerPermissions = strings.Join(role.Permissions, " ") } - systemUserManagerCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SYSTEM_USER_MANAGER_ROLE_ID}}) + systemUserManagerCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SystemUserManagerRoleId}}) if countErr != nil { systemManagerCount = 0 } systemReadOnlyAdminPermissions := "" systemReadOnlyAdminPermissionsModified := false - if role, err := ts.srv.GetRoleByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err == nil { + if role, err := ts.srv.GetRoleByName(context.Background(), model.SystemReadOnlyAdminRoleId); err == nil { systemReadOnlyAdminPermissionsModified = len(model.PermissionsChangedByPatch(role, &model.RolePatch{Permissions: &model.SystemReadOnlyAdminDefaultPermissions})) > 0 systemReadOnlyAdminPermissions = strings.Join(role.Permissions, " ") } - systemReadOnlyAdminCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID}}) + systemReadOnlyAdminCount, countErr := ts.dbStore.User().Count(model.UserCountOptions{Roles: []string{model.SystemReadOnlyAdminRoleId}}) if countErr != nil { systemReadOnlyAdminCount = 0 } @@ -1050,7 +1050,7 @@ func (ts *TelemetryService) trackPermissions() { "system_read_only_admin_count": systemReadOnlyAdminCount, }) - if schemes, err := ts.srv.GetSchemes(model.SCHEME_SCOPE_TEAM, 0, 100); err == nil { + if schemes, err := ts.srv.GetSchemes(model.SchemeScopeTeam, 0, 100); err == nil { for _, scheme := range schemes { teamAdminPermissions := "" if role, err := ts.srv.GetRoleByName(context.Background(), scheme.DefaultTeamAdminRole); err == nil { @@ -1164,44 +1164,44 @@ func (ts *TelemetryService) trackGroups() { } func (ts *TelemetryService) trackChannelModeration() { - channelSchemeCount, err := ts.dbStore.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL) + channelSchemeCount, err := ts.dbStore.Scheme().CountByScope(model.SchemeScopeChannel) if err != nil { mlog.Debug("Could not get channel_scheme_count", mlog.Err(err)) } - createPostUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser) + createPostUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionCreatePost.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Debug("Could not get create_post_user_disabled_count", mlog.Err(err)) } - createPostGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest) + createPostGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionCreatePost.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Debug("Could not get create_post_guest_disabled_count", mlog.Err(err)) } // only need to track one of 'add_reaction' or 'remove_reaction` because they're both toggled together by the channel moderation feature - postReactionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser) + postReactionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionAddReaction.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Debug("Could not get post_reactions_user_disabled_count", mlog.Err(err)) } - postReactionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest) + postReactionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionAddReaction.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Debug("Could not get post_reactions_guest_disabled_count", mlog.Err(err)) } // only need to track one of 'manage_public_channel_members' or 'manage_private_channel_members` because they're both toggled together by the channel moderation feature - manageMembersUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser) + manageMembersUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionManagePublicChannelMembers.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Debug("Could not get manage_members_user_disabled_count", mlog.Err(err)) } - useChannelMentionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser) + useChannelMentionsUser, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionUseChannelMentions.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Debug("Could not get use_channel_mentions_user_disabled_count", mlog.Err(err)) } - useChannelMentionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest) + useChannelMentionsGuest, err := ts.dbStore.Scheme().CountWithoutPermission(model.SchemeScopeChannel, model.PermissionUseChannelMentions.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Debug("Could not get use_channel_mentions_guest_disabled_count", mlog.Err(err)) } @@ -1288,7 +1288,7 @@ func (ts *TelemetryService) trackWarnMetrics() { return } for key, value := range systemDataList { - if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) { + if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) { if _, ok := model.WarnMetricsTable[key]; ok { ts.sendTelemetry(TrackWarnMetrics, map[string]interface{}{ key: value != "false", @@ -1309,7 +1309,7 @@ func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL "require_pluginSignature": *cfg.PluginSettings.RequirePluginSignature, "enable_remote_marketplace": *cfg.PluginSettings.EnableRemoteMarketplace, "automatic_prepackaged_plugins": *cfg.PluginSettings.AutomaticPrepackagedPlugins, - "is_default_marketplace_url": isDefault(*cfg.PluginSettings.MarketplaceUrl, model.PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL), + "is_default_marketplace_url": isDefault(*cfg.PluginSettings.MarketplaceUrl, model.PluginSettingsDefaultMarketplaceUrl), "signature_public_key_files": len(cfg.PluginSettings.SignaturePublicKeyFiles), "chimera_oauth_proxy_url": *cfg.PluginSettings.ChimeraOAuthProxyUrl, } diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index 9a57ee8320..c6b237e126 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -80,17 +80,17 @@ func initializeMocks(cfg *model.Config) (*mocks.ServerIface, *storeMocks.Store, systemStore := storeMocks.SystemStore{} props := model.StringMap{} - props[model.SYSTEM_TELEMETRY_ID] = "test" + props[model.SystemTelemetryId] = "test" systemStore.On("Get").Return(props, nil) - systemStore.On("GetByName", model.ADVANCED_PERMISSIONS_MIGRATION_KEY).Return(nil, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2).Return(nil, nil) + systemStore.On("GetByName", model.AdvancedPermissionsMigrationKey).Return(nil, nil) + systemStore.On("GetByName", model.MigrationKeyAdvancedPermissionsPhase2).Return(nil, nil) userStore := storeMocks.UserStore{} userStore.On("Count", model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true, ExcludeRegularUsers: false, TeamId: "", ViewRestrictions: nil}).Return(int64(10), nil) userStore.On("Count", model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: false, ExcludeRegularUsers: true, TeamId: "", ViewRestrictions: nil}).Return(int64(100), nil) - userStore.On("Count", model.UserCountOptions{Roles: []string{model.SYSTEM_MANAGER_ROLE_ID}}).Return(int64(5), nil) - userStore.On("Count", model.UserCountOptions{Roles: []string{model.SYSTEM_USER_MANAGER_ROLE_ID}}).Return(int64(10), nil) - userStore.On("Count", model.UserCountOptions{Roles: []string{model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID}}).Return(int64(15), nil) + userStore.On("Count", model.UserCountOptions{Roles: []string{model.SystemManagerRoleId}}).Return(int64(5), nil) + userStore.On("Count", model.UserCountOptions{Roles: []string{model.SystemUserManagerRoleId}}).Return(int64(10), nil) + userStore.On("Count", model.UserCountOptions{Roles: []string{model.SystemReadOnlyAdminRoleId}}).Return(int64(15), nil) userStore.On("AnalyticsGetGuestCount").Return(int64(11), nil) userStore.On("AnalyticsActiveCount", mock.Anything, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false, ExcludeRegularUsers: false, TeamId: "", ViewRestrictions: nil}).Return(int64(5), nil) userStore.On("AnalyticsGetInactiveUsersCount").Return(int64(8), nil) @@ -361,7 +361,7 @@ func TestRudderTelemetry(t *testing.T) { TrackConfigRate, TrackConfigEmail, TrackConfigPrivacy, - TrackConfigOauth, + TrackConfigOAuth, TrackConfigLDAP, TrackConfigCompliance, TrackConfigLocalization, @@ -404,7 +404,7 @@ func TestRudderTelemetry(t *testing.T) { TrackConfigRate, TrackConfigEmail, TrackConfigPrivacy, - TrackConfigOauth, + TrackConfigOAuth, TrackConfigLDAP, TrackConfigCompliance, TrackConfigLocalization, diff --git a/services/users/helper_test.go b/services/users/helper_test.go index 46cdeccd7c..ce060cbcd6 100644 --- a/services/users/helper_test.go +++ b/services/users/helper_test.go @@ -76,7 +76,7 @@ func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *Test buffer := &bytes.Buffer{} provider := cache.NewProvider() cache, err := provider.NewCache(&cache.CacheOptions{ - Size: model.SESSION_CACHE_SIZE, + Size: model.SessionCacheSize, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }) diff --git a/services/users/password.go b/services/users/password.go index b0b3603e3d..5e698e93e0 100644 --- a/services/users/password.go +++ b/services/users/password.go @@ -52,12 +52,12 @@ func IsPasswordValidWithSettings(password string, settings *model.PasswordSettin id := "model.user.is_valid.pwd" isError := false - if len(password) < *settings.MinimumLength || len(password) > model.PASSWORD_MAXIMUM_LENGTH { + if len(password) < *settings.MinimumLength || len(password) > model.PasswordMaximumLength { isError = true } if *settings.Lowercase { - if !strings.ContainsAny(password, model.LOWERCASE_LETTERS) { + if !strings.ContainsAny(password, model.LowercaseLetters) { isError = true } @@ -65,7 +65,7 @@ func IsPasswordValidWithSettings(password string, settings *model.PasswordSettin } if *settings.Uppercase { - if !strings.ContainsAny(password, model.UPPERCASE_LETTERS) { + if !strings.ContainsAny(password, model.UppercaseLetters) { isError = true } diff --git a/services/users/password_test.go b/services/users/password_test.go index a5de5a8a5e..8ffc6491d2 100644 --- a/services/users/password_test.go +++ b/services/users/password_test.go @@ -37,7 +37,7 @@ func TestIsPasswordValidWithSettings(t *testing.T) { }, }, "Long": { - Password: strings.Repeat("x", model.PASSWORD_MAXIMUM_LENGTH), + Password: strings.Repeat("x", model.PasswordMaximumLength), Settings: &model.PasswordSettings{ Lowercase: model.NewBool(false), Uppercase: model.NewBool(false), @@ -57,7 +57,7 @@ func TestIsPasswordValidWithSettings(t *testing.T) { ExpectedError: "model.user.is_valid.pwd.app_error", }, "TooLong": { - Password: strings.Repeat("x", model.PASSWORD_MAXIMUM_LENGTH+1), + Password: strings.Repeat("x", model.PasswordMaximumLength+1), Settings: &model.PasswordSettings{ Lowercase: model.NewBool(false), Uppercase: model.NewBool(false), diff --git a/services/users/service.go b/services/users/service.go index b3dd2d419b..7c9b26662c 100644 --- a/services/users/service.go +++ b/services/users/service.go @@ -51,7 +51,7 @@ func New(c ServiceConfig) (*UserService, error) { } sessionCache, err := cacheProvider.NewCache(&cache.CacheOptions{ - Size: model.SESSION_CACHE_SIZE, + Size: model.SessionCacheSize, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }) diff --git a/services/users/session.go b/services/users/session.go index 14dc2805f8..0b63e4b2f5 100644 --- a/services/users/session.go +++ b/services/users/session.go @@ -97,8 +97,8 @@ func (us *UserService) ClearUserSessionCache(userID string) { if us.cluster != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventClearSessionCacheForUser, + SendType: model.ClusterSendReliable, Data: userID, } us.cluster.SendClusterMessage(msg) @@ -110,8 +110,8 @@ func (us *UserService) ClearAllUsersSessionCache() { if us.cluster != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, - SendType: model.CLUSTER_SEND_RELIABLE, + Event: model.ClusterEventClearSessionCacheForAllUsers, + SendType: model.ClusterSendReliable, } us.cluster.SendClusterMessage(msg) } @@ -217,7 +217,7 @@ func (us *UserService) UpdateSessionsIsGuest(userID string, isGuest bool) error } for _, session := range sessions { - session.AddProp(model.SESSION_PROP_IS_GUEST, fmt.Sprintf("%t", isGuest)) + session.AddProp(model.SessionPropIsGuest, fmt.Sprintf("%t", isGuest)) err := us.sessionStore.UpdateProps(session) if err != nil { mlog.Warn("Unable to update isGuest session", mlog.Err(err)) diff --git a/services/users/session_test.go b/services/users/session_test.go index 9ebd105d11..3b156ff21b 100644 --- a/services/users/session_test.go +++ b/services/users/session_test.go @@ -111,7 +111,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) { session.CreateAt = model.GetMillis() session.UserId = model.NewId() session.Token = model.NewId() - session.Roles = model.SYSTEM_USER_ROLE_ID + session.Roles = model.SystemUserRoleId th.service.SetSessionExpireInDays(session, 1) session, _ = th.service.CreateSession(session) diff --git a/services/users/users.go b/services/users/users.go index ee9cc19c7c..9d1f8c48d3 100644 --- a/services/users/users.go +++ b/services/users/users.go @@ -26,9 +26,9 @@ func (us *UserService) CreateUser(user *model.User, opts UserCreateOptions) (*mo return us.createUser(user) } - user.Roles = model.SYSTEM_USER_ROLE_ID + user.Roles = model.SystemUserRoleId if opts.Guest { - user.Roles = model.SYSTEM_GUEST_ROLE_ID + user.Roles = model.SystemGuestRoleId } if !user.IsLDAPUser() && !user.IsSAMLUser() && !user.IsGuest() && !CheckUserDomain(user, *us.config().TeamSettings.RestrictCreationToDomains) { @@ -46,7 +46,7 @@ func (us *UserService) CreateUser(user *model.User, opts UserCreateOptions) (*mo return nil, UserCountError } if count <= 0 { - user.Roles = model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID + user.Roles = model.SystemAdminRoleId + " " + model.SystemUserRoleId } if _, ok := i18n.GetSupportedLocales()[user.Locale]; !ok { @@ -214,8 +214,8 @@ func (us *UserService) InvalidateCacheForUser(userID string) { if us.cluster != nil { msg := &model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, - SendType: model.CLUSTER_SEND_BEST_EFFORT, + Event: model.ClusterEventInvalidateCacheForUser, + SendType: model.ClusterSendBestEffort, Data: userID, } us.cluster.SendClusterMessage(msg) diff --git a/store/localcachelayer/layer.go b/store/localcachelayer/layer.go index 7bc26eac6b..08e997dd74 100644 --- a/store/localcachelayer/layer.go +++ b/store/localcachelayer/layer.go @@ -26,7 +26,7 @@ const ( FileInfoCacheSize = 25000 FileInfoCacheSec = 30 * 60 - ChannelGuestCountCacheSize = model.CHANNEL_CACHE_SIZE + ChannelGuestCountCacheSize = model.ChannelCacheSize ChannelGuestCountCacheSec = 30 * 60 WebhookCacheSize = 25000 @@ -35,10 +35,10 @@ const ( EmojiCacheSize = 5000 EmojiCacheSec = 30 * 60 - ChannelPinnedPostsCounsCacheSize = model.CHANNEL_CACHE_SIZE + ChannelPinnedPostsCounsCacheSize = model.ChannelCacheSize ChannelPinnedPostsCountsCacheSec = 30 * 60 - ChannelMembersCountsCacheSize = model.CHANNEL_CACHE_SIZE + ChannelMembersCountsCacheSize = model.ChannelCacheSize ChannelMembersCountsCacheSec = 30 * 60 LastPostsCacheSize = 20000 @@ -52,8 +52,8 @@ const ( UserProfileByIDCacheSize = 20000 UserProfileByIDSec = 30 * 60 - ProfilesInChannelCacheSize = model.CHANNEL_CACHE_SIZE - PROFILES_IN_ChannelCacheSec = 15 * 60 + ProfilesInChannelCacheSize = model.ChannelCacheSize + ProfilesInChannelCacheSec = 15 * 60 TeamCacheSize = 20000 TeamCacheSec = 30 * 60 @@ -120,7 +120,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: ReactionCacheSize, Name: "Reaction", DefaultExpiry: ReactionCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForReactions, }); err != nil { return } @@ -131,7 +131,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: RoleCacheSize, Name: "Role", DefaultExpiry: RoleCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLES, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForRoles, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }); err != nil { @@ -141,7 +141,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: RoleCacheSize, Name: "RolePermission", DefaultExpiry: RoleCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLE_PERMISSIONS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForRolePermissions, }); err != nil { return } @@ -152,7 +152,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: SchemeCacheSize, Name: "Scheme", DefaultExpiry: SchemeCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_SCHEMES, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForSchemes, }); err != nil { return } @@ -163,7 +163,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: FileInfoCacheSize, Name: "FileInfo", DefaultExpiry: FileInfoCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_FILE_INFOS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForFileInfos, }); err != nil { return } @@ -174,7 +174,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: WebhookCacheSize, Name: "Webhook", DefaultExpiry: WebhookCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOKS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForWebhooks, }); err != nil { return } @@ -185,7 +185,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: EmojiCacheSize, Name: "EmojiById", DefaultExpiry: EmojiCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_BY_ID, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForEmojisById, }); err != nil { return } @@ -193,7 +193,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: EmojiCacheSize, Name: "EmojiByName", DefaultExpiry: EmojiCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_ID_BY_NAME, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForEmojisIdByName, }); err != nil { return } @@ -209,7 +209,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: ChannelPinnedPostsCounsCacheSize, Name: "ChannelPinnedPostsCounts", DefaultExpiry: ChannelPinnedPostsCountsCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_PINNEDPOSTS_COUNTS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelPinnedpostsCounts, }); err != nil { return } @@ -217,7 +217,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: ChannelMembersCountsCacheSize, Name: "ChannelMemberCounts", DefaultExpiry: ChannelMembersCountsCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBER_COUNTS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelMemberCounts, }); err != nil { return } @@ -225,15 +225,15 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: ChannelGuestCountCacheSize, Name: "ChannelGuestsCount", DefaultExpiry: ChannelGuestCountCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_GUEST_COUNT, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannelGuestCount, }); err != nil { return } if localCacheStore.channelByIdCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: model.CHANNEL_CACHE_SIZE, + Size: model.ChannelCacheSize, Name: "channelById", DefaultExpiry: ChannelCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForChannel, }); err != nil { return } @@ -244,7 +244,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: LastPostsCacheSize, Name: "LastPost", DefaultExpiry: LastPostsCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POSTS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForLastPosts, }); err != nil { return } @@ -252,7 +252,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: LastPostTimeCacheSize, Name: "LastPostTime", DefaultExpiry: LastPostTimeCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POST_TIME, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForLastPostTime, }); err != nil { return } @@ -263,7 +263,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: TermsOfServiceCacheSize, Name: "TermsOfService", DefaultExpiry: TermsOfServiceCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TERMS_OF_SERVICE, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForTermsOfService, }); err != nil { return } @@ -274,7 +274,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: UserProfileByIDCacheSize, Name: "UserProfileByIds", DefaultExpiry: UserProfileByIDSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_BY_IDS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForProfileByIds, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), }); err != nil { @@ -283,8 +283,8 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf if localCacheStore.profilesInChannelCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: ProfilesInChannelCacheSize, Name: "ProfilesInChannel", - DefaultExpiry: PROFILES_IN_ChannelCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_IN_CHANNEL, + DefaultExpiry: ProfilesInChannelCacheSec * time.Second, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForProfileInChannel, }); err != nil { return } @@ -299,31 +299,31 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf Size: TeamCacheSize, Name: "Team", DefaultExpiry: TeamCacheSec * time.Second, - InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TEAMS, + InvalidateClusterEvent: model.ClusterEventInvalidateCacheForTeams, }); err != nil { return } localCacheStore.team = LocalCacheTeamStore{TeamStore: baseStore.Team(), rootStore: &localCacheStore} if cluster != nil { - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS, localCacheStore.reaction.handleClusterInvalidateReaction) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLES, localCacheStore.role.handleClusterInvalidateRole) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLE_PERMISSIONS, localCacheStore.role.handleClusterInvalidateRolePermissions) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_SCHEMES, localCacheStore.scheme.handleClusterInvalidateScheme) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_FILE_INFOS, localCacheStore.fileInfo.handleClusterInvalidateFileInfo) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POST_TIME, localCacheStore.post.handleClusterInvalidateLastPostTime) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOKS, localCacheStore.webhook.handleClusterInvalidateWebhook) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_BY_ID, localCacheStore.emoji.handleClusterInvalidateEmojiById) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_ID_BY_NAME, localCacheStore.emoji.handleClusterInvalidateEmojiIdByName) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_PINNEDPOSTS_COUNTS, localCacheStore.channel.handleClusterInvalidateChannelPinnedPostCount) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBER_COUNTS, localCacheStore.channel.handleClusterInvalidateChannelMemberCounts) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_GUEST_COUNT, localCacheStore.channel.handleClusterInvalidateChannelGuestCounts) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL, localCacheStore.channel.handleClusterInvalidateChannelById) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POSTS, localCacheStore.post.handleClusterInvalidateLastPosts) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TERMS_OF_SERVICE, localCacheStore.termsOfService.handleClusterInvalidateTermsOfService) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_BY_IDS, localCacheStore.user.handleClusterInvalidateScheme) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_IN_CHANNEL, localCacheStore.user.handleClusterInvalidateProfilesInChannel) - cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TEAMS, localCacheStore.team.handleClusterInvalidateTeam) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForReactions, localCacheStore.reaction.handleClusterInvalidateReaction) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForRoles, localCacheStore.role.handleClusterInvalidateRole) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForRolePermissions, localCacheStore.role.handleClusterInvalidateRolePermissions) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForSchemes, localCacheStore.scheme.handleClusterInvalidateScheme) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForFileInfos, localCacheStore.fileInfo.handleClusterInvalidateFileInfo) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForLastPostTime, localCacheStore.post.handleClusterInvalidateLastPostTime) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForWebhooks, localCacheStore.webhook.handleClusterInvalidateWebhook) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForEmojisById, localCacheStore.emoji.handleClusterInvalidateEmojiById) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForEmojisIdByName, localCacheStore.emoji.handleClusterInvalidateEmojiIdByName) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelPinnedpostsCounts, localCacheStore.channel.handleClusterInvalidateChannelPinnedPostCount) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMemberCounts, localCacheStore.channel.handleClusterInvalidateChannelMemberCounts) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelGuestCount, localCacheStore.channel.handleClusterInvalidateChannelGuestCounts) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannel, localCacheStore.channel.handleClusterInvalidateChannelById) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForLastPosts, localCacheStore.post.handleClusterInvalidateLastPosts) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForTermsOfService, localCacheStore.termsOfService.handleClusterInvalidateTermsOfService) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForProfileByIds, localCacheStore.user.handleClusterInvalidateScheme) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForProfileInChannel, localCacheStore.user.handleClusterInvalidateProfilesInChannel) + cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForTeams, localCacheStore.team.handleClusterInvalidateTeam) } return } @@ -389,7 +389,7 @@ func (s *LocalCacheStore) doInvalidateCacheCluster(cache cache.Cache, key string if s.cluster != nil { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), - SendType: model.CLUSTER_SEND_BEST_EFFORT, + SendType: model.ClusterSendBestEffort, Data: key, } s.cluster.SendClusterMessage(msg) @@ -419,7 +419,7 @@ func (s *LocalCacheStore) doClearCacheCluster(cache cache.Cache) { if s.cluster != nil { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), - SendType: model.CLUSTER_SEND_BEST_EFFORT, + SendType: model.ClusterSendBestEffort, Data: ClearCacheMessageData, } s.cluster.SendClusterMessage(msg) diff --git a/store/localcachelayer/layer_test.go b/store/localcachelayer/layer_test.go index 7280b39c3a..da0572b000 100644 --- a/store/localcachelayer/layer_test.go +++ b/store/localcachelayer/layer_test.go @@ -76,13 +76,13 @@ func initStores() { if os.Getenv("IS_CI") == "true" { switch os.Getenv("MM_SQLSETTINGS_DRIVERNAME") { case "mysql": - storeTypes = append(storeTypes, newStoreType("LocalCache+MySQL", model.DATABASE_DRIVER_MYSQL)) + storeTypes = append(storeTypes, newStoreType("LocalCache+MySQL", model.DatabaseDriverMysql)) case "postgres": - storeTypes = append(storeTypes, newStoreType("LocalCache+PostgreSQL", model.DATABASE_DRIVER_POSTGRES)) + storeTypes = append(storeTypes, newStoreType("LocalCache+PostgreSQL", model.DatabaseDriverPostgres)) } } else { - storeTypes = append(storeTypes, newStoreType("LocalCache+MySQL", model.DATABASE_DRIVER_MYSQL), - newStoreType("LocalCache+PostgreSQL", model.DATABASE_DRIVER_POSTGRES)) + storeTypes = append(storeTypes, newStoreType("LocalCache+MySQL", model.DatabaseDriverMysql), + newStoreType("LocalCache+PostgreSQL", model.DatabaseDriverPostgres)) } defer func() { diff --git a/store/searchlayer/channel_layer.go b/store/searchlayer/channel_layer.go index e5a2339eef..2650072c7c 100644 --- a/store/searchlayer/channel_layer.go +++ b/store/searchlayer/channel_layer.go @@ -20,7 +20,7 @@ type SearchChannelStore struct { } func (c *SearchChannelStore) deleteChannelIndex(channel *model.Channel) { - if channel.Type == model.CHANNEL_OPEN { + if channel.Type == model.ChannelTypeOpen { for _, engine := range c.rootStore.searchEngine.GetActiveEngines() { if engine.IsIndexingEnabled() { runIndexFn(engine, func(engineCopy searchengine.SearchEngineInterface) { @@ -36,7 +36,7 @@ func (c *SearchChannelStore) deleteChannelIndex(channel *model.Channel) { } func (c *SearchChannelStore) indexChannel(channel *model.Channel) { - if channel.Type == model.CHANNEL_OPEN { + if channel.Type == model.ChannelTypeOpen { for _, engine := range c.rootStore.searchEngine.GetActiveEngines() { if engine.IsIndexingEnabled() { runIndexFn(engine, func(engineCopy searchengine.SearchEngineInterface) { diff --git a/store/searchlayer/layer_test.go b/store/searchlayer/layer_test.go index adaa4579dc..e6e6d54445 100644 --- a/store/searchlayer/layer_test.go +++ b/store/searchlayer/layer_test.go @@ -21,7 +21,7 @@ import ( func TestUpdateConfigRace(t *testing.T) { driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") if driverName == "" { - driverName = model.DATABASE_DRIVER_POSTGRES + driverName = model.DatabaseDriverPostgres } settings := storetest.MakeSqlSettings(driverName, false) store := sqlstore.New(*settings, nil) diff --git a/store/searchtest/channel_layer.go b/store/searchtest/channel_layer.go index 08a1110e21..631bd89f65 100644 --- a/store/searchtest/channel_layer.go +++ b/store/searchtest/channel_layer.go @@ -76,7 +76,7 @@ func TestSearchChannelStore(t *testing.T, s store.Store, testEngine *SearchTestE } func testAutocompleteChannelByName(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "Channel Alternate", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "Channel Alternate", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channel-a", false) @@ -85,7 +85,7 @@ func testAutocompleteChannelByName(t *testing.T, th *SearchTestHelper) { } func testAutocompleteChannelByDisplayName(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "ChannelA", false) @@ -94,7 +94,7 @@ func testAutocompleteChannelByDisplayName(t *testing.T, th *SearchTestHelper) { } func testAutocompleteChannelByNameSplittedWithDashChar(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channel-a", false) @@ -103,7 +103,7 @@ func testAutocompleteChannelByNameSplittedWithDashChar(t *testing.T, th *SearchT } func testAutocompleteChannelByNameSplittedWithUnderscoreChar(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel_alternate", "ChannelAlternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel_alternate", "ChannelAlternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channel_a", false) @@ -112,7 +112,7 @@ func testAutocompleteChannelByNameSplittedWithUnderscoreChar(t *testing.T, th *S } func testAutocompleteChannelByDisplayNameSplittedByWhitespaces(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) @@ -121,9 +121,9 @@ func testAutocompleteChannelByDisplayNameSplittedByWhitespaces(t *testing.T, th th.checkChannelIdsMatch(t, []string{alternate.Id}, res) } func testAutocompleteAllChannelsIfTermIsEmpty(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "Channel Alternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) - other, err := th.createChannel(th.Team.Id, "other-channel", "Other Channel", "", model.CHANNEL_OPEN, false) + other, err := th.createChannel(th.Team.Id, "other-channel", "Other Channel", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) defer th.deleteChannel(other) @@ -133,7 +133,7 @@ func testAutocompleteAllChannelsIfTermIsEmpty(t *testing.T, th *SearchTestHelper } func testSearchChannelsInCaseInsensitiveManner(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channela", false) @@ -145,7 +145,7 @@ func testSearchChannelsInCaseInsensitiveManner(t *testing.T, th *SearchTestHelpe } func testSearchOnlyPublicChannels(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.CHANNEL_PRIVATE, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.ChannelTypePrivate, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channel-a", false) @@ -154,7 +154,7 @@ func testSearchOnlyPublicChannels(t *testing.T, th *SearchTestHelper) { } func testSearchShouldSupportHavingHyphenAsLastCharacter(t *testing.T, th *SearchTestHelper) { - alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.CHANNEL_OPEN, false) + alternate, err := th.createChannel(th.Team.Id, "channel-alternate", "ChannelAlternate", "", model.ChannelTypeOpen, false) require.NoError(t, err) defer th.deleteChannel(alternate) res, err := th.Store.Channel().AutocompleteInTeam(th.Team.Id, "channel-", false) diff --git a/store/searchtest/file_info_layer.go b/store/searchtest/file_info_layer.go index 0ac41a33f2..f96d481487 100644 --- a/store/searchtest/file_info_layer.go +++ b/store/searchtest/file_info_layer.go @@ -200,11 +200,11 @@ func testFileInfoSearchFileInfosIncludingDMs(t *testing.T, th *SearchTestHelper) require.NoError(t, err) defer th.deleteChannel(direct) - post, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "dm test", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "dm test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) p1, err := th.createFileInfo(th.User.Id, post.Id, "dm test filename", "dm contenttest filename", "jpg", "image/jpeg", 0, 1) @@ -241,11 +241,11 @@ func testFileInfoSearchFileInfosWithPagination(t *testing.T, th *SearchTestHelpe require.NoError(t, err) defer th.deleteChannel(direct) - post, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.POST_DEFAULT, 10000, false) + post, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.PostTypeDefault, 10000, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "dm test", "", model.POST_DEFAULT, 20000, false) + post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "dm test", "", model.PostTypeDefault, 20000, false) require.NoError(t, err) p1, err := th.createFileInfo(th.User.Id, post.Id, "dm test filename", "dm contenttest filename", "jpg", "image/jpeg", 10000, 0) @@ -288,7 +288,7 @@ func testFileInfoSearchFileInfosWithPagination(t *testing.T, th *SearchTestHelpe } func testFileInfoSearchExactPhraseInQuotes(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -318,7 +318,7 @@ func testFileInfoSearchExactPhraseInQuotes(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchEmailAddresses(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -369,7 +369,7 @@ func testFileInfoSearchEmailAddresses(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchMarkdownUnderscores(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -415,7 +415,7 @@ func testFileInfoSearchMarkdownUnderscores(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -546,7 +546,7 @@ func testFileInfoSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchAlternativeSpellings(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -574,7 +574,7 @@ func testFileInfoSearchAlternativeSpellings(t *testing.T, th *SearchTestHelper) } func testFileInfoSearchAlternativeSpellingsAccents(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -608,7 +608,7 @@ func testFileInfoSearchAlternativeSpellingsAccents(t *testing.T, th *SearchTestH } func testFileInfoSearchOrExcludeFileInfosBySpecificUser(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -628,10 +628,10 @@ func testFileInfoSearchOrExcludeFileInfosBySpecificUser(t *testing.T, th *Search } func testFileInfoSearchOrExcludeFileInfosInChannel(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -659,9 +659,9 @@ func testFileInfoSearchOrExcludeFileInfosInDMGM(t *testing.T, th *SearchTestHelp require.NoError(t, err) defer th.deleteChannel(group) - post1, err := th.createPost(th.User.Id, direct.Id, "test fromuser", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, direct.Id, "test fromuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User2.Id, group.Id, "test fromuser 2", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User2.Id, group.Id, "test fromuser 2", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) defer th.deleteUserPosts(th.User2.Id) @@ -712,7 +712,7 @@ func testFileInfoSearchOrExcludeFileInfosInDMGM(t *testing.T, th *SearchTestHelp } func testFileInfoSearchOrExcludeByExtensions(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -780,9 +780,9 @@ func testFileInfoSearchOrExcludeByExtensions(t *testing.T, th *SearchTestHelper) } func testFileInfoFilterFilesInSpecificDate(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -823,9 +823,9 @@ func testFileInfoFilterFilesInSpecificDate(t *testing.T, th *SearchTestHelper) { } func testFileInfoFilterFilesBeforeSpecificDate(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -867,9 +867,9 @@ func testFileInfoFilterFilesBeforeSpecificDate(t *testing.T, th *SearchTestHelpe } func testFileInfoFilterFilesAfterSpecificDate(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -911,9 +911,9 @@ func testFileInfoFilterFilesAfterSpecificDate(t *testing.T, th *SearchTestHelper } func testFileInfoFilterFilesWithATerm(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -952,7 +952,7 @@ func testFileInfoFilterFilesWithATerm(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchUsingBooleanOperators(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -991,9 +991,9 @@ func testFileInfoSearchUsingBooleanOperators(t *testing.T, th *SearchTestHelper) } func testFileInfoSearchUsingCombinedFilters(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1063,7 +1063,7 @@ func testFileInfoSearchUsingCombinedFilters(t *testing.T, th *SearchTestHelper) } func testFileInfoSearchIgnoringStopWords(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1125,7 +1125,7 @@ func testFileInfoSearchIgnoringStopWords(t *testing.T, th *SearchTestHelper) { } func testFileInfoSupportStemming(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1149,7 +1149,7 @@ func testFileInfoSupportStemming(t *testing.T, th *SearchTestHelper) { } func testFileInfoSupportWildcards(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1186,7 +1186,7 @@ func testFileInfoSupportWildcards(t *testing.T, th *SearchTestHelper) { } func testFileInfoNotSupportPrecedingWildcards(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1208,7 +1208,7 @@ func testFileInfoNotSupportPrecedingWildcards(t *testing.T, th *SearchTestHelper } func testFileInfoSearchDiscardWildcardAlone(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1229,7 +1229,7 @@ func testFileInfoSearchDiscardWildcardAlone(t *testing.T, th *SearchTestHelper) } func testFileInfoSupportTermsWithDash(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1263,7 +1263,7 @@ func testFileInfoSupportTermsWithDash(t *testing.T, th *SearchTestHelper) { } func testFileInfoSupportTermsWithUnderscore(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1297,13 +1297,13 @@ func testFileInfoSupportTermsWithUnderscore(t *testing.T, th *SearchTestHelper) } func testFileInfoSearchInDeletedOrArchivedChannels(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelDeleted.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelDeleted.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1378,7 +1378,7 @@ func testFileInfoSearchInDeletedOrArchivedChannels(t *testing.T, th *SearchTestH } func testFileInfoSearchTermsWithDashes(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1427,7 +1427,7 @@ func testFileInfoSearchTermsWithDashes(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchTermsWithDots(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1476,7 +1476,7 @@ func testFileInfoSearchTermsWithDots(t *testing.T, th *SearchTestHelper) { } func testFileInfoSearchTermsWithUnderscores(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1525,10 +1525,10 @@ func testFileInfoSearchTermsWithUnderscores(t *testing.T, th *SearchTestHelper) } func testFileInfoSupportStemmingAndWildcards(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1562,10 +1562,10 @@ func testFileInfoSupportStemmingAndWildcards(t *testing.T, th *SearchTestHelper) } func testFileInfoSupportWildcardOutsideQuotes(t *testing.T, th *SearchTestHelper) { - post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) - post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) p1, err := th.createFileInfo(th.User.Id, post1.Id, "hello world", "hello world", "jpg", "image/jpeg", 0, 0) @@ -1596,7 +1596,7 @@ func testFileInfoSupportWildcardOutsideQuotes(t *testing.T, th *SearchTestHelper } func testFileInfoSlashShouldNotBeCharSeparator(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1627,7 +1627,7 @@ func testFileInfoSlashShouldNotBeCharSeparator(t *testing.T, th *SearchTestHelpe } func testFileInfoSearchEmailsWithoutQuotes(t *testing.T, th *SearchTestHelper) { - post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.POST_DEFAULT, 0, false) + post, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "testmessage", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) diff --git a/store/searchtest/helper.go b/store/searchtest/helper.go index 0581047e72..109721ee05 100644 --- a/store/searchtest/helper.go +++ b/store/searchtest/helper.go @@ -36,11 +36,11 @@ func (th *SearchTestHelper) SetupBasicFixtures() error { } // Create teams - team, err := th.createTeam("searchtest-team", "Searchtest team", model.TEAM_OPEN) + team, err := th.createTeam("searchtest-team", "Searchtest team", model.TeamOpen) if err != nil { return err } - anotherTeam, err := th.createTeam("another-searchtest-team", "Another Searchtest team", model.TEAM_OPEN) + anotherTeam, err := th.createTeam("another-searchtest-team", "Another Searchtest team", model.TeamOpen) if err != nil { return err } @@ -60,19 +60,19 @@ func (th *SearchTestHelper) SetupBasicFixtures() error { } // Create channels - channelBasic, err := th.createChannel(team.Id, "channel-a", "ChannelA", "", model.CHANNEL_OPEN, false) + channelBasic, err := th.createChannel(team.Id, "channel-a", "ChannelA", "", model.ChannelTypeOpen, false) if err != nil { return err } - channelPrivate, err := th.createChannel(team.Id, "channel-private", "ChannelPrivate", "", model.CHANNEL_PRIVATE, false) + channelPrivate, err := th.createChannel(team.Id, "channel-private", "ChannelPrivate", "", model.ChannelTypePrivate, false) if err != nil { return err } - channelDeleted, err := th.createChannel(team.Id, "channel-deleted", "ChannelA (deleted)", "", model.CHANNEL_OPEN, true) + channelDeleted, err := th.createChannel(team.Id, "channel-deleted", "ChannelA (deleted)", "", model.ChannelTypeOpen, true) if err != nil { return err } - channelAnotherTeam, err := th.createChannel(anotherTeam.Id, "channel-a", "ChannelA", "", model.CHANNEL_OPEN, false) + channelAnotherTeam, err := th.createChannel(anotherTeam.Id, "channel-a", "ChannelA", "", model.ChannelTypeOpen, false) if err != nil { return err } @@ -185,7 +185,7 @@ func (th *SearchTestHelper) createGuest(username, nickname, firstName, lastName FirstName: firstName, LastName: lastName, Email: th.makeEmail(), - Roles: model.SYSTEM_GUEST_ROLE_ID, + Roles: model.SystemGuestRoleId, }) } @@ -266,7 +266,7 @@ func (th *SearchTestHelper) createDirectChannel(teamID, name, displayName string TeamId: teamID, Name: name, DisplayName: displayName, - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, } m1 := &model.ChannelMember{} @@ -296,7 +296,7 @@ func (th *SearchTestHelper) createGroupChannel(teamID, displayName string, users TeamId: teamID, Name: model.GetGroupNameFromUserIds(userIDS), DisplayName: displayName, - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } channel, err := th.Store.Channel().Save(group, 10000) diff --git a/store/searchtest/post_layer.go b/store/searchtest/post_layer.go index 89e229e0c8..baab1e1e33 100644 --- a/store/searchtest/post_layer.go +++ b/store/searchtest/post_layer.go @@ -280,11 +280,11 @@ func testSearchPostsIncludingDMs(t *testing.T, th *SearchTestHelper) { require.NoError(t, err) defer th.deleteChannel(direct) - p1, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, direct.Id, "dm other", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, direct.Id, "dm other", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -302,11 +302,11 @@ func testSearchPostsWithPagination(t *testing.T, th *SearchTestHelper) { require.NoError(t, err) defer th.deleteChannel(direct) - p1, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.POST_DEFAULT, 10000, false) + p1, err := th.createPost(th.User.Id, direct.Id, "dm test", "", model.PostTypeDefault, 10000, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, direct.Id, "dm other", "", model.POST_DEFAULT, 20000, false) + _, err = th.createPost(th.User.Id, direct.Id, "dm other", "", model.PostTypeDefault, 20000, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -325,9 +325,9 @@ func testSearchPostsWithPagination(t *testing.T, th *SearchTestHelper) { } func testSearchReturnPinnedAndUnpinned(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test unpinned", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test unpinned", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test pinned", "", model.POST_DEFAULT, 0, true) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test pinned", "", model.PostTypeDefault, 0, true) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -341,13 +341,13 @@ func testSearchReturnPinnedAndUnpinned(t *testing.T, th *SearchTestHelper) { } func testSearchExactPhraseInQuotes(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test 1 2 3", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test 1 2 3", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test 123", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel test 123", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel something test 1 2 3", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel something test 1 2 3", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel 1 2 3", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "channel 1 2 3", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -361,9 +361,9 @@ func testSearchExactPhraseInQuotes(t *testing.T, th *SearchTestHelper) { } func testSearchEmailAddresses(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test email test@test.com", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test email test@test.com", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test email test2@test.com", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test email test2@test.com", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -387,7 +387,7 @@ func testSearchEmailAddresses(t *testing.T, th *SearchTestHelper) { } func testSearchMarkdownUnderscores(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "_start middle end_ _another_", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "_start middle end_ _another_", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -430,9 +430,9 @@ func testSearchMarkdownUnderscores(t *testing.T, th *SearchTestHelper) { func testSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { t.Run("Should be able to search chinese words", func(t *testing.T) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "你好", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "你好", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "你", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "你", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -463,7 +463,7 @@ func testSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { }) }) t.Run("Should be able to search cyrillic words", func(t *testing.T) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "слово test", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "слово test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -486,9 +486,9 @@ func testSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { }) t.Run("Should be able to search japanese words", func(t *testing.T) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "本", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "本", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "本木", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "本木", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -521,9 +521,9 @@ func testSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { }) t.Run("Should be able to search korean words", func(t *testing.T) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "불", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "불", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "불다", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "불다", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -556,9 +556,9 @@ func testSearchNonLatinWords(t *testing.T, th *SearchTestHelper) { } func testSearchAlternativeSpellings(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "Straße test", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "Straße test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "Strasse test", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "Strasse test", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -580,9 +580,9 @@ func testSearchAlternativeSpellings(t *testing.T, th *SearchTestHelper) { } func testSearchAlternativeSpellingsAccents(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "café", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "café", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "café", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "café", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -610,9 +610,9 @@ func testSearchAlternativeSpellingsAccents(t *testing.T, th *SearchTestHelper) { } func testSearchOrExcludePostsBySpecificUser(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test fromuser", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test fromuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User2.Id, th.ChannelPrivate.Id, "test fromuser 2", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User2.Id, th.ChannelPrivate.Id, "test fromuser 2", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) defer th.deleteUserPosts(th.User2.Id) @@ -629,9 +629,9 @@ func testSearchOrExcludePostsBySpecificUser(t *testing.T, th *SearchTestHelper) } func testSearchOrExcludePostsInChannel(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test fromuser", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test fromuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User2.Id, th.ChannelPrivate.Id, "test fromuser 2", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User2.Id, th.ChannelPrivate.Id, "test fromuser 2", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) defer th.deleteUserPosts(th.User2.Id) @@ -656,9 +656,9 @@ func testSearchOrExcludePostsInDMGM(t *testing.T, th *SearchTestHelper) { require.NoError(t, err) defer th.deleteChannel(group) - p1, err := th.createPost(th.User.Id, direct.Id, "test fromuser", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, direct.Id, "test fromuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User2.Id, group.Id, "test fromuser 2", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User2.Id, group.Id, "test fromuser 2", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) defer th.deleteUserPosts(th.User2.Id) @@ -703,13 +703,13 @@ func testSearchOrExcludePostsInDMGM(t *testing.T, th *SearchTestHelper) { func testFilterMessagesInSpecificDate(t *testing.T, th *SearchTestHelper) { creationDate := model.GetMillisForTime(time.Date(2020, 03, 22, 12, 0, 0, 0, time.UTC)) - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.POST_DEFAULT, creationDate, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.PostTypeDefault, creationDate, false) require.NoError(t, err) creationDate2 := model.GetMillisForTime(time.Date(2020, 03, 23, 0, 0, 0, 0, time.UTC)) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in the present", "", model.POST_DEFAULT, creationDate2, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in the present", "", model.PostTypeDefault, creationDate2, false) require.NoError(t, err) creationDate3 := model.GetMillisForTime(time.Date(2020, 03, 21, 23, 59, 59, 0, time.UTC)) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.POST_DEFAULT, creationDate3, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.PostTypeDefault, creationDate3, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -740,13 +740,13 @@ func testFilterMessagesInSpecificDate(t *testing.T, th *SearchTestHelper) { func testFilterMessagesBeforeSpecificDate(t *testing.T, th *SearchTestHelper) { creationDate := model.GetMillisForTime(time.Date(2020, 03, 01, 12, 0, 0, 0, time.UTC)) - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.POST_DEFAULT, creationDate, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.PostTypeDefault, creationDate, false) require.NoError(t, err) creationDate2 := model.GetMillisForTime(time.Date(2020, 03, 22, 23, 59, 59, 0, time.UTC)) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in specific date 2", "", model.POST_DEFAULT, creationDate2, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in specific date 2", "", model.PostTypeDefault, creationDate2, false) require.NoError(t, err) creationDate3 := model.GetMillisForTime(time.Date(2020, 03, 26, 16, 55, 0, 0, time.UTC)) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.POST_DEFAULT, creationDate3, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.PostTypeDefault, creationDate3, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -778,13 +778,13 @@ func testFilterMessagesBeforeSpecificDate(t *testing.T, th *SearchTestHelper) { func testFilterMessagesAfterSpecificDate(t *testing.T, th *SearchTestHelper) { creationDate := model.GetMillisForTime(time.Date(2020, 03, 01, 12, 0, 0, 0, time.UTC)) - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.POST_DEFAULT, creationDate, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in specific date", "", model.PostTypeDefault, creationDate, false) require.NoError(t, err) creationDate2 := model.GetMillisForTime(time.Date(2020, 03, 22, 23, 59, 59, 0, time.UTC)) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in specific date 2", "", model.POST_DEFAULT, creationDate2, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "test in specific date 2", "", model.PostTypeDefault, creationDate2, false) require.NoError(t, err) creationDate3 := model.GetMillisForTime(time.Date(2020, 03, 26, 16, 55, 0, 0, time.UTC)) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.POST_DEFAULT, creationDate3, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test in the present", "", model.PostTypeDefault, creationDate3, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -815,11 +815,11 @@ func testFilterMessagesAfterSpecificDate(t *testing.T, th *SearchTestHelper) { } func testFilterMessagesWithATerm(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one two three", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one two three", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "one four five six", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "one four five six", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "one seven eight nine", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "one seven eight nine", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -850,11 +850,11 @@ func testFilterMessagesWithATerm(t *testing.T, th *SearchTestHelper) { } func testSearchUsingBooleanOperators(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one two three message", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one two three message", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "two messages", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "two messages", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another message", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another message", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -886,13 +886,13 @@ func testSearchUsingBooleanOperators(t *testing.T, th *SearchTestHelper) { func testSearchUsingCombinedFilters(t *testing.T, th *SearchTestHelper) { creationDate := model.GetMillisForTime(time.Date(2020, 03, 01, 12, 0, 0, 0, time.UTC)) - p1, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "one two three message", "", model.POST_DEFAULT, creationDate, false) + p1, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "one two three message", "", model.PostTypeDefault, creationDate, false) require.NoError(t, err) creationDate2 := model.GetMillisForTime(time.Date(2020, 03, 10, 12, 0, 0, 0, time.UTC)) - p2, err := th.createPost(th.User2.Id, th.ChannelPrivate.Id, "two messages", "", model.POST_DEFAULT, creationDate2, false) + p2, err := th.createPost(th.User2.Id, th.ChannelPrivate.Id, "two messages", "", model.PostTypeDefault, creationDate2, false) require.NoError(t, err) creationDate3 := model.GetMillisForTime(time.Date(2020, 03, 20, 12, 0, 0, 0, time.UTC)) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "two another message", "", model.POST_DEFAULT, creationDate3, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "two another message", "", model.PostTypeDefault, creationDate3, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) defer th.deleteUserPosts(th.User2.Id) @@ -951,13 +951,13 @@ func testSearchUsingCombinedFilters(t *testing.T, th *SearchTestHelper) { } func testSearchIgnoringStopWords(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "the search for a bunch of stop words", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "the search for a bunch of stop words", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "the objective is to avoid a bunch of stop words", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "the objective is to avoid a bunch of stop words", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "in the a on to where you", "", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "in the a on to where you", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p4, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "where is the car?", "", model.POST_DEFAULT, 0, false) + p4, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "where is the car?", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1009,11 +1009,11 @@ func testSearchIgnoringStopWords(t *testing.T, th *SearchTestHelper) { } func testSupportStemming(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching post", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1029,11 +1029,11 @@ func testSupportStemming(t *testing.T, th *SearchTestHelper) { } func testSupportWildcards(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1062,11 +1062,11 @@ func testSupportWildcards(t *testing.T, th *SearchTestHelper) { } func testNotSupportPrecedingWildcards(t *testing.T, th *SearchTestHelper) { - _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.POST_DEFAULT, 0, false) + _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching post", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "another post", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1080,9 +1080,9 @@ func testNotSupportPrecedingWildcards(t *testing.T, th *SearchTestHelper) { } func testSearchDiscardWildcardAlone(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "qwerty", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "qwerty", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "qwertyjkl", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "qwertyjkl", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1097,9 +1097,9 @@ func testSearchDiscardWildcardAlone(t *testing.T, th *SearchTestHelper) { } func testSupportTermsWithDash(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search term-with-dash", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search term-with-dash", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with dash", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with dash", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1127,9 +1127,9 @@ func testSupportTermsWithDash(t *testing.T, th *SearchTestHelper) { } func testSupportTermsWithUnderscore(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search term_with_underscore", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search term_with_underscore", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with underscore", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with underscore", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1157,11 +1157,11 @@ func testSupportTermsWithUnderscore(t *testing.T, th *SearchTestHelper) { } func testSearchOrExcludePostsWithHashtags(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post with #hashtag", "#hashtag", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "search post with #hashtag", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with hashtag", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with hashtag", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with", "#hashtag", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1193,15 +1193,15 @@ func testSearchOrExcludePostsWithHashtags(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagWithMarkdown(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with `#hashtag`", "#hashtag", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with `#hashtag`", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with **#hashtag**", "#hashtag", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with **#hashtag**", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p4, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with ~~#hashtag~~", "#hashtag", model.POST_DEFAULT, 0, false) + p4, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with ~~#hashtag~~", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p5, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with _#hashtag_", "#hashtag", model.POST_DEFAULT, 0, false) + p5, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with _#hashtag_", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1221,9 +1221,9 @@ func testSearchHashtagWithMarkdown(t *testing.T, th *SearchTestHelper) { } func testSearcWithMultipleHashtags(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtwo #hashone", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtwo #hashone", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with `#hashtag`", "#hashtwo #hashthree", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching term with `#hashtag`", "#hashtwo #hashthree", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1255,7 +1255,7 @@ func testSearcWithMultipleHashtags(t *testing.T, th *SearchTestHelper) { } func testSearchPostsWithDotsInHashtags(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag.dot", "#hashtag.dot", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag.dot", "#hashtag.dot", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1271,11 +1271,11 @@ func testSearchPostsWithDotsInHashtags(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagCaseInsensitive(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #HaShTaG", "#HaShTaG", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #HaShTaG", "#HaShTaG", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #HASHTAG", "#HASHTAG", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #HASHTAG", "#HASHTAG", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1323,9 +1323,9 @@ func testSearchHashtagCaseInsensitive(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagWithDash(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag-test", "#hashtag-test", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag-test", "#hashtag-test", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1341,9 +1341,9 @@ func testSearchHashtagWithDash(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagWithNumbers(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #h4sht4g", "#h4sht4g", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #h4sht4g", "#h4sht4g", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag", "#hashtag", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1359,9 +1359,9 @@ func testSearchHashtagWithNumbers(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagWithDots(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag.test", "#hashtag.test", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag.test", "#hashtag.test", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1377,9 +1377,9 @@ func testSearchHashtagWithDots(t *testing.T, th *SearchTestHelper) { } func testSearchHashtagWithUnderscores(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag_test", "#hashtag_test", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtag_test", "#hashtag_test", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "searching hashtag #hashtagtest", "#hashtagtest", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1395,17 +1395,17 @@ func testSearchHashtagWithUnderscores(t *testing.T, th *SearchTestHelper) { } func testSearchShouldExcludeSytemMessages(t *testing.T, th *SearchTestHelper) { - _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message one", "", model.POST_JOIN_CHANNEL, 0, false) + _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message one", "", model.PostTypeJoinChannel, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message two", "", model.POST_LEAVE_CHANNEL, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message two", "", model.PostTypeLeaveChannel, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message three", "", model.POST_LEAVE_TEAM, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message three", "", model.PostTypeLeaveTeam, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message four", "", model.POST_ADD_TO_CHANNEL, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message four", "", model.PostTypeAddToChannel, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message five", "", model.POST_ADD_TO_TEAM, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message five", "", model.PostTypeAddToTeam, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message six", "", model.POST_HEADER_CHANGE, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "test system message six", "", model.PostTypeHeaderChange, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1417,11 +1417,11 @@ func testSearchShouldExcludeSytemMessages(t *testing.T, th *SearchTestHelper) { } func testSearchShouldBeAbleToMatchByMentions(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system @testuser", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system @testuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system testuser", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system testuser", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system #testuser", "#testuser", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "test system #testuser", "#testuser", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1436,11 +1436,11 @@ func testSearchShouldBeAbleToMatchByMentions(t *testing.T, th *SearchTestHelper) } func testSearchInDeletedOrArchivedChannels(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelDeleted.Id, "message in deleted channel", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelDeleted.Id, "message in deleted channel", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message in regular channel", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message in regular channel", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "message in private channel", "", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "message in private channel", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1507,9 +1507,9 @@ func testSearchInDeletedOrArchivedChannels(t *testing.T, th *SearchTestHelper) { } func testSearchTermsWithDashes(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with-dash-term", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with-dash-term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with dash term", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with dash term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1552,9 +1552,9 @@ func testSearchTermsWithDashes(t *testing.T, th *SearchTestHelper) { } func testSearchTermsWithDots(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with.dots.term", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with.dots.term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with dots term", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with dots term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1597,9 +1597,9 @@ func testSearchTermsWithDots(t *testing.T, th *SearchTestHelper) { } func testSearchTermsWithUnderscores(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with_underscores_term", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with_underscores_term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with underscores term", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with underscores term", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1647,9 +1647,9 @@ func testSearchBotAccountsPosts(t *testing.T, th *SearchTestHelper) { defer th.deleteBot(bot.UserId) err = th.addUserToTeams(model.UserFromBot(bot), []string{th.Team.Id}) require.NoError(t, err) - p1, err := th.createPost(bot.UserId, th.ChannelBasic.Id, "bot test message", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(bot.UserId, th.ChannelBasic.Id, "bot test message", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(bot.UserId, th.ChannelPrivate.Id, "bot test message in private", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(bot.UserId, th.ChannelPrivate.Id, "bot test message in private", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(bot.UserId) @@ -1663,11 +1663,11 @@ func testSearchBotAccountsPosts(t *testing.T, th *SearchTestHelper) { } func testSupportStemmingAndWildcards(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "approve", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "approve", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "approved", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "approved", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "approvedz", "", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "approvedz", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1693,9 +1693,9 @@ func testSupportStemmingAndWildcards(t *testing.T, th *SearchTestHelper) { } func testSupportWildcardOutsideQuotes(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "hello world", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "hello world", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "hell or heaven", "", model.POST_DEFAULT, 0, false) + p2, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "hell or heaven", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1721,11 +1721,11 @@ func testSupportWildcardOutsideQuotes(t *testing.T, th *SearchTestHelper) { } func testHashtagSearchShouldSupportThreeOrMoreCharacters(t *testing.T, th *SearchTestHelper) { - _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one char hashtag #1", "#1", model.POST_DEFAULT, 0, false) + _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "one char hashtag #1", "#1", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelPrivate.Id, "two chars hashtag #12", "#12", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelPrivate.Id, "two chars hashtag #12", "#12", model.PostTypeDefault, 0, false) require.NoError(t, err) - p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "three chars hashtag #123", "#123", model.POST_DEFAULT, 0, false) + p3, err := th.createPost(th.User.Id, th.ChannelPrivate.Id, "three chars hashtag #123", "#123", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1738,7 +1738,7 @@ func testHashtagSearchShouldSupportThreeOrMoreCharacters(t *testing.T, th *Searc } func testSlashShouldNotBeCharSeparator(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "alpha/beta gamma, theta", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "alpha/beta gamma, theta", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1765,9 +1765,9 @@ func testSlashShouldNotBeCharSeparator(t *testing.T, th *SearchTestHelper) { } func testSearchEmailsWithoutQuotes(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message test@test.com", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message test@test.com", "", model.PostTypeDefault, 0, false) require.NoError(t, err) - _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "message test2@test.com", "", model.POST_DEFAULT, 0, false) + _, err = th.createPost(th.User.Id, th.ChannelBasic.Id, "message test2@test.com", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1780,7 +1780,7 @@ func testSearchEmailsWithoutQuotes(t *testing.T, th *SearchTestHelper) { } func testSupportSearchInComments(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message test@test.com", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message test@test.com", "", model.PostTypeDefault, 0, false) require.NoError(t, err) r1, err := th.createReply(th.User.Id, "reply check", "", p1, 0, false) require.NoError(t, err) @@ -1795,7 +1795,7 @@ func testSupportSearchInComments(t *testing.T, th *SearchTestHelper) { } func testSupportSearchTermsWithinLinks(t *testing.T, th *SearchTestHelper) { - p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with link http://www.wikipedia.org/dolphins", "", model.POST_DEFAULT, 0, false) + p1, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with link http://www.wikipedia.org/dolphins", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) @@ -1808,7 +1808,7 @@ func testSupportSearchTermsWithinLinks(t *testing.T, th *SearchTestHelper) { } func testShouldNotReturnLinksEmbeddedInMarkdown(t *testing.T, th *SearchTestHelper) { - _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with link [here](http://www.wikipedia.org/dolphins)", "", model.POST_DEFAULT, 0, false) + _, err := th.createPost(th.User.Id, th.ChannelBasic.Id, "message with link [here](http://www.wikipedia.org/dolphins)", "", model.PostTypeDefault, 0, false) require.NoError(t, err) defer th.deleteUserPosts(th.User.Id) diff --git a/store/searchtest/user_layer.go b/store/searchtest/user_layer.go index b5c1d23121..2d9638764e 100644 --- a/store/searchtest/user_layer.go +++ b/store/searchtest/user_layer.go @@ -167,7 +167,7 @@ func TestSearchUserStore(t *testing.T, s store.Store, testEngine *SearchTestEngi func testGetAllUsersInChannelWithEmptyTerm(t *testing.T, th *SearchTestHelper) { options := &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, } users, err := th.Store.User().AutocompleteUsersInChannel(th.Team.Id, th.ChannelBasic.Id, "", options) require.NoError(t, err) @@ -870,6 +870,6 @@ func createDefaultOptions(allowFullName, allowEmails, allowInactive bool) *model AllowFullNames: allowFullName, AllowEmails: allowEmails, AllowInactive: allowInactive, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, } } diff --git a/store/sqlstore/bot_store.go b/store/sqlstore/bot_store.go index 460635470f..79d7be06ab 100644 --- a/store/sqlstore/bot_store.go +++ b/store/sqlstore/bot_store.go @@ -57,7 +57,7 @@ func newSqlBotStore(sqlStore *SqlStore, metrics einterfaces.MetricsInterface) st table := db.AddTableWithName(bot{}, "Bots").SetKeys(false, "UserId") table.ColMap("UserId").SetMaxSize(26) table.ColMap("Description").SetMaxSize(1024) - table.ColMap("OwnerId").SetMaxSize(model.BOT_CREATOR_ID_MAX_RUNES) + table.ColMap("OwnerId").SetMaxSize(model.BotCreatorIdMaxRunes) } return us diff --git a/store/sqlstore/channel_member_history_store.go b/store/sqlstore/channel_member_history_store.go index 73f45cbe65..49c8431dee 100644 --- a/store/sqlstore/channel_member_history_store.go +++ b/store/sqlstore/channel_member_history_store.go @@ -212,7 +212,7 @@ func (s SqlChannelMemberHistoryStore) PermanentDeleteBatch(endTime int64, limit err error ) - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { var innerSelect string innerSelect, args, err = s.getQueryBuilder(). Select("ctid"). diff --git a/store/sqlstore/channel_store.go b/store/sqlstore/channel_store.go index 9e1898b97e..9258c74384 100644 --- a/store/sqlstore/channel_store.go +++ b/store/sqlstore/channel_store.go @@ -24,10 +24,10 @@ import ( ) const ( - AllChannelMembersForUserCacheSize = model.SESSION_CACHE_SIZE + AllChannelMembersForUserCacheSize = model.SessionCacheSize AllChannelMembersForUserCacheDuration = 15 * time.Minute // 15 mins - AllChannelMembersNotifyPropsForChannelCacheSize = model.SESSION_CACHE_SIZE + AllChannelMembersNotifyPropsForChannelCacheSize = model.SessionCacheSize AllChannelMembersNotifyPropsForChannelCacheDuration = 30 * time.Minute // 30 mins ChannelCacheDuration = 15 * time.Minute // 15 mins @@ -132,11 +132,11 @@ func getChannelRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuest // them from ExplicitRoles field. for _, role := range roles { switch role { - case model.CHANNEL_GUEST_ROLE_ID: + case model.ChannelGuestRoleId: result.schemeGuest = true - case model.CHANNEL_USER_ROLE_ID: + case model.ChannelUserRoleId: result.schemeUser = true - case model.CHANNEL_ADMIN_ROLE_ID: + case model.ChannelAdminRoleId: result.schemeAdmin = true default: result.explicitRoles = append(result.explicitRoles, role) @@ -153,7 +153,7 @@ func getChannelRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuest } else if defaultTeamGuestRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamGuestRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_GUEST_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelGuestRoleId) } } if result.schemeUser { @@ -162,7 +162,7 @@ func getChannelRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuest } else if defaultTeamUserRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamUserRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_USER_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelUserRoleId) } } if result.schemeAdmin { @@ -171,7 +171,7 @@ func getChannelRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuest } else if defaultTeamAdminRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamAdminRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_ADMIN_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelAdminRoleId) } } for _, impliedRole := range schemeImpliedRoles { @@ -288,7 +288,7 @@ func (db allChannelMember) Process() (string, string) { } else if db.TeamSchemeDefaultGuestRole.Valid && db.TeamSchemeDefaultGuestRole.String != "" { schemeImpliedRoles = append(schemeImpliedRoles, db.TeamSchemeDefaultGuestRole.String) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_GUEST_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelGuestRoleId) } } if db.SchemeUser.Valid && db.SchemeUser.Bool { @@ -297,7 +297,7 @@ func (db allChannelMember) Process() (string, string) { } else if db.TeamSchemeDefaultUserRole.Valid && db.TeamSchemeDefaultUserRole.String != "" { schemeImpliedRoles = append(schemeImpliedRoles, db.TeamSchemeDefaultUserRole.String) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_USER_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelUserRoleId) } } if db.SchemeAdmin.Valid && db.SchemeAdmin.Bool { @@ -306,7 +306,7 @@ func (db allChannelMember) Process() (string, string) { } else if db.TeamSchemeDefaultAdminRole.Valid && db.TeamSchemeDefaultAdminRole.String != "" { schemeImpliedRoles = append(schemeImpliedRoles, db.TeamSchemeDefaultAdminRole.String) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.CHANNEL_ADMIN_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.ChannelAdminRoleId) } } for _, impliedRole := range schemeImpliedRoles { @@ -353,7 +353,7 @@ var allChannelMembersNotifyPropsForChannelCache = cache.NewLRU(cache.LRUOptions{ Size: AllChannelMembersNotifyPropsForChannelCacheSize, }) var channelByNameCache = cache.NewLRU(cache.LRUOptions{ - Size: model.CHANNEL_CACHE_SIZE, + Size: model.ChannelCacheSize, }) func (s SqlChannelStore) ClearCaches() { @@ -425,7 +425,7 @@ func (s SqlChannelStore) createIndexesIfNotExists() { s.CreateIndexIfNotExists("idx_channels_create_at", "Channels", "CreateAt") s.CreateIndexIfNotExists("idx_channels_delete_at", "Channels", "DeleteAt") - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { s.CreateIndexIfNotExists("idx_channels_name_lower", "Channels", "lower(Name)") s.CreateIndexIfNotExists("idx_channels_displayname_lower", "Channels", "lower(DisplayName)") } @@ -436,7 +436,7 @@ func (s SqlChannelStore) createIndexesIfNotExists() { s.CreateIndexIfNotExists("idx_publicchannels_team_id", "PublicChannels", "TeamId") s.CreateIndexIfNotExists("idx_publicchannels_delete_at", "PublicChannels", "DeleteAt") - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { s.CreateIndexIfNotExists("idx_publicchannels_name_lower", "PublicChannels", "lower(Name)") s.CreateIndexIfNotExists("idx_publicchannels_displayname_lower", "PublicChannels", "lower(DisplayName)") } @@ -477,7 +477,7 @@ func (s SqlChannelStore) upsertPublicChannelT(transaction *gorp.Transaction, cha Purpose: channel.Purpose, } - if channel.Type != model.CHANNEL_OPEN { + if channel.Type != model.ChannelTypeOpen { if _, err := transaction.Delete(publicChannel); err != nil { return errors.Wrap(err, "failed to delete public channel") } @@ -495,7 +495,7 @@ func (s SqlChannelStore) upsertPublicChannelT(transaction *gorp.Transaction, cha "Purpose": publicChannel.Purpose, } var err error - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { _, err = transaction.Exec(` INSERT INTO PublicChannels(Id, DeleteAt, TeamId, DisplayName, Name, Header, Purpose) @@ -537,7 +537,7 @@ func (s SqlChannelStore) Save(channel *model.Channel, maxChannelsPerTeam int64) return nil, store.NewErrInvalidInput("Channel", "DeleteAt", channel.DeleteAt) } - if channel.Type == model.CHANNEL_DIRECT { + if channel.Type == model.ChannelTypeDirect { return nil, store.NewErrInvalidInput("Channel", "Type", channel.Type) } @@ -577,7 +577,7 @@ func (s SqlChannelStore) CreateDirectChannel(user *model.User, otherUser *model. channel.Name = model.GetDMNameFromIds(otherUser.Id, user.Id) channel.Header = "" - channel.Type = model.CHANNEL_DIRECT + channel.Type = model.ChannelTypeDirect channel.Shared = model.NewBool(user.IsRemote() || otherUser.IsRemote()) channel.CreatorId = user.Id @@ -602,7 +602,7 @@ func (s SqlChannelStore) SaveDirectChannel(directChannel *model.Channel, member1 return nil, store.NewErrInvalidInput("Channel", "DeleteAt", directChannel.DeleteAt) } - if directChannel.Type != model.CHANNEL_DIRECT { + if directChannel.Type != model.ChannelTypeDirect { return nil, store.NewErrInvalidInput("Channel", "Type", directChannel.Type) } @@ -649,7 +649,7 @@ func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *mo return nil, err // we just pass through the error as-is for now. } - if channel.Type != model.CHANNEL_DIRECT && channel.Type != model.CHANNEL_GROUP && maxChannelsPerTeam >= 0 { + if channel.Type != model.ChannelTypeDirect && channel.Type != model.ChannelTypeGroup && maxChannelsPerTeam >= 0 { if count, err := transaction.SelectInt("SELECT COUNT(0) FROM Channels WHERE TeamId = :TeamId AND DeleteAt = 0 AND (Type = 'O' OR Type = 'P')", map[string]interface{}{"TeamId": channel.TeamId}); err != nil { return nil, errors.Wrapf(err, "save_channel_count: teamId=%s", channel.TeamId) } else if count >= maxChannelsPerTeam { @@ -1043,7 +1043,7 @@ func (s SqlChannelStore) getAllChannelsQuery(opts store.ChannelSearchOpts, forCo query := s.getQueryBuilder(). Select(selectStr). From("Channels AS c"). - Where(sq.Eq{"c.Type": []string{model.CHANNEL_PRIVATE, model.CHANNEL_OPEN}}) + Where(sq.Eq{"c.Type": []string{model.ChannelTypePrivate, model.ChannelTypeOpen}}) if !forCount { query = query.Join("Teams ON Teams.Id = c.TeamId") @@ -1119,7 +1119,7 @@ func (s SqlChannelStore) GetPrivateChannelsForTeam(teamId string, offset int, li builder := s.getQueryBuilder(). Select("*"). From("Channels"). - Where(sq.Eq{"Type": model.CHANNEL_PRIVATE, "TeamId": teamId, "DeleteAt": 0}). + Where(sq.Eq{"Type": model.ChannelTypePrivate, "TeamId": teamId, "DeleteAt": 0}). OrderBy("DisplayName"). Limit(uint64(limit)). Offset(uint64(offset)) @@ -1907,7 +1907,7 @@ func (s SqlChannelStore) GetMemberCountsByGroup(ctx context.Context, channelID s manualTimezone := `LOCATE(',', Users.Timezone) + 19` manualTimezoneEnd := `LOCATE('useAutomaticTimezone', Users.Timezone) - 22 - LOCATE(',', Users.Timezone)` - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { autoTimezone = `POSITION(':' IN Users.Timezone) + 2` autoTimezoneEnd = `POSITION(',' IN Users.Timezone) - POSITION(':' IN Users.Timezone) - 3` manualTimezone = `POSITION(',' IN Users.Timezone) + 19` @@ -2096,7 +2096,7 @@ func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string, query := `SELECT Id, LastPostAt, TotalMsgCount, TotalMsgCountRoot FROM Channels WHERE Id IN ` + keys // TODO: use a CTE for mysql too when version 8 becomes the minimum supported version. - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = `WITH c AS ( ` + query + `), updated AS ( UPDATE @@ -2125,7 +2125,7 @@ func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string, } times := map[string]int64{} - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { for _, t := range lastPostAtTimes { times[t.Id] = t.LastPostAt } @@ -2181,16 +2181,16 @@ func (s SqlChannelStore) UpdateLastViewedAt(channelIds []string, userId string, func (s SqlChannelStore) CountPostsAfter(channelId string, timestamp int64, userId string) (int, int, error) { joinLeavePostTypes := []string{ // These types correspond to the ones checked by Post.IsJoinLeaveMessage - model.POST_JOIN_LEAVE, - model.POST_ADD_REMOVE, - model.POST_JOIN_CHANNEL, - model.POST_LEAVE_CHANNEL, - model.POST_JOIN_TEAM, - model.POST_LEAVE_TEAM, - model.POST_ADD_TO_CHANNEL, - model.POST_REMOVE_FROM_CHANNEL, - model.POST_ADD_TO_TEAM, - model.POST_REMOVE_FROM_TEAM, + model.PostTypeJoinLeave, + model.PostTypeAddRemove, + model.PostTypeJoinChannel, + model.PostTypeLeaveChannel, + model.PostTypeJoinTeam, + model.PostTypeLeaveTeam, + model.PostTypeAddToChannel, + model.PostTypeRemoveFromChannel, + model.PostTypeAddToTeam, + model.PostTypeRemoveFromTeam, } query := s.getQueryBuilder().Select("count(*)").From("Posts").Where(sq.Eq{"ChannelId": channelId}).Where(sq.Gt{"CreateAt": timestamp}).Where(sq.NotEq{"Type": joinLeavePostTypes}).Where(sq.Eq{"DeleteAt": 0}) @@ -2444,7 +2444,7 @@ func (s SqlChannelStore) AutocompleteInTeam(teamId string, term string, includeD Channels.TeamId = :TeamId ` + deleteFilter + ` %v - LIMIT ` + strconv.Itoa(model.CHANNEL_SEARCH_DEFAULT_LIMIT) + LIMIT ` + strconv.Itoa(model.ChannelSearchDefaultLimit) var channels model.ChannelList @@ -2764,11 +2764,11 @@ func (s SqlChannelStore) channelSearchQuery(opts *store.ChannelSearchOpts) sq.Se if opts.Public && !opts.Private { query = query.InnerJoin("PublicChannels ON c.Id = PublicChannels.Id") } else if opts.Private && !opts.Public { - query = query.Where(sq.Eq{"c.Type": model.CHANNEL_PRIVATE}) + query = query.Where(sq.Eq{"c.Type": model.ChannelTypePrivate}) } else { query = query.Where(sq.Or{ - sq.Eq{"c.Type": model.CHANNEL_OPEN}, - sq.Eq{"c.Type": model.CHANNEL_PRIVATE}, + sq.Eq{"c.Type": model.ChannelTypeOpen}, + sq.Eq{"c.Type": model.ChannelTypePrivate}, }) } @@ -2848,7 +2848,7 @@ func (s SqlChannelStore) buildLIKEClause(term string, searchColumns string) (lik // Prepare the LIKE portion of the query. var searchFields []string for _, field := range strings.Split(searchColumns, ", ") { - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { searchFields = append(searchFields, fmt.Sprintf("lower(%s) LIKE lower(%s) escape '*'", field, ":LikeTerm")) } else { searchFields = append(searchFields, fmt.Sprintf("%s LIKE %s escape '*'", field, ":LikeTerm")) @@ -2870,7 +2870,7 @@ func (s SqlChannelStore) buildFulltextClause(term string, searchColumns string) } // Prepare the FULLTEXT portion of the query. - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { fulltextTerm = strings.Replace(fulltextTerm, "|", "", -1) splitTerm := strings.Fields(fulltextTerm) @@ -2885,7 +2885,7 @@ func (s SqlChannelStore) buildFulltextClause(term string, searchColumns string) fulltextTerm = strings.Join(splitTerm, " ") fulltextClause = fmt.Sprintf("((to_tsvector('english', %s)) @@ to_tsquery('english', :FulltextTerm))", convertMySQLFullTextColumnsToPostgres(searchColumns)) - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { splitTerm := strings.Fields(fulltextTerm) for i, t := range strings.Fields(fulltextTerm) { splitTerm[i] = "+" + t + "*" @@ -2958,7 +2958,7 @@ func (s SqlChannelStore) getSearchGroupChannelsQuery(userId, term string, isPost HAVING %s LIMIT - ` + strconv.Itoa(model.CHANNEL_SEARCH_DEFAULT_LIMIT) + ` + ` + strconv.Itoa(model.ChannelSearchDefaultLimit) + ` )` } else { baseLikeClause = "GROUP_CONCAT(u.Username SEPARATOR ', ') LIKE %s" @@ -2990,7 +2990,7 @@ func (s SqlChannelStore) getSearchGroupChannelsQuery(userId, term string, isPost HAVING %s LIMIT - ` + strconv.Itoa(model.CHANNEL_SEARCH_DEFAULT_LIMIT) + ` + strconv.Itoa(model.ChannelSearchDefaultLimit) } var likeClauses []string @@ -3009,7 +3009,7 @@ func (s SqlChannelStore) getSearchGroupChannelsQuery(userId, term string, isPost } func (s SqlChannelStore) SearchGroupChannels(userId, term string) (*model.ChannelList, error) { - isPostgreSQL := s.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := s.DriverName() == model.DatabaseDriverPostgres queryString, args := s.getSearchGroupChannelsQuery(userId, term, isPostgreSQL) var groupChannels model.ChannelList @@ -3091,11 +3091,11 @@ func (s SqlChannelStore) MigrateChannelMembers(fromChannelId string, fromUserId member.SchemeGuest = sql.NullBool{Bool: false, Valid: true} } for _, role := range roles { - if role == model.CHANNEL_ADMIN_ROLE_ID { + if role == model.ChannelAdminRoleId { member.SchemeAdmin = sql.NullBool{Bool: true, Valid: true} - } else if role == model.CHANNEL_USER_ROLE_ID { + } else if role == model.ChannelUserRoleId { member.SchemeUser = sql.NullBool{Bool: true, Valid: true} - } else if role == model.CHANNEL_GUEST_ROLE_ID { + } else if role == model.ChannelGuestRoleId { member.SchemeGuest = sql.NullBool{Bool: true, Valid: true} } else { newRoles = append(newRoles, role) diff --git a/store/sqlstore/channel_store_categories.go b/store/sqlstore/channel_store_categories.go index 1501e840b0..982defd5ef 100644 --- a/store/sqlstore/channel_store_categories.go +++ b/store/sqlstore/channel_store_categories.go @@ -157,7 +157,7 @@ func (s SqlChannelStore) migrateFavoritesToSidebarT(transaction *gorp.Transactio Join("ChannelMembers on Preferences.Name = ChannelMembers.ChannelId and Preferences.UserId = ChannelMembers.UserId"). Where(sq.Eq{ "Preferences.UserId": userId, - "Preferences.Category": model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + "Preferences.Category": model.PreferenceCategoryFavoriteChannel, "Preferences.Value": "true", }). Where(sq.Or{ @@ -203,7 +203,7 @@ func (s SqlChannelStore) MigrateFavoritesToSidebarChannels(lastUserId string, ru Select("Preferences.UserId", "Preferences.Name AS ChannelId", "SidebarCategories.Id AS CategoryId"). From("Preferences"). Where(sq.And{ - sq.Eq{"Preferences.Category": model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL}, + sq.Eq{"Preferences.Category": model.PreferenceCategoryFavoriteChannel}, sq.NotEq{"Preferences.Value": "false"}, sq.NotEq{"SidebarCategories.Id": nil}, sq.Gt{"Preferences.UserId": lastUserId}, @@ -288,7 +288,7 @@ func (s SqlChannelStore) CreateSidebarCategory(userId, teamId string, newCategor // Remove any channels from their previous categories and add them to the new one var deleteQuery string - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { deleteQuery = ` DELETE SidebarChannels @@ -378,11 +378,11 @@ func (s SqlChannelStore) completePopulatingCategoryChannelsT(db dbSelecter, cate var channelTypeFilter sq.Sqlizer if category.Type == model.SidebarCategoryDirectMessages { // any DM/GM channels that aren't in any category should be returned as part of the Direct Messages category - channelTypeFilter = sq.Eq{"Channels.Type": []string{model.CHANNEL_DIRECT, model.CHANNEL_GROUP}} + channelTypeFilter = sq.Eq{"Channels.Type": []string{model.ChannelTypeDirect, model.ChannelTypeGroup}} } else if category.Type == model.SidebarCategoryChannels { // any public/private channels that are on the current team and aren't in any category should be returned as part of the Channels category channelTypeFilter = sq.And{ - sq.Eq{"Channels.Type": []string{model.CHANNEL_OPEN, model.CHANNEL_PRIVATE}}, + sq.Eq{"Channels.Type": []string{model.ChannelTypeOpen, model.ChannelTypePrivate}}, sq.Eq{"Channels.TeamId": category.TeamId}, } } @@ -705,7 +705,7 @@ func (s SqlChannelStore) UpdateSidebarCategories(userId, teamId string, categori sq.Eq{ "UserId": userId, "Name": originalCategory.Channels, - "Category": model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + "Category": model.PreferenceCategoryFavoriteChannel, }, ).ToSql() @@ -720,7 +720,7 @@ func (s SqlChannelStore) UpdateSidebarCategories(userId, teamId string, categori if err = s.Preference().(*SqlPreferenceStore).save(transaction, &model.Preference{ Name: channelID, UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Value: "true", }); err != nil { return nil, nil, errors.Wrap(err, "failed to save Preference") @@ -732,7 +732,7 @@ func (s SqlChannelStore) UpdateSidebarCategories(userId, teamId string, categori sq.Eq{ "UserId": userId, "Name": category.Channels, - "Category": model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + "Category": model.PreferenceCategoryFavoriteChannel, }, ).ToSql() if nErr != nil { @@ -777,7 +777,7 @@ func (s SqlChannelStore) UpdateSidebarChannelsByPreferences(preferences *model.P for _, preference := range *preferences { preference := preference - if preference.Category != model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL { + if preference.Category != model.PreferenceCategoryFavoriteChannel { continue } @@ -801,7 +801,7 @@ func (s SqlChannelStore) UpdateSidebarChannelsByPreferences(preferences *model.P } func (s SqlChannelStore) removeSidebarEntriesForPreferenceT(transaction *gorp.Transaction, preference *model.Preference) error { - if preference.Category != model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL { + if preference.Category != model.PreferenceCategoryFavoriteChannel { return nil } @@ -813,7 +813,7 @@ func (s SqlChannelStore) removeSidebarEntriesForPreferenceT(transaction *gorp.Tr "CategoryType": model.SidebarCategoryFavorites, } var query string - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { query = ` DELETE SidebarChannels @@ -846,7 +846,7 @@ func (s SqlChannelStore) removeSidebarEntriesForPreferenceT(transaction *gorp.Tr } func (s SqlChannelStore) addChannelToFavoritesCategoryT(transaction *gorp.Transaction, preference *model.Preference) error { - if preference.Category != model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL { + if preference.Category != model.PreferenceCategoryFavoriteChannel { return nil } @@ -928,7 +928,7 @@ func (s SqlChannelStore) DeleteSidebarChannelsByPreferences(preferences *model.P for _, preference := range *preferences { preference := preference - if preference.Category != model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL { + if preference.Category != model.PreferenceCategoryFavoriteChannel { continue } @@ -961,7 +961,7 @@ func (s SqlChannelStore) ClearSidebarOnTeamLeave(userId, teamId string) error { } var deleteQuery string - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { deleteQuery = "DELETE SidebarChannels FROM SidebarChannels LEFT JOIN SidebarCategories ON SidebarCategories.Id = SidebarChannels.CategoryId WHERE SidebarCategories.TeamId=:TeamId AND SidebarCategories.UserId=:UserId" } else { deleteQuery = ` diff --git a/store/sqlstore/cluster_discovery_store.go b/store/sqlstore/cluster_discovery_store.go index 0fcc33ef14..23b86c1b97 100644 --- a/store/sqlstore/cluster_discovery_store.go +++ b/store/sqlstore/cluster_discovery_store.go @@ -92,7 +92,7 @@ func (s sqlClusterDiscoveryStore) GetAll(ClusterDiscoveryType, clusterName strin From("ClusterDiscovery"). Where(sq.Eq{"Type": ClusterDiscoveryType}). Where(sq.Eq{"ClusterName": clusterName}). - Where(sq.Gt{"LastPingAt": model.GetMillis() - model.CDS_OFFLINE_AFTER_MILLIS}) + Where(sq.Gt{"LastPingAt": model.GetMillis() - model.CDSOfflineAfterMillis}) queryString, args, err := query.ToSql() if err != nil { @@ -128,7 +128,7 @@ func (s sqlClusterDiscoveryStore) SetLastPingAt(ClusterDiscovery *model.ClusterD func (s sqlClusterDiscoveryStore) Cleanup() error { query := s.getQueryBuilder(). Delete("ClusterDiscovery"). - Where(sq.Lt{"LastPingAt": model.GetMillis() - model.CDS_OFFLINE_AFTER_MILLIS}) + Where(sq.Lt{"LastPingAt": model.GetMillis() - model.CDSOfflineAfterMillis}) queryString, args, err := query.ToSql() if err != nil { diff --git a/store/sqlstore/command_webhook_store.go b/store/sqlstore/command_webhook_store.go index 18d7ff17db..e1eac526ec 100644 --- a/store/sqlstore/command_webhook_store.go +++ b/store/sqlstore/command_webhook_store.go @@ -58,7 +58,7 @@ func (s SqlCommandWebhookStore) Save(webhook *model.CommandWebhook) (*model.Comm func (s SqlCommandWebhookStore) Get(id string) (*model.CommandWebhook, error) { var webhook model.CommandWebhook - exptime := model.GetMillis() - model.COMMAND_WEBHOOK_LIFETIME + exptime := model.GetMillis() - model.CommandWebhookLifetime query := s.getQueryBuilder(). Select("*"). @@ -104,7 +104,7 @@ func (s SqlCommandWebhookStore) TryUse(id string, limit int) error { func (s SqlCommandWebhookStore) Cleanup() { mlog.Debug("Cleaning up command webhook store.") - exptime := model.GetMillis() - model.COMMAND_WEBHOOK_LIFETIME + exptime := model.GetMillis() - model.CommandWebhookLifetime query := s.getQueryBuilder(). Delete("CommandWebhooks"). diff --git a/store/sqlstore/emoji_store.go b/store/sqlstore/emoji_store.go index c8d244ef5c..7f47aa1acc 100644 --- a/store/sqlstore/emoji_store.go +++ b/store/sqlstore/emoji_store.go @@ -88,7 +88,7 @@ func (es SqlEmojiStore) GetList(offset, limit int, sort string) ([]*model.Emoji, query := "SELECT * FROM Emoji WHERE DeleteAt = 0" - if sort == model.EMOJI_SORT_BY_NAME { + if sort == model.EmojiSortByName { query += " ORDER BY Name" } diff --git a/store/sqlstore/file_info_store.go b/store/sqlstore/file_info_store.go index d6b909606e..9bc856abb2 100644 --- a/store/sqlstore/file_info_store.go +++ b/store/sqlstore/file_info_store.go @@ -81,7 +81,7 @@ func (fs SqlFileInfoStore) createIndexesIfNotExists() { fs.CreateIndexIfNotExists("idx_fileinfo_postid_at", "FileInfo", "PostId") fs.CreateIndexIfNotExists("idx_fileinfo_extension_at", "FileInfo", "Extension") fs.CreateFullTextIndexIfNotExists("idx_fileinfo_name_txt", "FileInfo", "Name") - if fs.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if fs.DriverName() == model.DatabaseDriverPostgres { fs.CreateFullTextFuncIndexIfNotExists("idx_fileinfo_name_splitted", "FileInfo", "Translate(Name, '.,-', ' ')") } fs.CreateFullTextIndexIfNotExists("idx_fileinfo_content_txt", "FileInfo", "Content") @@ -210,7 +210,7 @@ func (fs SqlFileInfoStore) GetWithOptions(page, perPage int, opt *model.GetFileI } if opt.SortBy == "" { - opt.SortBy = model.FILEINFO_SORT_BY_CREATED + opt.SortBy = model.FileinfoSortByCreated } sortDirection := "ASC" if opt.SortDescending { @@ -218,9 +218,9 @@ func (fs SqlFileInfoStore) GetWithOptions(page, perPage int, opt *model.GetFileI } switch opt.SortBy { - case model.FILEINFO_SORT_BY_CREATED: + case model.FileinfoSortByCreated: query = query.OrderBy("FileInfo.CreateAt " + sortDirection) - case model.FILEINFO_SORT_BY_SIZE: + case model.FileinfoSortBySize: query = query.OrderBy("FileInfo.Size " + sortDirection) default: return nil, store.NewErrInvalidInput("FileInfo", "", opt.SortBy) @@ -528,7 +528,7 @@ func (fs SqlFileInfoStore) Search(paramsList []*model.SearchParams, userId, team if terms == "" && excludedTerms == "" { // we've already confirmed that we have a channel or user to search for - } else if fs.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if fs.DriverName() == model.DatabaseDriverPostgres { // Parse text for wildcards if wildcard, err := regexp.Compile(`\*($| )`); err == nil { terms = wildcard.ReplaceAllLiteralString(terms, ":* ") @@ -552,7 +552,7 @@ func (fs SqlFileInfoStore) Search(paramsList []*model.SearchParams, userId, team sq.Expr("to_tsvector('english', Translate(FileInfo.Name, '.,-', ' ')) @@ to_tsquery('english', ?)", queryTerms), sq.Expr("to_tsvector('english', FileInfo.Content) @@ to_tsquery('english', ?)", queryTerms), }) - } else if fs.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if fs.DriverName() == model.DatabaseDriverMysql { var err error terms, err = removeMysqlStopWordsFromTerms(terms) if err != nil { diff --git a/store/sqlstore/group_store.go b/store/sqlstore/group_store.go index dc931af382..4621d60737 100644 --- a/store/sqlstore/group_store.go +++ b/store/sqlstore/group_store.go @@ -411,9 +411,9 @@ func (s *SqlGroupStore) UpsertMember(groupID string, userID string) (*model.Grou Columns("GroupId", "UserId", "CreateAt", "DeleteAt"). Values(member.GroupId, member.UserId, member.CreateAt, member.DeleteAt) - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { query = query.SuffixExpr(sq.Expr("ON DUPLICATE KEY UPDATE CreateAt = ?, DeleteAt = ?", member.CreateAt, member.DeleteAt)) - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { query = query.SuffixExpr(sq.Expr("ON CONFLICT (groupid, userid) DO UPDATE SET CreateAt = ?, DeleteAt = ?", member.CreateAt, member.DeleteAt)) } @@ -1010,7 +1010,7 @@ func (s *SqlGroupStore) groupsBySyncableBaseQuery(st model.GroupSyncableType, t if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { operatorKeyword = "LIKE" } query = query.Where(fmt.Sprintf("(ug.Name %[1]s ? OR ug.DisplayName %[1]s ?)", operatorKeyword), pattern, pattern) @@ -1075,7 +1075,7 @@ func (s *SqlGroupStore) getGroupsAssociatedToChannelsByTeam(teamID string, opts if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { operatorKeyword = "LIKE" } query = query.Where(fmt.Sprintf("(ug.Name %[1]s ? OR ug.DisplayName %[1]s ?)", operatorKeyword), pattern, pattern) @@ -1195,7 +1195,7 @@ func (s *SqlGroupStore) GetGroups(page, perPage int, opts model.GroupSearchOpts) if opts.Q != "" { pattern := fmt.Sprintf("%%%s%%", sanitizeSearchTerm(opts.Q, "\\")) operatorKeyword := "ILIKE" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { operatorKeyword = "LIKE" } groupsQuery = groupsQuery.Where(fmt.Sprintf("(g.Name %[1]s ? OR g.DisplayName %[1]s ?)", operatorKeyword), pattern, pattern) @@ -1284,7 +1284,7 @@ func (s *SqlGroupStore) teamMembersMinusGroupMembersQuery(teamID string, groupID selectStr = "count(DISTINCT Users.Id)" } else { tmpl := "Users.*, coalesce(TeamMembers.SchemeGuest, false), TeamMembers.SchemeAdmin, TeamMembers.SchemeUser, %s AS GroupIDs" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { selectStr = fmt.Sprintf(tmpl, "group_concat(UserGroups.Id)") } else { selectStr = fmt.Sprintf(tmpl, "string_agg(UserGroups.Id, ',')") @@ -1362,7 +1362,7 @@ func (s *SqlGroupStore) channelMembersMinusGroupMembersQuery(channelID string, g selectStr = "count(DISTINCT Users.Id)" } else { tmpl := "Users.*, coalesce(ChannelMembers.SchemeGuest, false), ChannelMembers.SchemeAdmin, ChannelMembers.SchemeUser, %s AS GroupIDs" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { selectStr = fmt.Sprintf(tmpl, "group_concat(UserGroups.Id)") } else { selectStr = fmt.Sprintf(tmpl, "string_agg(UserGroups.Id, ',')") diff --git a/store/sqlstore/integrity.go b/store/sqlstore/integrity.go index 26904c0940..0ea4004a8f 100644 --- a/store/sqlstore/integrity.go +++ b/store/sqlstore/integrity.go @@ -215,7 +215,7 @@ func checkTeamsChannelsIntegrity(ss *SqlStore) model.IntegrityCheckResult { parentIdAttr: "TeamId", childName: "Channels", childIdAttr: "Id", - filter: sq.NotEq{"CT.Type": []string{model.CHANNEL_DIRECT, model.CHANNEL_GROUP}}, + filter: sq.NotEq{"CT.Type": []string{model.ChannelTypeDirect, model.ChannelTypeGroup}}, }) res2 := checkParentChildIntegrity(ss, relationalCheckConfig{ parentName: "Teams", @@ -223,7 +223,7 @@ func checkTeamsChannelsIntegrity(ss *SqlStore) model.IntegrityCheckResult { childName: "Channels", childIdAttr: "Id", canParentIdBeEmpty: true, - filter: sq.Eq{"CT.Type": []string{model.CHANNEL_DIRECT, model.CHANNEL_GROUP}}, + filter: sq.Eq{"CT.Type": []string{model.ChannelTypeDirect, model.ChannelTypeGroup}}, }) data1 := res1.Data.(model.RelationalIntegrityCheckData) data2 := res2.Data.(model.RelationalIntegrityCheckData) diff --git a/store/sqlstore/integrity_test.go b/store/sqlstore/integrity_test.go index bd21da95b0..96c8fc9c76 100644 --- a/store/sqlstore/integrity_test.go +++ b/store/sqlstore/integrity_test.go @@ -29,7 +29,7 @@ func createChannel(ss store.Store, teamId, creatorId string) *model.Channel { m.CreatorId = creatorId m.DisplayName = "Name" m.Name = "zz" + model.NewId() + "b" - m.Type = model.CHANNEL_OPEN + m.Type = model.ChannelTypeOpen c, _ := ss.Channel().Save(&m, -1) return c } @@ -41,7 +41,7 @@ func createChannelWithSchemeId(ss store.Store, schemeId *string) *model.Channel m.CreatorId = model.NewId() m.DisplayName = "Name" m.Name = "zz" + model.NewId() + "b" - m.Type = model.CHANNEL_OPEN + m.Type = model.ChannelTypeOpen c, _ := ss.Channel().Save(&m, -1) return c } @@ -49,7 +49,7 @@ func createChannelWithSchemeId(ss store.Store, schemeId *string) *model.Channel func createCommand(ss store.Store, userId, teamId string) *model.Command { m := model.Command{} m.CreatorId = userId - m.Method = model.COMMAND_METHOD_POST + m.Method = model.CommandMethodPost m.TeamId = teamId m.URL = "http://nowhere.com/" m.Trigger = "trigger" @@ -99,10 +99,10 @@ func createCompliance(ss store.Store, userId string) *model.Compliance { m := model.Compliance{} m.UserId = userId m.Desc = "Audit" - m.Status = model.COMPLIANCE_STATUS_FAILED + m.Status = model.ComplianceStatusFailed m.StartAt = model.GetMillis() - 1 m.EndAt = model.GetMillis() + 1 - m.Type = model.COMPLIANCE_TYPE_ADHOC + m.Type = model.ComplianceTypeAdhoc c, _ := ss.Compliance().Save(&m) return c } @@ -200,7 +200,7 @@ func createPreferences(ss store.Store, userId string) *model.Preferences { { UserId: userId, Name: model.NewId(), - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Value: "somevalue", }, } @@ -220,54 +220,54 @@ func createReaction(ss store.Store, userId, postId string) *model.Reaction { func createDefaultRoles(ss store.Store) { ss.Role().Save(&model.Role{ - Name: model.TEAM_ADMIN_ROLE_ID, - DisplayName: model.TEAM_ADMIN_ROLE_ID, + Name: model.TeamAdminRoleId, + DisplayName: model.TeamAdminRoleId, Permissions: []string{ - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + model.PermissionDeleteOthersPosts.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.TEAM_USER_ROLE_ID, - DisplayName: model.TEAM_USER_ROLE_ID, + Name: model.TeamUserRoleId, + DisplayName: model.TeamUserRoleId, Permissions: []string{ - model.PERMISSION_VIEW_TEAM.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + model.PermissionViewTeam.Id, + model.PermissionAddUserToTeam.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.TEAM_GUEST_ROLE_ID, - DisplayName: model.TEAM_GUEST_ROLE_ID, + Name: model.TeamGuestRoleId, + DisplayName: model.TeamGuestRoleId, Permissions: []string{ - model.PERMISSION_VIEW_TEAM.Id, + model.PermissionViewTeam.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_ADMIN_ROLE_ID, - DisplayName: model.CHANNEL_ADMIN_ROLE_ID, + Name: model.ChannelAdminRoleId, + DisplayName: model.ChannelAdminRoleId, Permissions: []string{ - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + model.PermissionManagePublicChannelMembers.Id, + model.PermissionManagePrivateChannelMembers.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_USER_ROLE_ID, - DisplayName: model.CHANNEL_USER_ROLE_ID, + Name: model.ChannelUserRoleId, + DisplayName: model.ChannelUserRoleId, Permissions: []string{ - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_CREATE_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionCreatePost.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_GUEST_ROLE_ID, - DisplayName: model.CHANNEL_GUEST_ROLE_ID, + Name: model.ChannelGuestRoleId, + DisplayName: model.ChannelGuestRoleId, Permissions: []string{ - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_CREATE_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionCreatePost.Id, }, }) } @@ -277,7 +277,7 @@ func createScheme(ss store.Store) *model.Scheme { m.DisplayName = model.NewId() m.Name = model.NewId() m.Description = model.NewId() - m.Scope = model.SCHEME_SCOPE_CHANNEL + m.Scope = model.SchemeScopeChannel s, _ := ss.Scheme().Save(&m) return s } @@ -292,7 +292,7 @@ func createSession(ss store.Store, userId string) *model.Session { func createStatus(ss store.Store, userId string) *model.Status { m := model.Status{} m.UserId = userId - m.Status = model.STATUS_ONLINE + m.Status = model.StatusOnline ss.Status().SaveOrUpdate(&m) return &m } @@ -300,7 +300,7 @@ func createStatus(ss store.Store, userId string) *model.Status { func createTeam(ss store.Store) *model.Team { m := model.Team{} m.DisplayName = "DisplayName" - m.Type = model.TEAM_OPEN + m.Type = model.TeamOpen m.Email = "test@example.com" m.Name = "z-z-z" + model.NewRandomTeamName() + "b" t, _ := ss.Team().Save(&m) @@ -319,7 +319,7 @@ func createTeamWithSchemeId(ss store.Store, schemeId *string) *model.Team { m := model.Team{} m.SchemeId = schemeId m.DisplayName = "DisplayName" - m.Type = model.TEAM_OPEN + m.Type = model.TeamOpen m.Email = "test@example.com" m.Name = "z-z-z" + model.NewId() + "b" t, _ := ss.Team().Save(&m) diff --git a/store/sqlstore/job_store.go b/store/sqlstore/job_store.go index 6ef7b32022..c64a786919 100644 --- a/store/sqlstore/job_store.go +++ b/store/sqlstore/job_store.go @@ -97,7 +97,7 @@ func (jss SqlJobStore) UpdateStatusOptimistically(id string, currentStatus strin Set("Status", newStatus). Where(sq.Eq{"Id": id, "Status": currentStatus}) - if newStatus == model.JOB_STATUS_IN_PROGRESS { + if newStatus == model.JobStatusInProgress { builder = builder.Set("StartAt", model.GetMillis()) } query, args, err := builder.ToSql() diff --git a/store/sqlstore/link_metadata_store.go b/store/sqlstore/link_metadata_store.go index 8e1bd455b1..5e8f2ffcfb 100644 --- a/store/sqlstore/link_metadata_store.go +++ b/store/sqlstore/link_metadata_store.go @@ -31,7 +31,7 @@ func newSqlLinkMetadataStore(sqlStore *SqlStore) store.LinkMetadataStore { } func (s SqlLinkMetadataStore) createIndexesIfNotExists() { - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { s.CreateCompositeIndexIfNotExists("idx_link_metadata_url_timestamp", "LinkMetadata", []string{"URL(512)", "Timestamp"}) } else { s.CreateCompositeIndexIfNotExists("idx_link_metadata_url_timestamp", "LinkMetadata", []string{"URL", "Timestamp"}) diff --git a/store/sqlstore/oauth_store.go b/store/sqlstore/oauth_store.go index 7a1157ff64..e5858520ee 100644 --- a/store/sqlstore/oauth_store.go +++ b/store/sqlstore/oauth_store.go @@ -296,9 +296,9 @@ func (as SqlOAuthStore) deleteApp(transaction *gorp.Transaction, clientId string func (as SqlOAuthStore) deleteOAuthAppSessions(transaction *gorp.Transaction, clientId string) error { query := "" - if as.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if as.DriverName() == model.DatabaseDriverPostgres { query = "DELETE FROM Sessions s USING OAuthAccessData o WHERE o.Token = s.Token AND o.ClientId = :Id" - } else if as.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if as.DriverName() == model.DatabaseDriverMysql { query = "DELETE s.* FROM Sessions s INNER JOIN OAuthAccessData o ON o.Token = s.Token WHERE o.ClientId = :Id" } @@ -323,7 +323,7 @@ func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId Preferences WHERE Category = :Category - AND Name = :Name`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, "Name": clientId}); err != nil { + AND Name = :Name`, map[string]interface{}{"Category": model.PreferenceCategoryAuthorizedOAuthApp, "Name": clientId}); err != nil { return errors.Wrapf(err, "failed to delete Preferences with name=%s", clientId) } diff --git a/store/sqlstore/plugin_store.go b/store/sqlstore/plugin_store.go index b8767e32ef..660e94b546 100644 --- a/store/sqlstore/plugin_store.go +++ b/store/sqlstore/plugin_store.go @@ -58,9 +58,9 @@ func (ps SqlPluginStore) SaveOrUpdate(kv *model.PluginKeyValue) (*model.PluginKe Insert("PluginKeyValueStore"). Columns("PluginId", "PKey", "PValue", "ExpireAt"). Values(kv.PluginId, kv.Key, kv.Value, kv.ExpireAt) - if ps.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ps.DriverName() == model.DatabaseDriverPostgres { query = query.SuffixExpr(sq.Expr("ON CONFLICT (pluginid, pkey) DO UPDATE SET PValue = ?, ExpireAt = ?", kv.Value, kv.ExpireAt)) - } else if ps.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ps.DriverName() == model.DatabaseDriverMysql { query = query.SuffixExpr(sq.Expr("ON DUPLICATE KEY UPDATE PValue = ?, ExpireAt = ?", kv.Value, kv.ExpireAt)) } @@ -144,7 +144,7 @@ func (ps SqlPluginStore) CompareAndSet(kv *model.PluginKeyValue, oldValue []byte // Failed to update return false, errors.Wrap(err, "unable to get rows affected") } else if rowsAffected == 0 { - if ps.DriverName() == model.DATABASE_DRIVER_MYSQL && bytes.Equal(oldValue, kv.Value) { + if ps.DriverName() == model.DatabaseDriverMysql && bytes.Equal(oldValue, kv.Value) { // ROW_COUNT on MySQL is zero even if the row existed but no changes to the row were required. // Check if the row exists with the required value to distinguish this case. Strictly speaking, // this isn't a good use of CompareAndSet anyway, since there's no corresponding guarantee of diff --git a/store/sqlstore/post_store.go b/store/sqlstore/post_store.go index 9d4333b712..ab9cdded4c 100644 --- a/store/sqlstore/post_store.go +++ b/store/sqlstore/post_store.go @@ -132,7 +132,7 @@ func newSqlPostStore(sqlStore *SqlStore, metrics einterfaces.MetricsInterface) s s := &SqlPostStore{ SqlStore: sqlStore, metrics: metrics, - maxPostSizeCached: model.POST_MESSAGE_MAX_RUNES_V1, + maxPostSizeCached: model.PostMessageMaxRunesV1, } for _, db := range sqlStore.GetAllConns() { @@ -143,11 +143,11 @@ func newSqlPostStore(sqlStore *SqlStore, metrics einterfaces.MetricsInterface) s table.ColMap("RootId").SetMaxSize(26) table.ColMap("ParentId").SetMaxSize(26) table.ColMap("OriginalId").SetMaxSize(26) - table.ColMap("Message").SetMaxSize(model.POST_MESSAGE_MAX_BYTES_V2) + table.ColMap("Message").SetMaxSize(model.PostMessageMaxBytesV2) table.ColMap("Type").SetMaxSize(26) table.ColMap("Hashtags").SetMaxSize(1000) table.ColMap("Props").SetMaxSize(8000) - table.ColMap("Filenames").SetMaxSize(model.POST_FILENAMES_MAX_RUNES) + table.ColMap("Filenames").SetMaxSize(model.PostFilenamesMaxRunes) table.ColMap("FileIds").SetMaxSize(300) table.ColMap("RemoteId").SetMaxSize(26) } @@ -418,7 +418,7 @@ func (s *SqlPostStore) GetFlaggedPosts(userId string, offset int, limit int) (*m pl := model.NewPostList() var posts []*model.Post - if _, err := s.GetReplica().Select(&posts, "SELECT *, (SELECT count(Posts.Id) FROM Posts WHERE Posts.RootId = (CASE WHEN p.RootId = '' THEN p.Id ELSE p.RootId END) AND Posts.DeleteAt = 0) as ReplyCount FROM Posts p WHERE Id IN (SELECT Name FROM Preferences WHERE UserId = :UserId AND Category = :Category) AND DeleteAt = 0 ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset", map[string]interface{}{"UserId": userId, "Category": model.PREFERENCE_CATEGORY_FLAGGED_POST, "Offset": offset, "Limit": limit}); err != nil { + if _, err := s.GetReplica().Select(&posts, "SELECT *, (SELECT count(Posts.Id) FROM Posts WHERE Posts.RootId = (CASE WHEN p.RootId = '' THEN p.Id ELSE p.RootId END) AND Posts.DeleteAt = 0) as ReplyCount FROM Posts p WHERE Id IN (SELECT Name FROM Preferences WHERE UserId = :UserId AND Category = :Category) AND DeleteAt = 0 ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset", map[string]interface{}{"UserId": userId, "Category": model.PreferenceCategoryFlaggedPost, "Offset": offset, "Limit": limit}); err != nil { return nil, errors.Wrap(err, "failed to find Posts") } @@ -461,7 +461,7 @@ func (s *SqlPostStore) GetFlaggedPostsForTeam(userId, teamId string, offset int, ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset` - if _, err := s.GetReplica().Select(&posts, query, map[string]interface{}{"UserId": userId, "Category": model.PREFERENCE_CATEGORY_FLAGGED_POST, "Offset": offset, "Limit": limit, "TeamId": teamId}); err != nil { + if _, err := s.GetReplica().Select(&posts, query, map[string]interface{}{"UserId": userId, "Category": model.PreferenceCategoryFlaggedPost, "Offset": offset, "Limit": limit, "TeamId": teamId}); err != nil { return nil, errors.Wrap(err, "failed to find Posts") } @@ -488,7 +488,7 @@ func (s *SqlPostStore) GetFlaggedPostsForChannel(userId, channelId string, offse ORDER BY CreateAt DESC LIMIT :Limit OFFSET :Offset` - if _, err := s.GetReplica().Select(&posts, query, map[string]interface{}{"UserId": userId, "Category": model.PREFERENCE_CATEGORY_FLAGGED_POST, "ChannelId": channelId, "Offset": offset, "Limit": limit}); err != nil { + if _, err := s.GetReplica().Select(&posts, query, map[string]interface{}{"UserId": userId, "Category": model.PreferenceCategoryFlaggedPost, "ChannelId": channelId, "Offset": offset, "Limit": limit}); err != nil { return nil, errors.Wrap(err, "failed to find Posts") } for _, post := range posts { @@ -669,7 +669,7 @@ func (s *SqlPostStore) Delete(postId string, time int64, deleteByID string) erro return errors.Wrapf(err, "failed to delete Post with id=%s", postId) } - post.AddProp(model.POST_PROPS_DELETE_BY, deleteByID) + post.AddProp(model.PostPropsDeleteBy, deleteByID) _, err = s.GetMaster().Exec("UPDATE Posts SET DeleteAt = :DeleteAt, UpdateAt = :UpdateAt, Props = :Props WHERE Id = :Id OR RootId = :RootId", map[string]interface{}{"DeleteAt": time, "UpdateAt": time, "Id": postId, "RootId": postId, "Props": model.StringInterfaceToJson(post.GetProps())}) if err != nil { @@ -980,7 +980,7 @@ func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFr var query string // union of IDs and then join to get full posts is faster in mysql - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { query = `SELECT *` + replyCountQuery1 + ` FROM Posts p1 JOIN ( (SELECT Id @@ -1008,7 +1008,7 @@ func (s *SqlPostStore) GetPostsSince(options model.GetPostsSinceOptions, allowFr LIMIT 1000) temp_tab)) ) j ON p1.Id = j.Id ORDER BY CreateAt ` + order - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { query = `WITH cte AS (SELECT * FROM @@ -1058,7 +1058,7 @@ func (s *SqlPostStore) HasAutoResponsePostByUserSince(options model.GetPostsSinc "ChannelId": options.ChannelId, "Time": options.Time, "UserId": userId, - "Type": model.POST_AUTO_RESPONDER, + "Type": model.PostTypeAutoResponder, }) if err != nil { @@ -1141,7 +1141,7 @@ func (s *SqlPostStore) getPostsAround(before bool, options model.GetPostsOptions // We force MySQL to use the right index to prevent it from accidentally // using the index_merge_intersection optimization. // See MM-27575. - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { table += " USE INDEX(idx_posts_channel_id_delete_at_create_at)" } columns := []string{"p.*"} @@ -1256,7 +1256,7 @@ func (s *SqlPostStore) getPostIdAroundTime(channelId string, time int64, before // We force MySQL to use the right index to prevent it from accidentally // using the index_merge_intersection optimization. // See MM-27575. - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { table += " USE INDEX(idx_posts_channel_id_delete_at_create_at)" } @@ -1298,7 +1298,7 @@ func (s *SqlPostStore) GetPostAfterTime(channelId string, time int64, collapsedT // We force MySQL to use the right index to prevent it from accidentally // using the index_merge_intersection optimization. // See MM-27575. - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { table += " USE INDEX(idx_posts_channel_id_delete_at_create_at)" } conditions := sq.And{ @@ -1350,7 +1350,7 @@ func (s *SqlPostStore) getRootPosts(channelId string, offset int, limit int, ski } func (s *SqlPostStore) getParentsPosts(channelId string, offset int, limit int, skipFetchThreads bool) ([]*model.Post, error) { - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { return s.getParentsPostsPostgreSQL(channelId, offset, limit, skipFetchThreads) } @@ -1630,7 +1630,7 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search Posts q2 WHERE DeleteAt = 0 - AND Type NOT LIKE '` + model.POST_SYSTEM_MESSAGE_PREFIX + `%' + AND Type NOT LIKE '` + model.PostSystemMessagePrefix + `%' POST_FILTER AND ChannelId IN ( SELECT @@ -1683,7 +1683,7 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search if terms == "" && excludedTerms == "" { // we've already confirmed that we have a channel or user to search for searchQuery = strings.Replace(searchQuery, "SEARCH_CLAUSE", "", 1) - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { // Parse text for wildcards if wildcard, err := regexp.Compile(`\*($| )`); err == nil { terms = wildcard.ReplaceAllLiteralString(terms, ":* ") @@ -1705,7 +1705,7 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search searchClause := fmt.Sprintf("AND to_tsvector('english', %s) @@ to_tsquery('english', :Terms)", searchType) searchQuery = strings.Replace(searchQuery, "SEARCH_CLAUSE", searchClause, 1) - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { if searchType == "Message" { var err error terms, err = removeMysqlStopWordsFromTerms(terms) @@ -1800,7 +1800,7 @@ func (s *SqlPostStore) AnalyticsUserCountsWithPostsByDay(teamId string) (model.A ORDER BY Name DESC LIMIT 30` - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = `SELECT TO_CHAR(DATE(TO_TIMESTAMP(Posts.CreateAt / 1000)), 'YYYY-MM-DD') AS Name, COUNT(DISTINCT Posts.UserId) AS Value @@ -1856,7 +1856,7 @@ func (s *SqlPostStore) AnalyticsPostCountsByDay(options *model.AnalyticsPostCoun ORDER BY Name DESC LIMIT 30` - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = `SELECT TO_CHAR(DATE(TO_TIMESTAMP(Posts.CreateAt / 1000)), 'YYYY-MM-DD') AS Name, Count(Posts.Id) AS Value @@ -2068,7 +2068,7 @@ func (s *SqlPostStore) GetOldest() (*model.Post, error) { func (s *SqlPostStore) determineMaxPostSize() int { var maxPostSizeBytes int32 - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { // The Post.Message column in Postgres has historically been VARCHAR(4000), but // may be manually enlarged to support longer posts. if err := s.GetReplica().SelectOne(&maxPostSizeBytes, ` @@ -2082,7 +2082,7 @@ func (s *SqlPostStore) determineMaxPostSize() int { `); err != nil { mlog.Warn("Unable to determine the maximum supported post size", mlog.Err(err)) } - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { // The Post.Message column in MySQL has historically been TEXT, with a maximum // limit of 65535. if err := s.GetReplica().SelectOne(&maxPostSizeBytes, ` @@ -2108,8 +2108,8 @@ func (s *SqlPostStore) determineMaxPostSize() int { // To maintain backwards compatibility, don't yield a maximum post // size smaller than the previous limit, even though it wasn't // actually possible to store 4000 runes in all cases. - if maxPostSize < model.POST_MESSAGE_MAX_RUNES_V1 { - maxPostSize = model.POST_MESSAGE_MAX_RUNES_V1 + if maxPostSize < model.PostMessageMaxRunesV1 { + maxPostSize = model.PostMessageMaxRunesV1 } mlog.Info("Post.Message has size restrictions", mlog.Int("max_characters", maxPostSize), mlog.Int32("max_bytes", maxPostSizeBytes)) diff --git a/store/sqlstore/preference_store.go b/store/sqlstore/preference_store.go index da02890785..ebb93793fb 100644 --- a/store/sqlstore/preference_store.go +++ b/store/sqlstore/preference_store.go @@ -39,7 +39,7 @@ func (s SqlPreferenceStore) deleteUnusedFeatures() { mlog.Debug("Deleting any unused pre-release features") sql, args, err := s.getQueryBuilder(). Delete("Preferences"). - Where(sq.Eq{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS}). + Where(sq.Eq{"Category": model.PreferenceCategoryAdvancedSettings}). Where(sq.Eq{"Value": "false"}). Where(sq.Like{"Name": store.FeatureTogglePrefix + "%"}).ToSql() if err != nil { @@ -84,9 +84,9 @@ func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *mode Columns("UserId", "Category", "Name", "Value"). Values(preference.UserId, preference.Category, preference.Name, preference.Value) - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { query = query.SuffixExpr(sq.Expr("ON DUPLICATE KEY UPDATE Value = ?", preference.Value)) - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { query = query.SuffixExpr(sq.Expr("ON CONFLICT (userid, category, name) DO UPDATE SET Value = ?", preference.Value)) } else { return store.NewErrNotImplemented("failed to update preference because of missing driver") @@ -237,7 +237,7 @@ func (s *SqlPreferenceStore) DeleteOrphanedRows(limit int) (deleted int64, err e LIMIT :Limit ) AS A )` - props := map[string]interface{}{"Limit": limit, "Category": model.PREFERENCE_CATEGORY_FLAGGED_POST} + props := map[string]interface{}{"Limit": limit, "Category": model.PreferenceCategoryFlaggedPost} result, err := s.GetMaster().Exec(query, props) if err != nil { return @@ -257,7 +257,7 @@ func (s SqlPreferenceStore) CleanupFlagsBatch(limit int64) (int64, error) { sq.Select("Preferences.Name"). From("Preferences"). LeftJoin("Posts ON Preferences.Name = Posts.Id"). - Where(sq.Eq{"Preferences.Category": model.PREFERENCE_CATEGORY_FLAGGED_POST}). + Where(sq.Eq{"Preferences.Category": model.PreferenceCategoryFlaggedPost}). Where(sq.Eq{"Posts.Id": nil}). Limit(uint64(limit)), "t"). @@ -266,7 +266,7 @@ func (s SqlPreferenceStore) CleanupFlagsBatch(limit int64) (int64, error) { return int64(0), errors.Wrap(err, "could not build nested sql query to delete preference") } query, args, err := s.getQueryBuilder().Delete("Preferences"). - Where(sq.Eq{"Category": model.PREFERENCE_CATEGORY_FLAGGED_POST}). + Where(sq.Eq{"Category": model.PreferenceCategoryFlaggedPost}). Where(sq.Expr("name IN ("+nameInQ+")", nameInArgs...)). ToSql() diff --git a/store/sqlstore/preference_store_test.go b/store/sqlstore/preference_store_test.go index e8c123eb20..5d29aa6874 100644 --- a/store/sqlstore/preference_store_test.go +++ b/store/sqlstore/preference_store_test.go @@ -21,7 +21,7 @@ func TestDeleteUnusedFeatures(t *testing.T) { StoreTest(t, func(t *testing.T, ss store.Store) { userId1 := model.NewId() userId2 := model.NewId() - category := model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS + category := model.PreferenceCategoryAdvancedSettings feature1 := "feature1" feature2 := "feature2" @@ -62,7 +62,7 @@ func TestDeleteUnusedFeatures(t *testing.T) { FROM Preferences WHERE Category = :Category AND Value = :Val - AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "false"}); err != nil { + AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PreferenceCategoryAdvancedSettings, "Val": "false"}); err != nil { require.NoError(t, err) } else if val != 0 { require.Fail(t, "Found %d features with value 'false', expected all to be deleted", val) @@ -73,7 +73,7 @@ func TestDeleteUnusedFeatures(t *testing.T) { FROM Preferences WHERE Category = :Category AND Value = :Val - AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "true"}); err != nil { + AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PreferenceCategoryAdvancedSettings, "Val": "true"}); err != nil { require.NoError(t, err) } else if val == 0 { require.Fail(t, "Found %d features with value 'true', expected to find at least %d features", val, 2) diff --git a/store/sqlstore/reaction_store.go b/store/sqlstore/reaction_store.go index 40a375be91..63d92c6d65 100644 --- a/store/sqlstore/reaction_store.go +++ b/store/sqlstore/reaction_store.go @@ -260,7 +260,7 @@ func (s *SqlReactionStore) saveReactionAndUpdatePost(transaction *gorp.Transacti "RemoteId": reaction.RemoteId, } - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { if _, err := transaction.Exec( `INSERT INTO Reactions @@ -271,7 +271,7 @@ func (s *SqlReactionStore) saveReactionAndUpdatePost(transaction *gorp.Transacti UpdateAt = :UpdateAt, DeleteAt = 0, RemoteId = :RemoteId`, params); err != nil { return err } - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { if _, err := transaction.Exec( `INSERT INTO Reactions diff --git a/store/sqlstore/remote_cluster_store.go b/store/sqlstore/remote_cluster_store.go index ea7acf98cd..9defad0b95 100644 --- a/store/sqlstore/remote_cluster_store.go +++ b/store/sqlstore/remote_cluster_store.go @@ -180,7 +180,7 @@ func (s sqlRemoteClusterStore) SetLastPingAt(remoteClusterId string) error { func (s *sqlRemoteClusterStore) createIndexesIfNotExists() { uniquenessColumns := []string{"SiteUrl", "RemoteTeamId"} - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { uniquenessColumns = []string{"RemoteTeamId", "SiteUrl(168)"} } s.CreateUniqueCompositeIndexIfNotExists(RemoteClusterSiteURLUniqueIndex, "RemoteClusters", uniquenessColumns) diff --git a/store/sqlstore/retention_policy_store.go b/store/sqlstore/retention_policy_store.go index 5a696c671f..0bca67ac97 100644 --- a/store/sqlstore/retention_policy_store.go +++ b/store/sqlstore/retention_policy_store.go @@ -793,7 +793,7 @@ func genericRetentionPoliciesDeletion( if err != nil { return 0, errors.Wrap(err, r.Table+"_tosql") } - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { primaryKeysStr := "(" + strings.Join(r.PrimaryKeys, ",") + ")" query = ` DELETE FROM ` + r.Table + ` WHERE ` + primaryKeysStr + ` IN ( diff --git a/store/sqlstore/role_store.go b/store/sqlstore/role_store.go index ad25cd7f58..8070bb821b 100644 --- a/store/sqlstore/role_store.go +++ b/store/sqlstore/role_store.go @@ -325,9 +325,9 @@ func (s *SqlRoleStore) channelHigherScopedPermissionsQuery(roleNames []string) s return fmt.Sprintf( sqlTmpl, strings.Join(roleNames, "', '"), - model.CHANNEL_GUEST_ROLE_ID, - model.CHANNEL_USER_ROLE_ID, - model.CHANNEL_ADMIN_ROLE_ID, + model.ChannelGuestRoleId, + model.ChannelUserRoleId, + model.ChannelAdminRoleId, ) } @@ -342,9 +342,9 @@ func (s *SqlRoleStore) ChannelHigherScopedPermissions(roleNames []string) (map[s roleNameHigherScopedPermissions := map[string]*model.RolePermissions{} for _, rp := range rolesPermissions { - roleNameHigherScopedPermissions[rp.GuestRoleName] = &model.RolePermissions{RoleID: model.CHANNEL_GUEST_ROLE_ID, Permissions: strings.Split(rp.HigherScopedGuestPermissions, " ")} - roleNameHigherScopedPermissions[rp.UserRoleName] = &model.RolePermissions{RoleID: model.CHANNEL_USER_ROLE_ID, Permissions: strings.Split(rp.HigherScopedUserPermissions, " ")} - roleNameHigherScopedPermissions[rp.AdminRoleName] = &model.RolePermissions{RoleID: model.CHANNEL_ADMIN_ROLE_ID, Permissions: strings.Split(rp.HigherScopedAdminPermissions, " ")} + roleNameHigherScopedPermissions[rp.GuestRoleName] = &model.RolePermissions{RoleID: model.ChannelGuestRoleId, Permissions: strings.Split(rp.HigherScopedGuestPermissions, " ")} + roleNameHigherScopedPermissions[rp.UserRoleName] = &model.RolePermissions{RoleID: model.ChannelUserRoleId, Permissions: strings.Split(rp.HigherScopedUserPermissions, " ")} + roleNameHigherScopedPermissions[rp.AdminRoleName] = &model.RolePermissions{RoleID: model.ChannelAdminRoleId, Permissions: strings.Split(rp.HigherScopedAdminPermissions, " ")} } return roleNameHigherScopedPermissions, nil @@ -355,7 +355,7 @@ func (s *SqlRoleStore) AllChannelSchemeRoles() ([]*model.Role, error) { Select("Roles.*"). From("Schemes"). Join("Roles ON Schemes.DefaultChannelGuestRole = Roles.Name OR Schemes.DefaultChannelUserRole = Roles.Name OR Schemes.DefaultChannelAdminRole = Roles.Name"). - Where(sq.Eq{"Schemes.Scope": model.SCHEME_SCOPE_CHANNEL}). + Where(sq.Eq{"Schemes.Scope": model.SchemeScopeChannel}). Where(sq.Eq{"Roles.DeleteAt": 0}). Where(sq.Eq{"Schemes.DeleteAt": 0}) @@ -387,7 +387,7 @@ func (s *SqlRoleStore) ChannelRolesUnderTeamRole(roleName string) ([]*model.Role Join("Channels ON Channels.TeamId = Teams.Id"). Join("Schemes AS ChannelSchemes ON Channels.SchemeId = ChannelSchemes.Id"). Join("Roles AS ChannelSchemeRoles ON (ChannelSchemeRoles.Name = ChannelSchemes.DefaultChannelGuestRole OR ChannelSchemeRoles.Name = ChannelSchemes.DefaultChannelUserRole OR ChannelSchemeRoles.Name = ChannelSchemes.DefaultChannelAdminRole)"). - Where(sq.Eq{"HigherScopedSchemes.Scope": model.SCHEME_SCOPE_TEAM}). + Where(sq.Eq{"HigherScopedSchemes.Scope": model.SchemeScopeTeam}). Where(sq.Eq{"HigherScopedRoles.Name": roleName}). Where(sq.Eq{"HigherScopedRoles.DeleteAt": 0}). Where(sq.Eq{"HigherScopedSchemes.DeleteAt": 0}). diff --git a/store/sqlstore/scheme_store.go b/store/sqlstore/scheme_store.go index d42beeea1b..01ba87c4ea 100644 --- a/store/sqlstore/scheme_store.go +++ b/store/sqlstore/scheme_store.go @@ -25,9 +25,9 @@ func newSqlSchemeStore(sqlStore *SqlStore) store.SchemeStore { for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.Scheme{}, "Schemes").SetKeys(false, "Id") table.ColMap("Id").SetMaxSize(26) - table.ColMap("Name").SetMaxSize(model.SCHEME_NAME_MAX_LENGTH).SetUnique(true) - table.ColMap("DisplayName").SetMaxSize(model.SCHEME_DISPLAY_NAME_MAX_LENGTH) - table.ColMap("Description").SetMaxSize(model.SCHEME_DESCRIPTION_MAX_LENGTH) + table.ColMap("Name").SetMaxSize(model.SchemeNameMaxLength).SetUnique(true) + table.ColMap("DisplayName").SetMaxSize(model.SchemeDisplayNameMaxLength) + table.ColMap("Description").SetMaxSize(model.SchemeDescriptionMaxLength) table.ColMap("Scope").SetMaxSize(32) table.ColMap("DefaultTeamAdminRole").SetMaxSize(64) table.ColMap("DefaultTeamUserRole").SetMaxSize(64) @@ -83,7 +83,7 @@ func (s *SqlSchemeStore) Save(scheme *model.Scheme) (*model.Scheme, error) { func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Transaction) (*model.Scheme, error) { // Fetch the default system scheme roles to populate default permissions. - defaultRoleNames := []string{model.TEAM_ADMIN_ROLE_ID, model.TEAM_USER_ROLE_ID, model.TEAM_GUEST_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_GUEST_ROLE_ID} + defaultRoleNames := []string{model.TeamAdminRoleId, model.TeamUserRoleId, model.TeamGuestRoleId, model.ChannelAdminRoleId, model.ChannelUserRoleId, model.ChannelGuestRoleId} defaultRoles := make(map[string]*model.Role) roles, err := s.SqlStore.Role().GetByNames(defaultRoleNames) if err != nil { @@ -92,18 +92,18 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr for _, role := range roles { switch role.Name { - case model.TEAM_ADMIN_ROLE_ID: - defaultRoles[model.TEAM_ADMIN_ROLE_ID] = role - case model.TEAM_USER_ROLE_ID: - defaultRoles[model.TEAM_USER_ROLE_ID] = role - case model.TEAM_GUEST_ROLE_ID: - defaultRoles[model.TEAM_GUEST_ROLE_ID] = role - case model.CHANNEL_ADMIN_ROLE_ID: - defaultRoles[model.CHANNEL_ADMIN_ROLE_ID] = role - case model.CHANNEL_USER_ROLE_ID: - defaultRoles[model.CHANNEL_USER_ROLE_ID] = role - case model.CHANNEL_GUEST_ROLE_ID: - defaultRoles[model.CHANNEL_GUEST_ROLE_ID] = role + case model.TeamAdminRoleId: + defaultRoles[model.TeamAdminRoleId] = role + case model.TeamUserRoleId: + defaultRoles[model.TeamUserRoleId] = role + case model.TeamGuestRoleId: + defaultRoles[model.TeamGuestRoleId] = role + case model.ChannelAdminRoleId: + defaultRoles[model.ChannelAdminRoleId] = role + case model.ChannelUserRoleId: + defaultRoles[model.ChannelUserRoleId] = role + case model.ChannelGuestRoleId: + defaultRoles[model.ChannelGuestRoleId] = role } } @@ -112,12 +112,12 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr } // Create the appropriate default roles for the scheme. - if scheme.Scope == model.SCHEME_SCOPE_TEAM { + if scheme.Scope == model.SchemeScopeTeam { // Team Admin Role teamAdminRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Team Admin Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.TEAM_ADMIN_ROLE_ID].Permissions, + Permissions: defaultRoles[model.TeamAdminRoleId].Permissions, SchemeManaged: true, } @@ -131,7 +131,7 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr teamUserRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Team User Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.TEAM_USER_ROLE_ID].Permissions, + Permissions: defaultRoles[model.TeamUserRoleId].Permissions, SchemeManaged: true, } @@ -145,7 +145,7 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr teamGuestRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Team Guest Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.TEAM_GUEST_ROLE_ID].Permissions, + Permissions: defaultRoles[model.TeamGuestRoleId].Permissions, SchemeManaged: true, } @@ -156,16 +156,16 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr scheme.DefaultTeamGuestRole = savedRole.Name } - if scheme.Scope == model.SCHEME_SCOPE_TEAM || scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope == model.SchemeScopeTeam || scheme.Scope == model.SchemeScopeChannel { // Channel Admin Role channelAdminRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Channel Admin Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, + Permissions: defaultRoles[model.ChannelAdminRoleId].Permissions, SchemeManaged: true, } - if scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope == model.SchemeScopeChannel { channelAdminRole.Permissions = []string{} } @@ -179,11 +179,11 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr channelUserRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Channel User Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.CHANNEL_USER_ROLE_ID].Permissions, + Permissions: defaultRoles[model.ChannelUserRoleId].Permissions, SchemeManaged: true, } - if scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope == model.SchemeScopeChannel { channelUserRole.Permissions = filterModerated(channelUserRole.Permissions) } @@ -197,11 +197,11 @@ func (s *SqlSchemeStore) createScheme(scheme *model.Scheme, transaction *gorp.Tr channelGuestRole := &model.Role{ Name: model.NewId(), DisplayName: fmt.Sprintf("Channel Guest Role for Scheme %s", scheme.Name), - Permissions: defaultRoles[model.CHANNEL_GUEST_ROLE_ID].Permissions, + Permissions: defaultRoles[model.ChannelGuestRoleId].Permissions, SchemeManaged: true, } - if scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + if scheme.Scope == model.SchemeScopeChannel { channelGuestRole.Permissions = filterModerated(channelGuestRole.Permissions) } @@ -277,13 +277,13 @@ func (s *SqlSchemeStore) Delete(schemeId string) (*model.Scheme, error) { } // Update any teams or channels using this scheme to the default scheme. - if scheme.Scope == model.SCHEME_SCOPE_TEAM { + if scheme.Scope == model.SchemeScopeTeam { if _, err := s.GetMaster().Exec("UPDATE Teams SET SchemeId = '' WHERE SchemeId = :SchemeId", map[string]interface{}{"SchemeId": schemeId}); err != nil { return nil, errors.Wrapf(err, "failed to update Teams with schemeId=%s", schemeId) } s.Team().ClearCaches() - } else if scheme.Scope == model.SCHEME_SCOPE_CHANNEL { + } else if scheme.Scope == model.SchemeScopeChannel { if _, err := s.GetMaster().Exec("UPDATE Channels SET SchemeId = '' WHERE SchemeId = :SchemeId", map[string]interface{}{"SchemeId": schemeId}); err != nil { return nil, errors.Wrapf(err, "failed to update Channels with schemeId=%s", schemeId) } @@ -294,7 +294,7 @@ func (s *SqlSchemeStore) Delete(schemeId string) (*model.Scheme, error) { // Delete the roles belonging to the scheme. roleNames := []string{scheme.DefaultChannelGuestRole, scheme.DefaultChannelUserRole, scheme.DefaultChannelAdminRole} - if scheme.Scope == model.SCHEME_SCOPE_TEAM { + if scheme.Scope == model.SchemeScopeTeam { roleNames = append(roleNames, scheme.DefaultTeamGuestRole, scheme.DefaultTeamUserRole, scheme.DefaultTeamAdminRole) } diff --git a/store/sqlstore/session_store.go b/store/sqlstore/session_store.go index ec96fcb168..93c4b72395 100644 --- a/store/sqlstore/session_store.go +++ b/store/sqlstore/session_store.go @@ -283,7 +283,7 @@ func (me SqlSessionStore) Cleanup(expiryTime int64, batchSize int64) { mlog.Debug("Cleaning up session store.") var query string - if me.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if me.DriverName() == model.DatabaseDriverPostgres { query = "DELETE FROM Sessions WHERE Id = any (array (SELECT Id FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit))" } else { query = "DELETE FROM Sessions WHERE ExpiresAt != 0 AND :ExpiresAt > ExpiresAt LIMIT :Limit" diff --git a/store/sqlstore/shared_channel_store.go b/store/sqlstore/shared_channel_store.go index d5e6e231f1..9c71318861 100644 --- a/store/sqlstore/shared_channel_store.go +++ b/store/sqlstore/shared_channel_store.go @@ -654,7 +654,7 @@ func (s SqlSharedChannelStore) UpdateUserLastSyncAt(userID string, channelID str args := map[string]interface{}{"UserId": userID, "ChannelId": channelID, "RemoteId": remoteID} var query string - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = ` UPDATE SharedChannelUsers AS scu @@ -665,7 +665,7 @@ func (s SqlSharedChannelStore) UpdateUserLastSyncAt(userID string, channelID str WHERE Users.Id = scu.UserId AND scu.UserId = :UserId AND scu.ChannelId = :ChannelId AND scu.RemoteId = :RemoteId ` - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { query = ` UPDATE SharedChannelUsers AS scu @@ -725,7 +725,7 @@ func (s SqlSharedChannelStore) UpsertAttachment(attachment *model.SharedChannelA "LastSyncAt": attachment.LastSyncAt, } - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { if _, err := s.GetMaster().Exec( `INSERT INTO SharedChannelAttachments @@ -736,7 +736,7 @@ func (s SqlSharedChannelStore) UpsertAttachment(attachment *model.SharedChannelA LastSyncAt = :LastSyncAt`, params); err != nil { return "", err } - } else if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if s.DriverName() == model.DatabaseDriverPostgres { if _, err := s.GetMaster().Exec( `INSERT INTO SharedChannelAttachments diff --git a/store/sqlstore/status_store.go b/store/sqlstore/status_store.go index 77925493df..09e05a46e6 100644 --- a/store/sqlstore/status_store.go +++ b/store/sqlstore/status_store.go @@ -110,7 +110,7 @@ func (s SqlStatusStore) updateExpiredStatuses(t *gorp.Transaction) ([]*model.Sta From("Status"). Where( sq.And{ - sq.Eq{"Status": model.STATUS_DND}, + sq.Eq{"Status": model.StatusDnd}, sq.Gt{"DNDEndTime": 0}, sq.LtOrEq{"DNDEndTime": currUnixTime}, }, @@ -126,13 +126,13 @@ func (s SqlStatusStore) updateExpiredStatuses(t *gorp.Transaction) ([]*model.Sta Update("Status"). Where( sq.And{ - sq.Eq{"Status": model.STATUS_DND}, + sq.Eq{"Status": model.StatusDnd}, sq.Gt{"DNDEndTime": 0}, sq.LtOrEq{"DNDEndTime": currUnixTime}, }, ). Set("Status", sq.Expr("PrevStatus")). - Set("PrevStatus", model.STATUS_DND). + Set("PrevStatus", model.StatusDnd). Set("DNDEndTime", 0). Set("Manual", false). ToSql() @@ -149,7 +149,7 @@ func (s SqlStatusStore) updateExpiredStatuses(t *gorp.Transaction) ([]*model.Sta } func (s SqlStatusStore) UpdateExpiredDNDStatuses() ([]*model.Status, error) { - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { transaction, err := s.GetMaster().Begin() if err != nil { return nil, errors.Wrap(err, "UpdateExpiredDNDStatuses: begin_transaction") @@ -165,7 +165,7 @@ func (s SqlStatusStore) UpdateExpiredDNDStatuses() ([]*model.Status, error) { for _, status := range statuses { status.Status = status.PrevStatus - status.PrevStatus = model.STATUS_DND + status.PrevStatus = model.StatusDnd status.DNDEndTime = 0 status.Manual = false } @@ -177,13 +177,13 @@ func (s SqlStatusStore) UpdateExpiredDNDStatuses() ([]*model.Status, error) { Update("Status"). Where( sq.And{ - sq.Eq{"Status": model.STATUS_DND}, + sq.Eq{"Status": model.StatusDnd}, sq.Gt{"DNDEndTime": 0}, sq.LtOrEq{"DNDEndTime": time.Now().UTC().Unix()}, }, ). Set("Status", sq.Expr("PrevStatus")). - Set("PrevStatus", model.STATUS_DND). + Set("PrevStatus", model.StatusDnd). Set("DNDEndTime", 0). Set("Manual", false). Suffix("RETURNING *"). @@ -215,7 +215,7 @@ func (s SqlStatusStore) UpdateExpiredDNDStatuses() ([]*model.Status, error) { } func (s SqlStatusStore) ResetAll() error { - if _, err := s.GetMaster().Exec("UPDATE Status SET Status = :Status WHERE Manual = false", map[string]interface{}{"Status": model.STATUS_OFFLINE}); err != nil { + if _, err := s.GetMaster().Exec("UPDATE Status SET Status = :Status WHERE Manual = false", map[string]interface{}{"Status": model.StatusOffline}); err != nil { return errors.Wrap(err, "failed to update Statuses") } return nil diff --git a/store/sqlstore/store.go b/store/sqlstore/store.go index c42d8dc575..024304a2b5 100644 --- a/store/sqlstore/store.go +++ b/store/sqlstore/store.go @@ -179,7 +179,7 @@ func New(settings model.SqlSettings, metrics einterfaces.MetricsInterface) *SqlS store.initConnection() - if *settings.DriverName == model.DATABASE_DRIVER_POSTGRES { + if *settings.DriverName == model.DatabaseDriverPostgres { ver, err := store.GetDbVersion(true) if err != nil { mlog.Critical("Cannot get DB version.", mlog.Err(err)) @@ -347,14 +347,14 @@ func getDBMap(settings *model.SqlSettings, db *dbsql.DB) *gorp.DbMap { connectionTimeout := time.Duration(*settings.QueryTimeout) * time.Second var dbMap *gorp.DbMap switch *settings.DriverName { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: dbMap = &gorp.DbMap{ Db: db, TypeConverter: mattermConverter{}, Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8MB4"}, QueryTimeout: connectionTimeout, } - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: dbMap = &gorp.DbMap{ Db: db, TypeConverter: mattermConverter{}, @@ -383,7 +383,7 @@ func (ss *SqlStore) Context() context.Context { func (ss *SqlStore) initConnection() { dataSource := *ss.settings.DataSource - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { // TODO: We ignore the readTimeout datasource parameter for MySQL since QueryTimeout // covers that already. Ideally we'd like to do this only for the upgrade // step. To be reviewed in MM-35789. @@ -437,13 +437,13 @@ func (ss *SqlStore) GetCurrentSchemaVersion() string { // that can be parsed by callers. func (ss *SqlStore) GetDbVersion(numerical bool) (string, error) { var sqlVersion string - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { if numerical { sqlVersion = `SHOW server_version_num` } else { sqlVersion = `SHOW server_version` } - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { sqlVersion = `SELECT version()` } else { return "", errors.New("Not supported driver") @@ -564,15 +564,15 @@ func (ss *SqlStore) MarkSystemRanUnitTests() { return } - unitTests := props[model.SYSTEM_RAN_UNIT_TESTS] + unitTests := props[model.SystemRanUnitTests] if unitTests == "" { - systemTests := &model.System{Name: model.SYSTEM_RAN_UNIT_TESTS, Value: "1"} + systemTests := &model.System{Name: model.SystemRanUnitTests, Value: "1"} ss.System().Save(systemTests) } } func (ss *SqlStore) DoesTableExist(tableName string) bool { - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { count, err := ss.GetMaster().SelectInt( `SELECT count(relname) FROM pg_class WHERE relname=$1`, strings.ToLower(tableName), @@ -586,7 +586,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { return count > 0 - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { count, err := ss.GetMaster().SelectInt( `SELECT @@ -617,7 +617,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { } func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { count, err := ss.GetMaster().SelectInt( `SELECT COUNT(0) FROM pg_attribute @@ -640,7 +640,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { return count > 0 - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { count, err := ss.GetMaster().SelectInt( `SELECT @@ -674,7 +674,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { // GetColumnInfo returns data type information about the given column. func (ss *SqlStore) GetColumnInfo(tableName, columnName string) (*ColumnInfo, error) { var columnInfo ColumnInfo - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { err := ss.GetMaster().SelectOne(&columnInfo, `SELECT data_type as DataType, COALESCE(character_maximum_length, 0) as CharMaximumLength @@ -686,7 +686,7 @@ func (ss *SqlStore) GetColumnInfo(tableName, columnName string) (*ColumnInfo, er return nil, err } return &columnInfo, nil - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { err := ss.GetMaster().SelectOne(&columnInfo, `SELECT data_type as DataType, COALESCE(character_maximum_length, 0) as CharMaximumLength @@ -706,11 +706,11 @@ func (ss *SqlStore) GetColumnInfo(tableName, columnName string) (*ColumnInfo, er // IsVarchar returns true if the column type matches one of the varchar types // either in MySQL or PostgreSQL. func (ss *SqlStore) IsVarchar(columnType string) bool { - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES && columnType == "character varying" { + if ss.DriverName() == model.DatabaseDriverPostgres && columnType == "character varying" { return true } - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL && columnType == "varchar" { + if ss.DriverName() == model.DatabaseDriverMysql && columnType == "varchar" { return true } @@ -718,7 +718,7 @@ func (ss *SqlStore) IsVarchar(columnType string) bool { } func (ss *SqlStore) DoesTriggerExist(triggerName string) bool { - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { count, err := ss.GetMaster().SelectInt(` SELECT COUNT(0) @@ -736,7 +736,7 @@ func (ss *SqlStore) DoesTriggerExist(triggerName string) bool { return count > 0 - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { count, err := ss.GetMaster().SelectInt(` SELECT COUNT(0) @@ -769,7 +769,7 @@ func (ss *SqlStore) CreateColumnIfNotExists(tableName string, columnName string, return false } - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { _, err := ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " ADD " + columnName + " " + postgresColType + " DEFAULT '" + defaultValue + "'") if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) @@ -779,7 +779,7 @@ func (ss *SqlStore) CreateColumnIfNotExists(tableName string, columnName string, return true - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { _, err := ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " ADD " + columnName + " " + mySqlColType + " DEFAULT '" + defaultValue + "'") if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) @@ -803,7 +803,7 @@ func (ss *SqlStore) CreateColumnIfNotExistsNoDefault(tableName string, columnNam return false } - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { _, err := ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " ADD " + columnName + " " + postgresColType) if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) @@ -813,7 +813,7 @@ func (ss *SqlStore) CreateColumnIfNotExistsNoDefault(tableName string, columnNam return true - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { _, err := ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " ADD " + columnName + " " + mySqlColType) if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) @@ -868,9 +868,9 @@ func (ss *SqlStore) RenameColumnIfExists(tableName string, oldColumnName string, } var err error - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { _, err = ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " CHANGE " + oldColumnName + " " + newColumnName + " " + colType) - } else if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if ss.DriverName() == model.DatabaseDriverPostgres { _, err = ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " RENAME COLUMN " + oldColumnName + " TO " + newColumnName) } @@ -890,9 +890,9 @@ func (ss *SqlStore) GetMaxLengthOfColumnIfExists(tableName string, columnName st var result string var err error - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { result, err = ss.GetMaster().SelectStr("SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns WHERE table_name = '" + tableName + "' AND COLUMN_NAME = '" + columnName + "'") - } else if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if ss.DriverName() == model.DatabaseDriverPostgres { result, err = ss.GetMaster().SelectStr("SELECT character_maximum_length FROM information_schema.columns WHERE table_name = '" + strings.ToLower(tableName) + "' AND column_name = '" + strings.ToLower(columnName) + "'") } @@ -911,9 +911,9 @@ func (ss *SqlStore) AlterColumnTypeIfExists(tableName string, columnName string, } var err error - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { _, err = ss.GetMaster().ExecNoTimeout("ALTER TABLE " + tableName + " MODIFY " + columnName + " " + mySqlColType) - } else if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if ss.DriverName() == model.DatabaseDriverPostgres { _, err = ss.GetMaster().ExecNoTimeout("ALTER TABLE " + strings.ToLower(tableName) + " ALTER COLUMN " + strings.ToLower(columnName) + " TYPE " + postgresColType) } @@ -948,14 +948,14 @@ func (ss *SqlStore) AlterDefaultIfColumnExists(tableName string, columnName stri } var defaultValue string - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { // Some column types in MySQL cannot have defaults, so don't try to configure anything. if mySqlColDefault == nil { return true } defaultValue = *mySqlColDefault - } else if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if ss.DriverName() == model.DatabaseDriverPostgres { // Postgres doesn't have the same limitation, but preserve the interface. if postgresColDefault == nil { return true @@ -992,7 +992,7 @@ func (ss *SqlStore) AlterPrimaryKey(tableName string, columnNames []string) bool var err error // get the current primary key as a comma separated list of columns switch ss.DriverName() { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: query := ` SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index) AS PK FROM @@ -1004,7 +1004,7 @@ func (ss *SqlStore) AlterPrimaryKey(tableName string, columnNames []string) bool GROUP BY index_name` currentPrimaryKey, err = ss.GetMaster().SelectStr(query, tableName) - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: query := ` SELECT string_agg(a.attname, ',') AS pk FROM @@ -1031,9 +1031,9 @@ func (ss *SqlStore) AlterPrimaryKey(tableName string, columnNames []string) bool } // alter primary key var alterQuery string - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { alterQuery = "ALTER TABLE " + tableName + " DROP PRIMARY KEY, ADD PRIMARY KEY (" + primaryKey + ")" - } else if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if ss.DriverName() == model.DatabaseDriverPostgres { alterQuery = "ALTER TABLE " + tableName + " DROP CONSTRAINT " + strings.ToLower(tableName) + "_pkey, ADD PRIMARY KEY (" + strings.ToLower(primaryKey) + ")" } _, err = ss.GetMaster().ExecNoTimeout(alterQuery) @@ -1076,7 +1076,7 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c uniqueStr = "UNIQUE " } - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { _, errExists := ss.GetMaster().SelectStr("SELECT $1::regclass", indexName) // It should fail if the index does not exist if errExists == nil { @@ -1109,7 +1109,7 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c time.Sleep(time.Second) os.Exit(ExitCreateIndexPostgres) } - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { count, err := ss.GetMaster().SelectInt("SELECT COUNT(0) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = ? AND index_name = ?", tableName, indexName) if err != nil { @@ -1168,7 +1168,7 @@ func (ss *SqlStore) CreateForeignKeyIfNotExists( func (ss *SqlStore) RemoveIndexIfExists(indexName string, tableName string) bool { - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { _, err := ss.GetMaster().SelectStr("SELECT $1::regclass", indexName) // It should fail if the index does not exist if err != nil { @@ -1183,7 +1183,7 @@ func (ss *SqlStore) RemoveIndexIfExists(indexName string, tableName string) bool } return true - } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if ss.DriverName() == model.DatabaseDriverMysql { count, err := ss.GetMaster().SelectInt("SELECT COUNT(0) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() and table_name = ? AND index_name = ?", tableName, indexName) if err != nil { @@ -1443,7 +1443,7 @@ func (ss *SqlStore) DropAllTables() { func (ss *SqlStore) getQueryBuilder() sq.StatementBuilderType { builder := sq.StatementBuilder.PlaceholderFormat(sq.Question) - if ss.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if ss.DriverName() == model.DatabaseDriverPostgres { builder = builder.PlaceholderFormat(sq.Dollar) } return builder @@ -1478,7 +1478,7 @@ func (ss *SqlStore) migrate(direction migrationDirection) error { conn := setupConnection("migrations", dataSource, ss.settings) defer conn.Db.Close() - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { driver, err = mysqlmigrate.WithInstance(conn.Db, &mysqlmigrate.Config{}) if err != nil { return err @@ -1535,7 +1535,7 @@ func (ss *SqlStore) migrate(direction migrationDirection) error { func (ss *SqlStore) appendMultipleStatementsFlag(dataSource string) (string, error) { // We need to tell the MySQL driver that we want to use multiStatements // in order to make migrations work. - if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { + if ss.DriverName() == model.DatabaseDriverMysql { config, err := mysql.ParseDSN(dataSource) if err != nil { return "", err diff --git a/store/sqlstore/store_test.go b/store/sqlstore/store_test.go index 55081f0663..7d54edeb01 100644 --- a/store/sqlstore/store_test.go +++ b/store/sqlstore/store_test.go @@ -104,14 +104,14 @@ func initStores() { if os.Getenv("IS_CI") == "true" { switch os.Getenv("MM_SQLSETTINGS_DRIVERNAME") { case "mysql": - storeTypes = append(storeTypes, newStoreType("MySQL", model.DATABASE_DRIVER_MYSQL)) + storeTypes = append(storeTypes, newStoreType("MySQL", model.DatabaseDriverMysql)) case "postgres": - storeTypes = append(storeTypes, newStoreType("PostgreSQL", model.DATABASE_DRIVER_POSTGRES)) + storeTypes = append(storeTypes, newStoreType("PostgreSQL", model.DatabaseDriverPostgres)) } } else { storeTypes = append(storeTypes, - newStoreType("MySQL", model.DATABASE_DRIVER_MYSQL), - newStoreType("PostgreSQL", model.DATABASE_DRIVER_POSTGRES), + newStoreType("MySQL", model.DatabaseDriverMysql), + newStoreType("PostgreSQL", model.DatabaseDriverPostgres), ) } @@ -165,7 +165,7 @@ func tearDownStores() { // before the fix in MM-28397. // Keeping it here to help avoiding future regressions. func TestStoreLicenseRace(t *testing.T) { - settings := makeSqlSettings(model.DATABASE_DRIVER_POSTGRES) + settings := makeSqlSettings(model.DatabaseDriverPostgres) store := New(*settings, nil) defer func() { store.Close() @@ -251,7 +251,7 @@ func TestGetReplica(t *testing.T) { testCase := testCase t.Run(testCase.Description+" with license", func(t *testing.T) { - settings := makeSqlSettings(model.DATABASE_DRIVER_POSTGRES) + settings := makeSqlSettings(model.DatabaseDriverPostgres) dataSourceReplicas := []string{} dataSourceSearchReplicas := []string{} for i := 0; i < testCase.DataSourceReplicaNum; i++ { @@ -321,7 +321,7 @@ func TestGetReplica(t *testing.T) { t.Run(testCase.Description+" without license", func(t *testing.T) { - settings := makeSqlSettings(model.DATABASE_DRIVER_POSTGRES) + settings := makeSqlSettings(model.DatabaseDriverPostgres) dataSourceReplicas := []string{} dataSourceSearchReplicas := []string{} for i := 0; i < testCase.DataSourceReplicaNum; i++ { @@ -389,8 +389,8 @@ func TestGetReplica(t *testing.T) { func TestGetDbVersion(t *testing.T) { testDrivers := []string{ - model.DATABASE_DRIVER_POSTGRES, - model.DATABASE_DRIVER_MYSQL, + model.DatabaseDriverPostgres, + model.DatabaseDriverMysql, } for _, driver := range testDrivers { @@ -408,8 +408,8 @@ func TestGetDbVersion(t *testing.T) { func TestUpAndDownMigrations(t *testing.T) { testDrivers := []string{ - model.DATABASE_DRIVER_POSTGRES, - model.DATABASE_DRIVER_MYSQL, + model.DatabaseDriverPostgres, + model.DatabaseDriverMysql, } for _, driver := range testDrivers { @@ -493,7 +493,7 @@ func TestGetAllConns(t *testing.T) { testCase := testCase t.Run(testCase.Description, func(t *testing.T) { t.Parallel() - settings := makeSqlSettings(model.DATABASE_DRIVER_POSTGRES) + settings := makeSqlSettings(model.DatabaseDriverPostgres) dataSourceReplicas := []string{} dataSourceSearchReplicas := []string{} for i := 0; i < testCase.DataSourceReplicaNum; i++ { @@ -560,8 +560,8 @@ func TestVersionString(t *testing.T) { func TestReplicaLagQuery(t *testing.T) { testDrivers := []string{ - model.DATABASE_DRIVER_POSTGRES, - model.DATABASE_DRIVER_MYSQL, + model.DatabaseDriverPostgres, + model.DatabaseDriverMysql, } for _, driver := range testDrivers { @@ -570,10 +570,10 @@ func TestReplicaLagQuery(t *testing.T) { var tableName string // Just any random query which returns a row in (string, int) format. switch driver { - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: query = `SELECT relname, count(relname) FROM pg_class WHERE relname='posts' GROUP BY relname` tableName = "posts" - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: query = `SELECT table_name, count(table_name) FROM information_schema.tables WHERE table_name='Posts' and table_schema=Database() GROUP BY table_name` tableName = "Posts" } @@ -621,19 +621,19 @@ func TestAppendMultipleStatementsFlagMysql(t *testing.T) { "Should append multiStatements param to the DSN path with existing params", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost?writeTimeout=30s", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost?writeTimeout=30s&multiStatements=true", - model.DATABASE_DRIVER_MYSQL, + model.DatabaseDriverMysql, }, { "Should append multiStatements param to the DSN path with no existing params", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost?multiStatements=true", - model.DATABASE_DRIVER_MYSQL, + model.DatabaseDriverMysql, }, { "Should not multiStatements param to the DSN when driver is not MySQL", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost", "user:rand?&ompasswith@character@unix(/var/run/mysqld/mysqld.sock)/mattermost", - model.DATABASE_DRIVER_POSTGRES, + model.DatabaseDriverPostgres, }, } @@ -649,9 +649,9 @@ func TestAppendMultipleStatementsFlagMysql(t *testing.T) { func makeSqlSettings(driver string) *model.SqlSettings { switch driver { - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: return storetest.MakeSqlSettings(driver, false) - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: return storetest.MakeSqlSettings(driver, false) } @@ -667,9 +667,9 @@ func TestExecNoTimeout(t *testing.T) { defer func() { sqlStore.master.QueryTimeout = timeout }() - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { query = `SELECT SLEEP(2);` - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { query = `SELECT pg_sleep(2);` } _, err := sqlStore.GetMaster().ExecNoTimeout(query) @@ -678,7 +678,7 @@ func TestExecNoTimeout(t *testing.T) { } func TestMySQLReadTimeout(t *testing.T) { - settings := makeSqlSettings(model.DATABASE_DRIVER_MYSQL) + settings := makeSqlSettings(model.DatabaseDriverMysql) dataSource := *settings.DataSource config, err := mysql.ParseDSN(dataSource) require.NoError(t, err) @@ -741,13 +741,13 @@ func TestAlterDefaultIfColumnExists(t *testing.T) { ok := sqlStore.AlterDefaultIfColumnExists("Posts", "Id", model.NewString(""), model.NewString("")) require.True(t, ok) - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { query = `SELECT column_default FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'Posts' AND column_name = 'Id'` - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { query = `SELECT column_default FROM information_schema.columns WHERE table_name = 'posts' @@ -757,9 +757,9 @@ func TestAlterDefaultIfColumnExists(t *testing.T) { err := sqlStore.GetMaster().SelectOne(&def, query) require.NoError(t, err) require.NotNil(t, def) - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { require.Equal(t, "", *def) - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { require.Equal(t, "''::character varying", *def) } }) @@ -771,9 +771,9 @@ func TestAlterDefaultIfColumnExists(t *testing.T) { err := sqlStore.GetMaster().SelectOne(&def, query) require.NoError(t, err) require.NotNil(t, def) - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { require.Equal(t, "", *def) - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { require.Equal(t, "''::character varying", *def) } }) @@ -794,9 +794,9 @@ func TestAlterDefaultIfColumnExists(t *testing.T) { err := sqlStore.GetMaster().SelectOne(&def, query) require.NoError(t, err) require.NotNil(t, def) - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { require.Equal(t, "test", *def) - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { require.Equal(t, "'test'::character varying", *def) } @@ -808,13 +808,13 @@ func TestAlterDefaultIfColumnExists(t *testing.T) { ok := sqlStore.AlterDefaultIfColumnExists("Posts", "UpdateAt", model.NewString("0"), model.NewString("0")) require.True(t, ok) - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { query = `SELECT column_default FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'Posts' AND column_name = 'UpdateAt'` - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + } else if sqlStore.DriverName() == model.DatabaseDriverPostgres { query = `SELECT column_default FROM information_schema.columns WHERE table_name = 'posts' diff --git a/store/sqlstore/system_store.go b/store/sqlstore/system_store.go index b14c0c0549..aab3d48ecf 100644 --- a/store/sqlstore/system_store.go +++ b/store/sqlstore/system_store.go @@ -68,9 +68,9 @@ func (s SqlSystemStore) SaveOrUpdateWithWarnMetricHandling(system *model.System) } } - if strings.HasPrefix(system.Name, model.WARN_METRIC_STATUS_STORE_PREFIX) && (system.Value == model.WARN_METRIC_STATUS_RUNONCE || system.Value == model.WARN_METRIC_STATUS_LIMIT_REACHED) { - if err := s.SaveOrUpdate(&model.System{Name: model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY, Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10)}); err != nil { - return errors.Wrapf(err, "failed to save system property with name=%s", model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY) + if strings.HasPrefix(system.Name, model.WarnMetricStatusStorePrefix) && (system.Value == model.WarnMetricStatusRunonce || system.Value == model.WarnMetricStatusLimitReached) { + if err := s.SaveOrUpdate(&model.System{Name: model.SystemWarnMetricLastRunTimestampKey, Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10)}); err != nil { + return errors.Wrapf(err, "failed to save system property with name=%s", model.SystemWarnMetricLastRunTimestampKey) } } diff --git a/store/sqlstore/team_store.go b/store/sqlstore/team_store.go index db55ab9c96..115fb40f4b 100644 --- a/store/sqlstore/team_store.go +++ b/store/sqlstore/team_store.go @@ -105,11 +105,11 @@ func getTeamRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuestRol // them from ExplicitRoles field. for _, role := range roles { switch role { - case model.TEAM_GUEST_ROLE_ID: + case model.TeamGuestRoleId: result.schemeGuest = true - case model.TEAM_USER_ROLE_ID: + case model.TeamUserRoleId: result.schemeUser = true - case model.TEAM_ADMIN_ROLE_ID: + case model.TeamAdminRoleId: result.schemeAdmin = true default: result.explicitRoles = append(result.explicitRoles, role) @@ -124,21 +124,21 @@ func getTeamRoles(schemeGuest, schemeUser, schemeAdmin bool, defaultTeamGuestRol if defaultTeamGuestRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamGuestRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.TEAM_GUEST_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.TeamGuestRoleId) } } if result.schemeUser { if defaultTeamUserRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamUserRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.TEAM_USER_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.TeamUserRoleId) } } if result.schemeAdmin { if defaultTeamAdminRole != "" { schemeImpliedRoles = append(schemeImpliedRoles, defaultTeamAdminRole) } else { - schemeImpliedRoles = append(schemeImpliedRoles, model.TEAM_ADMIN_ROLE_ID) + schemeImpliedRoles = append(schemeImpliedRoles, model.TeamAdminRoleId) } } for _, impliedRole := range schemeImpliedRoles { @@ -400,7 +400,7 @@ func (s SqlTeamStore) teamSearchQuery(opts *model.TeamSearch, countQuery bool) s term = wildcardSearchTerm(term) operatorKeyword := "ILIKE" - if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + if s.DriverName() == model.DatabaseDriverMysql { operatorKeyword = "LIKE" } @@ -1264,11 +1264,11 @@ func (s SqlTeamStore) MigrateTeamMembers(fromTeamId string, fromUserId string) ( member.SchemeGuest = sql.NullBool{Bool: false, Valid: true} } for _, role := range roles { - if role == model.TEAM_ADMIN_ROLE_ID { + if role == model.TeamAdminRoleId { member.SchemeAdmin = sql.NullBool{Bool: true, Valid: true} - } else if role == model.TEAM_USER_ROLE_ID { + } else if role == model.TeamUserRoleId { member.SchemeUser = sql.NullBool{Bool: true, Valid: true} - } else if role == model.TEAM_GUEST_ROLE_ID { + } else if role == model.TeamGuestRoleId { member.SchemeGuest = sql.NullBool{Bool: true, Valid: true} } else { newRoles = append(newRoles, role) diff --git a/store/sqlstore/terms_of_service_store.go b/store/sqlstore/terms_of_service_store.go index 437bc96428..67628414a4 100644 --- a/store/sqlstore/terms_of_service_store.go +++ b/store/sqlstore/terms_of_service_store.go @@ -25,7 +25,7 @@ func newSqlTermsOfServiceStore(sqlStore *SqlStore, metrics einterfaces.MetricsIn table := db.AddTableWithName(model.TermsOfService{}, "TermsOfService").SetKeys(false, "Id") table.ColMap("Id").SetMaxSize(26) table.ColMap("UserId").SetMaxSize(26) - table.ColMap("Text").SetMaxSize(model.POST_MESSAGE_MAX_BYTES_V2) + table.ColMap("Text").SetMaxSize(model.PostMessageMaxBytesV2) } return s diff --git a/store/sqlstore/tokens_store.go b/store/sqlstore/tokens_store.go index 0d7ebdf1ac..b258bb3c2a 100644 --- a/store/sqlstore/tokens_store.go +++ b/store/sqlstore/tokens_store.go @@ -69,7 +69,7 @@ func (s SqlTokenStore) GetByToken(tokenString string) (*model.Token, error) { func (s SqlTokenStore) Cleanup() { mlog.Debug("Cleaning up token store.") - deltime := model.GetMillis() - model.MAX_TOKEN_EXIPRY_TIME + deltime := model.GetMillis() - model.MaxTokenExipryTime if _, err := s.GetMaster().Exec("DELETE FROM Tokens WHERE CreateAt < :DelTime", map[string]interface{}{"DelTime": deltime}); err != nil { mlog.Error("Unable to cleanup token store.") } diff --git a/store/sqlstore/upgrade.go b/store/sqlstore/upgrade.go index 24e704ac2f..ad303b7990 100644 --- a/store/sqlstore/upgrade.go +++ b/store/sqlstore/upgrade.go @@ -273,7 +273,7 @@ func upgradeDatabaseToVersion33(sqlStore *SqlStore) { if shouldPerformUpgrade(sqlStore, Version320, Version330) { if sqlStore.DoesColumnExist("Users", "ThemeProps") { params := map[string]interface{}{ - "Category": model.PREFERENCE_CATEGORY_THEME, + "Category": model.PreferenceCategoryTheme, "Name": "", } @@ -284,12 +284,12 @@ func upgradeDatabaseToVersion33(sqlStore *SqlStore) { defer finalizeTransaction(transaction) // increase size of Value column of Preferences table to match the size of the ThemeProps column - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { if _, err := transaction.ExecNoTimeout("ALTER TABLE Preferences ALTER COLUMN Value TYPE varchar(2000)"); err != nil { themeMigrationFailed(err) return } - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if sqlStore.DriverName() == model.DatabaseDriverMysql { if _, err := transaction.ExecNoTimeout("ALTER TABLE Preferences MODIFY Value text"); err != nil { themeMigrationFailed(err) return @@ -301,7 +301,7 @@ func upgradeDatabaseToVersion33(sqlStore *SqlStore) { `INSERT INTO Preferences(UserId, Category, Name, Value) SELECT - Id, '`+model.PREFERENCE_CATEGORY_THEME+`', '', ThemeProps + Id, '`+model.PreferenceCategoryTheme+`', '', ThemeProps FROM Users WHERE @@ -323,7 +323,7 @@ func upgradeDatabaseToVersion33(sqlStore *SqlStore) { // rename solarized_* code themes to solarized-* to match client changes in 3.0 var data model.Preferences - if _, err := sqlStore.GetMaster().Select(&data, "SELECT * FROM Preferences WHERE Category = '"+model.PREFERENCE_CATEGORY_THEME+"' AND Value LIKE '%solarized_%'"); err == nil { + if _, err := sqlStore.GetMaster().Select(&data, "SELECT * FROM Preferences WHERE Category = '"+model.PreferenceCategoryTheme+"' AND Value LIKE '%solarized_%'"); err == nil { for i := range data { data[i].Value = strings.Replace(data[i].Value, "solarized_", "solarized-", -1) } @@ -418,7 +418,7 @@ func upgradeDatabaseToVersion38(sqlStore *SqlStore) { func upgradeDatabaseToVersion39(sqlStore *SqlStore) { if shouldPerformUpgrade(sqlStore, Version380, Version390) { - sqlStore.CreateColumnIfNotExists("OAuthAccessData", "Scope", "varchar(128)", "varchar(128)", model.DEFAULT_SCOPE) + sqlStore.CreateColumnIfNotExists("OAuthAccessData", "Scope", "varchar(128)", "varchar(128)", model.DefaultScope) sqlStore.RemoveTableIfExists("PasswordRecovery") saveSchemaVersion(sqlStore, Version390) @@ -635,7 +635,7 @@ func upgradeDatabaseToVersion56(sqlStore *SqlStore) { // migrating user's accepted terms of service data into the new table sqlStore.GetMaster().ExecNoTimeout("INSERT INTO UserTermsOfService SELECT Id, AcceptedTermsOfServiceId as TermsOfServiceId, :CreateAt FROM Users WHERE AcceptedTermsOfServiceId != \"\" AND AcceptedTermsOfServiceId IS NOT NULL", map[string]interface{}{"CreateAt": model.GetMillis()}) - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { sqlStore.RemoveIndexIfExists("idx_users_email_lower", "lower(Email)") sqlStore.RemoveIndexIfExists("idx_users_username_lower", "lower(Username)") sqlStore.RemoveIndexIfExists("idx_users_nickname_lower", "lower(Nickname)") @@ -667,7 +667,7 @@ func upgradeDatabaseToVersion58(sqlStore *SqlStore) { sqlStore.AlterColumnTypeIfExists("IncomingWebhooks", "Description", "text", "VARCHAR(500)") sqlStore.AlterColumnTypeIfExists("OutgoingWebhooks", "IconURL", "text", "VARCHAR(1024)") sqlStore.RemoveDefaultIfColumnExists("OutgoingWebhooks", "Username") - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { sqlStore.RemoveDefaultIfColumnExists("OutgoingWebhooks", "IconURL") } sqlStore.AlterDefaultIfColumnExists("OutgoingWebhooks", "Username", model.NewString("NULL"), nil) @@ -751,9 +751,9 @@ func upgradeDatabaseToVersion515(sqlStore *SqlStore) { func upgradeDatabaseToVersion516(sqlStore *SqlStore) { if shouldPerformUpgrade(sqlStore, Version5150, Version5160) { - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { sqlStore.GetMaster().ExecNoTimeout("ALTER TABLE Tokens ALTER COLUMN Extra TYPE varchar(2048)") - } else if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if sqlStore.DriverName() == model.DatabaseDriverMysql { sqlStore.GetMaster().ExecNoTimeout("ALTER TABLE Tokens MODIFY Extra text") } saveSchemaVersion(sqlStore, Version5160) @@ -952,7 +952,7 @@ func upgradeDatabaseToVersion529(sqlStore *SqlStore) { sqlStore.CreateColumnIfNotExistsNoDefault("Threads", "ChannelId", "VARCHAR(26)", "VARCHAR(26)") updateThreadChannelsQuery := "UPDATE Threads INNER JOIN Posts ON Posts.Id=Threads.PostId SET Threads.ChannelId=Posts.ChannelId WHERE Threads.ChannelId IS NULL" - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { updateThreadChannelsQuery = "UPDATE Threads SET ChannelId=Posts.ChannelId FROM Posts WHERE Posts.Id=Threads.PostId AND Threads.ChannelId IS NULL" } if _, err := sqlStore.GetMaster().ExecNoTimeout(updateThreadChannelsQuery); err != nil { @@ -998,7 +998,7 @@ func hasMissingMigrationsVersion532(sqlStore *SqlStore) bool { return true } - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { if !sqlStore.IsVarchar(scIdInfo.DataType) || scIdInfo.CharMaximumLength != 300 { return true } @@ -1027,7 +1027,7 @@ func upgradeDatabaseToVersion532(sqlStore *SqlStore) { if hasMissingMigrationsVersion532(sqlStore) { // this migration was reverted on MySQL due to performance reasons. Doing // it only on PostgreSQL for the time being. - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { // allow 10 files per post sqlStore.AlterColumnTypeIfExists("Posts", "FileIds", "text", "varchar(300)") } @@ -1073,7 +1073,7 @@ func upgradeDatabaseToVersion535(sqlStore *SqlStore) { mlog.Error("Error updating RemoteId,ReqFileId in UploadsSession table", mlog.Err(err)) } uniquenessColumns := []string{"SiteUrl", "RemoteTeamId"} - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { uniquenessColumns = []string{"RemoteTeamId", "SiteUrl(168)"} } sqlStore.CreateUniqueCompositeIndexIfNotExists(RemoteClusterSiteURLUniqueIndex, "RemoteClusters", uniquenessColumns) @@ -1114,7 +1114,7 @@ func rootCountMigration(sqlStore *SqlStore) { ChannelMembers.MentionCount > 0 SET MentionCountRoot = ChannelMembers.MentionCount - q.UnreadMentions ` - if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if sqlStore.DriverName() == model.DatabaseDriverPostgres { updateMentionCountRootQuery = ` WITH q AS (` + mentionCountRootCTE + `) UPDATE channelmembers @@ -1137,7 +1137,7 @@ func rootCountMigration(sqlStore *SqlStore) { sqlStore.AlterDefaultIfColumnExists("ChannelMembers", "MsgCountRoot", model.NewString("0"), model.NewString("0")) forceIndex := "" - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { forceIndex = "FORCE INDEX(idx_posts_channel_id_update_at)" } totalMsgCountRootCTE := ` @@ -1158,7 +1158,7 @@ func rootCountMigration(sqlStore *SqlStore) { UPDATE ChannelMembers CM SET MsgCountRoot=TotalMsgCountRoot FROM q WHERE q.id=CM.ChannelId AND LastViewedAt >= q.lastrootpostat; ` - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { updateChannels = ` UPDATE Channels INNER Join (` + totalMsgCountRootCTE + `) as q @@ -1246,7 +1246,7 @@ func fixCRTThreadCountsAndUnreads(sqlStore *SqlStore) { UPDATE ThreadMemberships set LastViewed = q.CM_LastViewedAt + 1, UnreadMentions = 0, LastUpdated = :Now FROM q WHERE ThreadMemberships.Postid = q.PostId AND ThreadMemberships.UserId = q.UserId ` - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { updateThreadMembershipQuery = ` UPDATE ThreadMemberships INNER JOIN (` + threadMembershipsCTE + `) as q @@ -1280,7 +1280,7 @@ func fixCRTChannelMembershipCounts(sqlStore *SqlStore) { WHERE ChannelMembers.Channelid = Channels.Id AND ChannelMembers.LastViewedAt >= Channels.LastPostAt; ` - if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { + if sqlStore.DriverName() == model.DatabaseDriverMysql { channelMembershipsCountsAndMentions = ` UPDATE ChannelMembers INNER JOIN Channels on Channels.Id = ChannelMembers.ChannelId diff --git a/store/sqlstore/upgrade_test.go b/store/sqlstore/upgrade_test.go index 6459ae1b84..9284e7468a 100644 --- a/store/sqlstore/upgrade_test.go +++ b/store/sqlstore/upgrade_test.go @@ -146,7 +146,7 @@ func createChannelWithLastPostAt(ss store.Store, teamId, creatorId string, lastP m.CreatorId = creatorId m.DisplayName = "Name" m.Name = "zz" + model.NewId() + "b" - m.Type = model.CHANNEL_OPEN + m.Type = model.ChannelTypeOpen return ss.Channel().Save(&m, -1) } diff --git a/store/sqlstore/user_access_token_store.go b/store/sqlstore/user_access_token_store.go index 9717d5161b..d43bf0b542 100644 --- a/store/sqlstore/user_access_token_store.go +++ b/store/sqlstore/user_access_token_store.go @@ -71,9 +71,9 @@ func (s SqlUserAccessTokenStore) Delete(tokenId string) error { func (s SqlUserAccessTokenStore) deleteSessionsAndTokensById(transaction *gorp.Transaction, tokenId string) error { query := "" - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = "DELETE FROM Sessions s USING UserAccessTokens o WHERE o.Token = s.Token AND o.Id = :Id" - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { query = "DELETE s.* FROM Sessions s INNER JOIN UserAccessTokens o ON o.Token = s.Token WHERE o.Id = :Id" } @@ -112,9 +112,9 @@ func (s SqlUserAccessTokenStore) DeleteAllForUser(userId string) error { func (s SqlUserAccessTokenStore) deleteSessionsandTokensByUser(transaction *gorp.Transaction, userId string) error { query := "" - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = "DELETE FROM Sessions s USING UserAccessTokens o WHERE o.Token = s.Token AND o.UserId = :UserId" - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { query = "DELETE s.* FROM Sessions s INNER JOIN UserAccessTokens o ON o.Token = s.Token WHERE o.UserId = :UserId" } @@ -224,9 +224,9 @@ func (s SqlUserAccessTokenStore) UpdateTokenDisable(tokenId string) error { func (s SqlUserAccessTokenStore) deleteSessionsAndDisableToken(transaction *gorp.Transaction, tokenId string) error { query := "" - if s.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if s.DriverName() == model.DatabaseDriverPostgres { query = "DELETE FROM Sessions s USING UserAccessTokens o WHERE o.Token = s.Token AND o.Id = :Id" - } else if s.DriverName() == model.DATABASE_DRIVER_MYSQL { + } else if s.DriverName() == model.DatabaseDriverMysql { query = "DELETE s.* FROM Sessions s INNER JOIN UserAccessTokens o ON o.Token = s.Token WHERE o.Id = :Id" } diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index 17f31925ad..a93b48f04d 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -26,10 +26,10 @@ const ( ) var ( - UserSearchTypeNames_NO_FULL_NAME = []string{"Username", "Nickname"} - UserSearchTypeNames = []string{"Username", "FirstName", "LastName", "Nickname"} - UserSearchTypeAll_NO_FULL_NAME = []string{"Username", "Nickname", "Email"} - UserSearchTypeAll = []string{"Username", "FirstName", "LastName", "Nickname", "Email"} + UserSearchTypeNamesNoFullName = []string{"Username", "Nickname"} + UserSearchTypeNames = []string{"Username", "FirstName", "LastName", "Nickname"} + UserSearchTypeAllNoFullName = []string{"Username", "Nickname", "Email"} + UserSearchTypeAll = []string{"Username", "FirstName", "LastName", "Nickname", "Email"} ) type SqlUserStore struct { @@ -86,7 +86,7 @@ func (us SqlUserStore) createIndexesIfNotExists() { us.CreateIndexIfNotExists("idx_users_create_at", "Users", "CreateAt") us.CreateIndexIfNotExists("idx_users_delete_at", "Users", "DeleteAt") - if us.DriverName() == model.DATABASE_DRIVER_POSTGRES { + if us.DriverName() == model.DatabaseDriverPostgres { us.CreateIndexIfNotExists("idx_users_email_lower_textpattern", "Users", "lower(Email) text_pattern_ops") us.CreateIndexIfNotExists("idx_users_username_lower_textpattern", "Users", "lower(Username) text_pattern_ops") us.CreateIndexIfNotExists("idx_users_nickname_lower_textpattern", "Users", "lower(Nickname) text_pattern_ops") @@ -95,9 +95,9 @@ func (us SqlUserStore) createIndexesIfNotExists() { } us.CreateFullTextIndexIfNotExists("idx_users_all_txt", "Users", strings.Join(UserSearchTypeAll, ", ")) - us.CreateFullTextIndexIfNotExists("idx_users_all_no_full_name_txt", "Users", strings.Join(UserSearchTypeAll_NO_FULL_NAME, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_all_no_full_name_txt", "Users", strings.Join(UserSearchTypeAllNoFullName, ", ")) us.CreateFullTextIndexIfNotExists("idx_users_names_txt", "Users", strings.Join(UserSearchTypeNames, ", ")) - us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", strings.Join(UserSearchTypeNames_NO_FULL_NAME, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", strings.Join(UserSearchTypeNamesNoFullName, ", ")) } func (us SqlUserStore) Save(user *model.User) (*model.User, error) { @@ -464,7 +464,7 @@ func (us SqlUserStore) GetEtagForAllProfiles() string { } func (us SqlUserStore) GetAllProfiles(options *model.UserGetOptions) ([]*model.User, error) { - isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := us.DriverName() == model.DatabaseDriverPostgres query := us.usersQuery. OrderBy("u.Username ASC"). Offset(uint64(options.Page * options.PerPage)).Limit(uint64(options.PerPage)) @@ -519,10 +519,10 @@ func applyMultiRoleFilters(query sq.SelectBuilder, systemRoles []string, teamRol for _, role := range systemRoles { queryRole := wildcardSearchTerm(role) switch role { - case model.SYSTEM_USER_ROLE_ID: + case model.SystemUserRoleId: // If querying for a `system_user` ensure that the user is only a system_user. sqOr = append(sqOr, sq.Eq{"u.Roles": role}) - case model.SYSTEM_GUEST_ROLE_ID, model.SYSTEM_ADMIN_ROLE_ID, model.SYSTEM_USER_MANAGER_ROLE_ID, model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID, model.SYSTEM_MANAGER_ROLE_ID: + case model.SystemGuestRoleId, model.SystemAdminRoleId, model.SystemUserManagerRoleId, model.SystemReadOnlyAdminRoleId, model.SystemManagerRoleId: // If querying for any other roles search using a wildcard. if isPostgreSQL { sqOr = append(sqOr, sq.ILike{"u.Roles": queryRole}) @@ -537,19 +537,19 @@ func applyMultiRoleFilters(query sq.SelectBuilder, systemRoles []string, teamRol if len(channelRoles) > 0 && channelRoles[0] != "" { for _, channelRole := range channelRoles { switch channelRole { - case model.CHANNEL_ADMIN_ROLE_ID: + case model.ChannelAdminRoleId: if isPostgreSQL { - sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeAdmin": true}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeAdmin": true}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } else { - sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeAdmin": true}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeAdmin": true}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } - case model.CHANNEL_USER_ROLE_ID: + case model.ChannelUserRoleId: if isPostgreSQL { - sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeUser": true}, sq.Eq{"cm.SchemeAdmin": false}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeUser": true}, sq.Eq{"cm.SchemeAdmin": false}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } else { - sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeUser": true}, sq.Eq{"cm.SchemeAdmin": false}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"cm.SchemeUser": true}, sq.Eq{"cm.SchemeAdmin": false}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } - case model.CHANNEL_GUEST_ROLE_ID: + case model.ChannelGuestRoleId: sqOr = append(sqOr, sq.Eq{"cm.SchemeGuest": true}) } } @@ -558,19 +558,19 @@ func applyMultiRoleFilters(query sq.SelectBuilder, systemRoles []string, teamRol if len(teamRoles) > 0 && teamRoles[0] != "" { for _, teamRole := range teamRoles { switch teamRole { - case model.TEAM_ADMIN_ROLE_ID: + case model.TeamAdminRoleId: if isPostgreSQL { - sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeAdmin": true}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeAdmin": true}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } else { - sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeAdmin": true}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeAdmin": true}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } - case model.TEAM_USER_ROLE_ID: + case model.TeamUserRoleId: if isPostgreSQL { - sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeUser": true}, sq.Eq{"tm.SchemeAdmin": false}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeUser": true}, sq.Eq{"tm.SchemeAdmin": false}, sq.NotILike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } else { - sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeUser": true}, sq.Eq{"tm.SchemeAdmin": false}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SYSTEM_ADMIN_ROLE_ID)}}) + sqOr = append(sqOr, sq.And{sq.Eq{"tm.SchemeUser": true}, sq.Eq{"tm.SchemeAdmin": false}, sq.NotLike{"u.Roles": wildcardSearchTerm(model.SystemAdminRoleId)}}) } - case model.TEAM_GUEST_ROLE_ID: + case model.TeamGuestRoleId: sqOr = append(sqOr, sq.Eq{"tm.SchemeGuest": true}) } } @@ -639,7 +639,7 @@ func (us SqlUserStore) GetEtagForProfiles(teamId string) string { } func (us SqlUserStore) GetProfiles(options *model.UserGetOptions) ([]*model.User, error) { - isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := us.DriverName() == model.DatabaseDriverPostgres query := us.usersQuery. Join("TeamMembers tm ON ( tm.UserId = u.Id AND tm.DeleteAt = 0 )"). Where("tm.TeamId = ?", options.InTeamId). @@ -830,7 +830,7 @@ func (us SqlUserStore) GetProfilesNotInChannel(teamId string, channelId string, } func (us SqlUserStore) GetProfilesWithoutTeam(options *model.UserGetOptions) ([]*model.User, error) { - isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := us.DriverName() == model.DatabaseDriverPostgres query := us.usersQuery. Where(`( SELECT @@ -1018,7 +1018,7 @@ func (us SqlUserStore) GetProfileByGroupChannelIdsForUser(userId string, channel From("Users u"). Join("ChannelMembers cm ON u.Id = cm.UserId"). Join("Channels c ON cm.ChannelId = c.Id"). - Where(sq.Eq{"c.Type": model.CHANNEL_GROUP, "cm.ChannelId": channelIds}). + Where(sq.Eq{"c.Type": model.ChannelTypeGroup, "cm.ChannelId": channelIds}). Where(isMemberQuery). Where(sq.NotEq{"u.Id": userId}). OrderBy("u.Username ASC") @@ -1220,7 +1220,7 @@ func (us SqlUserStore) PermanentDelete(userId string) error { } func (us SqlUserStore) Count(options model.UserCountOptions) (int64, error) { - isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := us.DriverName() == model.DatabaseDriverPostgres query := us.getQueryBuilder().Select("COUNT(DISTINCT u.Id)").From("Users AS u") if !options.IncludeDeleted { @@ -1465,17 +1465,17 @@ func (us SqlUserStore) performSearch(query sq.SelectBuilder, term string, option if options.AllowFullNames { searchType = UserSearchTypeAll } else { - searchType = UserSearchTypeAll_NO_FULL_NAME + searchType = UserSearchTypeAllNoFullName } } else { if options.AllowFullNames { searchType = UserSearchTypeNames } else { - searchType = UserSearchTypeNames_NO_FULL_NAME + searchType = UserSearchTypeNamesNoFullName } } - isPostgreSQL := us.DriverName() == model.DATABASE_DRIVER_POSTGRES + isPostgreSQL := us.DriverName() == model.DatabaseDriverPostgres query = applyRoleFilter(query, options.Role, isPostgreSQL) query = applyMultiRoleFilters(query, options.Roles, options.TeamRoles, options.ChannelRoles, isPostgreSQL) @@ -1899,9 +1899,9 @@ func (us SqlUserStore) DemoteUserToGuest(userID string) (*model.User, error) { newRoles := []string{} for _, role := range roles { - if role == model.SYSTEM_USER_ROLE_ID { - newRoles = append(newRoles, model.SYSTEM_GUEST_ROLE_ID) - } else if role != model.SYSTEM_ADMIN_ROLE_ID { + if role == model.SystemUserRoleId { + newRoles = append(newRoles, model.SystemGuestRoleId) + } else if role != model.SystemAdminRoleId { newRoles = append(newRoles, role) } } diff --git a/store/storetest/channel_member_history_store.go b/store/storetest/channel_member_history_store.go index 60cfed58f6..9d918c88d3 100644 --- a/store/storetest/channel_member_history_store.go +++ b/store/storetest/channel_member_history_store.go @@ -30,7 +30,7 @@ func testLogJoinEvent(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(&ch, -1) require.NoError(t, err) @@ -56,7 +56,7 @@ func testLogLeaveEvent(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(&ch, -1) require.NoError(t, err) @@ -85,7 +85,7 @@ func testGetUsersInChannelAtChannelMemberHistory(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(ch, -1) require.NoError(t, err) @@ -181,7 +181,7 @@ func testGetUsersInChannelAtChannelMembers(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(channel, -1) require.NoError(t, err) @@ -293,7 +293,7 @@ func testPermanentDeleteBatch(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(channel, -1) require.NoError(t, err) @@ -353,14 +353,14 @@ func testPermanentDeleteBatchForRetentionPolicies(t *testing.T, ss store.Store) DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) userID := model.NewId() diff --git a/store/storetest/channel_store.go b/store/storetest/channel_store.go index cd6657eea4..1be65246f1 100644 --- a/store/storetest/channel_store.go +++ b/store/storetest/channel_store.go @@ -122,7 +122,7 @@ func testChannelStoreSave(t *testing.T, ss store.Store) { o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr, "couldn't save item", nErr) @@ -136,7 +136,7 @@ func testChannelStoreSave(t *testing.T, ss store.Store) { o1.Id = "" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect _, nErr = ss.Channel().Save(&o1, -1) require.Error(t, nErr, "should not be able to save direct channel") @@ -144,7 +144,7 @@ func testChannelStoreSave(t *testing.T, ss store.Store) { o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o1, -1) require.NoError(t, nErr, "should have saved channel") @@ -173,7 +173,7 @@ func testChannelStoreSaveDirectChannel(t *testing.T, ss store.Store, s SqlStore) o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect u1 := &model.User{} u1.Email = MakeEmail() @@ -228,7 +228,7 @@ func testChannelStoreSaveDirectChannel(t *testing.T, ss store.Store, s SqlStore) // Attempt to save a non-direct channel o1.Id = "" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr = ss.Channel().SaveDirectChannel(&o1, &m1, &m2) require.Error(t, nErr, "Should not be able to save non-direct channel") @@ -236,7 +236,7 @@ func testChannelStoreSaveDirectChannel(t *testing.T, ss store.Store, s SqlStore) o1.Id = "" o1.DisplayName = "Myself" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect _, nErr = ss.Channel().SaveDirectChannel(&o1, &m1, &m1) require.NoError(t, nErr, "couldn't save direct channel", nErr) @@ -282,7 +282,7 @@ func testChannelStoreUpdate(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -291,7 +291,7 @@ func testChannelStoreUpdate(t *testing.T, ss store.Store) { o2.TeamId = o1.TeamId o2.DisplayName = "Name" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -329,7 +329,7 @@ func testGetChannelUnread(t *testing.T, ss store.Store) { notifyPropsModel := model.GetDefaultChannelNotifyProps() // Setup Channel 1 - c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Downtown", Type: model.CHANNEL_OPEN, TotalMsgCount: 100, TotalMsgCountRoot: 99} + c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Downtown", Type: model.ChannelTypeOpen, TotalMsgCount: 100, TotalMsgCountRoot: 99} _, nErr = ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -338,7 +338,7 @@ func testGetChannelUnread(t *testing.T, ss store.Store) { require.NoError(t, err) // Setup Channel 2 - c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Cultural", Type: model.CHANNEL_OPEN, TotalMsgCount: 100, TotalMsgCountRoot: 100} + c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Cultural", Type: model.ChannelTypeOpen, TotalMsgCount: 100, TotalMsgCountRoot: 100} _, nErr = ss.Channel().Save(c2, -1) require.NoError(t, nErr) @@ -372,7 +372,7 @@ func testChannelStoreGet(t *testing.T, ss store.Store, s SqlStore) { o1.TeamId = model.NewId() o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -403,7 +403,7 @@ func testChannelStoreGet(t *testing.T, ss store.Store, s SqlStore) { o2.TeamId = model.NewId() o2.DisplayName = "Direct Name" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_DIRECT + o2.Type = model.ChannelTypeDirect m1 := model.ChannelMember{} m1.ChannelId = o2.Id @@ -443,7 +443,7 @@ func testChannelStoreGetChannelsByIds(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Name" o1.Name = "aa" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -467,13 +467,13 @@ func testChannelStoreGetChannelsByIds(t *testing.T, ss store.Store) { o2.TeamId = model.NewId() o2.DisplayName = "Direct Name" o2.Name = "bb" + model.NewId() + "b" - o2.Type = model.CHANNEL_DIRECT + o2.Type = model.ChannelTypeDirect o3 := model.Channel{} o3.TeamId = model.NewId() o3.DisplayName = "Deleted channel" o3.Name = "cc" + model.NewId() + "b" - o3.Type = model.CHANNEL_OPEN + o3.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) nErr = ss.Channel().Delete(o3.Id, 123) @@ -526,7 +526,7 @@ func testChannelStoreGetForPost(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o1, nErr := ss.Channel().Save(ch, -1) require.NoError(t, nErr) @@ -548,7 +548,7 @@ func testChannelStoreRestore(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -570,7 +570,7 @@ func testChannelStoreDelete(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -578,7 +578,7 @@ func testChannelStoreDelete(t *testing.T, ss store.Store) { o2.TeamId = o1.TeamId o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -586,7 +586,7 @@ func testChannelStoreDelete(t *testing.T, ss store.Store) { o3.TeamId = o1.TeamId o3.DisplayName = "Channel3" o3.Name = "zz" + model.NewId() + "b" - o3.Type = model.CHANNEL_OPEN + o3.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -594,7 +594,7 @@ func testChannelStoreDelete(t *testing.T, ss store.Store) { o4.TeamId = o1.TeamId o4.DisplayName = "Channel4" o4.Name = "zz" + model.NewId() + "b" - o4.Type = model.CHANNEL_OPEN + o4.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -649,7 +649,7 @@ func testChannelStoreGetByName(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -681,7 +681,7 @@ func testChannelStoreGetByNames(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -690,7 +690,7 @@ func testChannelStoreGetByNames(t *testing.T, ss store.Store) { TeamId: o1.TeamId, DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -736,7 +736,7 @@ func testChannelStoreGetDeletedByName(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(o1, -1) require.NoError(t, nErr) @@ -759,7 +759,7 @@ func testChannelStoreGetDeleted(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen userId := model.NewId() @@ -778,7 +778,7 @@ func testChannelStoreGetDeleted(t *testing.T, ss store.Store) { o2.TeamId = o1.TeamId o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -790,7 +790,7 @@ func testChannelStoreGetDeleted(t *testing.T, ss store.Store) { o3.TeamId = o1.TeamId o3.DisplayName = "Channel3" o3.Name = "zz" + model.NewId() + "b" - o3.Type = model.CHANNEL_OPEN + o3.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -817,7 +817,7 @@ func testChannelMemberStore(t *testing.T, ss store.Store) { c1.TeamId = model.NewId() c1.DisplayName = "NameName" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -930,7 +930,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -939,7 +939,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -1081,7 +1081,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -1090,7 +1090,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -1100,7 +1100,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -1242,7 +1242,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } cs, nErr := ss.Scheme().Save(cs) require.NoError(t, nErr) @@ -1251,7 +1251,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr = ss.Team().Save(team) @@ -1260,7 +1260,7 @@ func testChannelSaveMember(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, SchemeId: &cs.Id, }, -1) @@ -1429,7 +1429,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -1438,7 +1438,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -1594,7 +1594,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -1603,7 +1603,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -1613,7 +1613,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -1769,7 +1769,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } cs, nErr := ss.Scheme().Save(cs) require.NoError(t, nErr) @@ -1778,7 +1778,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr = ss.Team().Save(team) @@ -1787,7 +1787,7 @@ func testChannelSaveMultipleMembers(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, SchemeId: &cs.Id, }, -1) @@ -1957,7 +1957,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -1966,7 +1966,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -2110,7 +2110,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -2119,7 +2119,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -2129,7 +2129,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -2273,7 +2273,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } cs, nErr := ss.Scheme().Save(cs) require.NoError(t, nErr) @@ -2282,7 +2282,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr = ss.Team().Save(team) @@ -2291,7 +2291,7 @@ func testChannelUpdateMember(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, SchemeId: &cs.Id, }, -1) @@ -2462,7 +2462,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -2471,7 +2471,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -2622,7 +2622,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -2631,7 +2631,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -2641,7 +2641,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { channel := &model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, } channel, nErr = ss.Channel().Save(channel, -1) @@ -2792,7 +2792,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } cs, nErr := ss.Scheme().Save(cs) require.NoError(t, nErr) @@ -2801,7 +2801,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr = ss.Team().Save(team) @@ -2810,7 +2810,7 @@ func testChannelUpdateMultipleMembers(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "DisplayName", Name: "z-z-z" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: team.Id, SchemeId: &cs.Id, }, -1) @@ -3062,7 +3062,7 @@ func testChannelDeleteMemberStore(t *testing.T, ss store.Store) { c1.TeamId = model.NewId() c1.DisplayName = "NameName" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -3127,7 +3127,7 @@ func testChannelStoreGetChannels(t *testing.T, ss store.Store) { o1.TeamId = team o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3135,7 +3135,7 @@ func testChannelStoreGetChannels(t *testing.T, ss store.Store) { o2.TeamId = team o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -3143,7 +3143,7 @@ func testChannelStoreGetChannels(t *testing.T, ss store.Store) { o3.TeamId = team o3.DisplayName = "Channel3" o3.Name = "zz" + model.NewId() + "b" - o3.Type = model.CHANNEL_OPEN + o3.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -3266,7 +3266,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -3274,7 +3274,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { t2.DisplayName = "Name2" t2.Name = "zz" + model.NewId() t2.Email = MakeEmail() - t2.Type = model.TEAM_OPEN + t2.Type = model.TeamOpen _, err = ss.Team().Save(&t2) require.NoError(t, err) @@ -3282,7 +3282,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { c1.TeamId = t1.Id c1.DisplayName = "Channel1" + model.NewId() c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -3302,7 +3302,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { c2.TeamId = t1.Id c2.DisplayName = "Channel2" + model.NewId() c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&c2, -1) require.NoError(t, nErr) c2.DeleteAt = model.GetMillis() @@ -3314,7 +3314,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { c3.TeamId = t2.Id c3.DisplayName = "Channel3" + model.NewId() c3.Name = "zz" + model.NewId() + "b" - c3.Type = model.CHANNEL_PRIVATE + c3.Type = model.ChannelTypePrivate _, nErr = ss.Channel().Save(&c3, -1) require.NoError(t, nErr) @@ -3329,7 +3329,7 @@ func testChannelStoreGetAllChannels(t *testing.T, ss store.Store, s SqlStore) { c5.Name = model.GetGroupNameFromUserIds(userIds) c5.DisplayName = "GroupChannel" + model.NewId() c5.Name = "zz" + model.NewId() + "b" - c5.Type = model.CHANNEL_GROUP + c5.Type = model.ChannelTypeGroup _, nErr = ss.Channel().Save(&c5, -1) require.NoError(t, nErr) @@ -3417,7 +3417,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3441,7 +3441,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: otherTeamId, DisplayName: "Channel2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -3459,7 +3459,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -3469,7 +3469,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelB", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -3479,7 +3479,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelC", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o5, -1) require.NoError(t, nErr) @@ -3503,7 +3503,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelD", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o6, -1) require.NoError(t, nErr) @@ -3514,7 +3514,7 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelD", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o7, -1) require.NoError(t, nErr) @@ -3541,13 +3541,13 @@ func testChannelStoreGetMoreChannels(t *testing.T, ss store.Store) { }) t.Run("verify analytics for open channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypeOpen) require.NoError(t, err) require.EqualValues(t, 4, count) }) t.Run("verify analytics for private channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypePrivate) require.NoError(t, err) require.EqualValues(t, 2, count) }) @@ -3561,7 +3561,7 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "PrivateChannel1Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr := ss.Channel().Save(&p1, -1) require.NoError(t, nErr) @@ -3571,7 +3571,7 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "PrivateChannel1Team2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&p2, -1) require.NoError(t, nErr) @@ -3581,7 +3581,7 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "OpenChannel1Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3597,7 +3597,7 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "PrivateChannel2Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&p3, -1) require.NoError(t, nErr) @@ -3607,7 +3607,7 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "PrivateChannel3Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&p4, -1) require.NoError(t, nErr) @@ -3633,13 +3633,13 @@ func testChannelStoreGetPrivateChannelsForTeam(t *testing.T, ss store.Store) { }) t.Run("verify analytics for private channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypePrivate) require.NoError(t, err) require.EqualValues(t, 3, count) }) t.Run("verify analytics for open open channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypeOpen) require.NoError(t, err) require.EqualValues(t, 1, count) }) @@ -3653,7 +3653,7 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "OpenChannel1Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3663,7 +3663,7 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "OpenChannel1Team2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -3673,7 +3673,7 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "PrivateChannel1Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -3689,7 +3689,7 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "OpenChannel2Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -3699,7 +3699,7 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "OpenChannel3Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o5, -1) require.NoError(t, nErr) @@ -3725,13 +3725,13 @@ func testChannelStoreGetPublicChannelsForTeam(t *testing.T, ss store.Store) { }) t.Run("verify analytics for open channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypeOpen) require.NoError(t, err) require.EqualValues(t, 3, count) }) t.Run("verify analytics for private channels", func(t *testing.T) { - count, err := ss.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) + count, err := ss.Channel().AnalyticsTypeCount(teamId, model.ChannelTypePrivate) require.NoError(t, err) require.EqualValues(t, 1, count) }) @@ -3745,7 +3745,7 @@ func testChannelStoreGetPublicChannelsByIdsForTeam(t *testing.T, ss store.Store) TeamId: teamId, DisplayName: "OpenChannel1Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&oc1, -1) require.NoError(t, nErr) @@ -3755,7 +3755,7 @@ func testChannelStoreGetPublicChannelsByIdsForTeam(t *testing.T, ss store.Store) TeamId: model.NewId(), DisplayName: "OpenChannel2TeamOther", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&oc2, -1) require.NoError(t, nErr) @@ -3765,7 +3765,7 @@ func testChannelStoreGetPublicChannelsByIdsForTeam(t *testing.T, ss store.Store) TeamId: teamId, DisplayName: "PrivateChannel3Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&pc3, -1) require.NoError(t, nErr) @@ -3787,7 +3787,7 @@ func testChannelStoreGetPublicChannelsByIdsForTeam(t *testing.T, ss store.Store) TeamId: teamId, DisplayName: "OpenChannel4Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&oc4, -1) require.NoError(t, nErr) @@ -3797,7 +3797,7 @@ func testChannelStoreGetPublicChannelsByIdsForTeam(t *testing.T, ss store.Store) TeamId: teamId, DisplayName: "OpenChannel4Team1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&oc5, -1) require.NoError(t, nErr) @@ -3824,7 +3824,7 @@ func testChannelStoreGetChannelCounts(t *testing.T, ss store.Store) { o2.TeamId = model.NewId() o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -3832,7 +3832,7 @@ func testChannelStoreGetChannelCounts(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3868,7 +3868,7 @@ func testChannelStoreGetMembersForUser(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -3876,7 +3876,7 @@ func testChannelStoreGetMembersForUser(t *testing.T, ss store.Store) { o1.TeamId = t1.Id o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3884,7 +3884,7 @@ func testChannelStoreGetMembersForUser(t *testing.T, ss store.Store) { o2.TeamId = o1.TeamId o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -3936,7 +3936,7 @@ func testChannelStoreGetMembersForUser(t *testing.T, ss store.Store) { group := &model.Channel{ Name: model.GetGroupNameFromUserIds(userIds), DisplayName: "test", - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } var channel *model.Channel channel, nErr = ss.Channel().Save(group, 10000) @@ -3965,7 +3965,7 @@ func testChannelStoreGetMembersForUserWithPagination(t *testing.T, ss store.Stor t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -3973,7 +3973,7 @@ func testChannelStoreGetMembersForUserWithPagination(t *testing.T, ss store.Stor o1.TeamId = t1.Id o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -3981,7 +3981,7 @@ func testChannelStoreGetMembersForUserWithPagination(t *testing.T, ss store.Stor o2.TeamId = o1.TeamId o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -4098,7 +4098,7 @@ func testCountPostsAfter(t *testing.T, ss store.Store) { UserId: userId1, ChannelId: channelId, CreateAt: 1001, - Type: model.POST_JOIN_CHANNEL, + Type: model.PostTypeJoinChannel, }) require.NoError(t, err) @@ -4106,7 +4106,7 @@ func testCountPostsAfter(t *testing.T, ss store.Store) { UserId: userId1, ChannelId: channelId, CreateAt: 1002, - Type: model.POST_REMOVE_FROM_CHANNEL, + Type: model.PostTypeRemoveFromChannel, }) require.NoError(t, err) @@ -4114,7 +4114,7 @@ func testCountPostsAfter(t *testing.T, ss store.Store) { UserId: userId1, ChannelId: channelId, CreateAt: 1003, - Type: model.POST_LEAVE_TEAM, + Type: model.PostTypeLeaveTeam, }) require.NoError(t, err) @@ -4122,7 +4122,7 @@ func testCountPostsAfter(t *testing.T, ss store.Store) { UserId: userId1, ChannelId: channelId, CreateAt: 1004, - Type: model.POST_HEADER_CHANGE, + Type: model.PostTypeHeaderChange, }) require.NoError(t, err) @@ -4157,7 +4157,7 @@ func testChannelStoreUpdateLastViewedAt(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen o1.TotalMsgCount = 25 o1.LastPostAt = 12345 _, nErr := ss.Channel().Save(&o1, -1) @@ -4174,7 +4174,7 @@ func testChannelStoreUpdateLastViewedAt(t *testing.T, ss store.Store) { o2.TeamId = model.NewId() o2.DisplayName = "Channel1" o2.Name = "zz" + model.NewId() + "c" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen o2.TotalMsgCount = 26 o2.LastPostAt = 123456 _, nErr = ss.Channel().Save(&o2, -1) @@ -4217,7 +4217,7 @@ func testChannelStoreIncrementMentionCount(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "Channel1" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen o1.TotalMsgCount = 25 _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -4249,7 +4249,7 @@ func testUpdateChannelMember(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -4278,7 +4278,7 @@ func testGetMember(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -4287,7 +4287,7 @@ func testGetMember(t *testing.T, ss store.Store) { TeamId: c1.TeamId, DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(c2, -1) require.NoError(t, nErr) @@ -4340,7 +4340,7 @@ func testChannelStoreGetMemberForPost(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o1, nErr := ss.Channel().Save(ch, -1) @@ -4375,7 +4375,7 @@ func testGetMemberCount(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -4384,7 +4384,7 @@ func testGetMemberCount(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&c2, -1) require.NoError(t, nErr) @@ -4492,7 +4492,7 @@ func testGetMemberCountsByGroup(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -4695,7 +4695,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -4704,7 +4704,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&c2, -1) require.NoError(t, nErr) @@ -4713,7 +4713,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { u1 := &model.User{ Email: MakeEmail(), DeleteAt: 0, - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, } _, err := ss.User().Save(u1) require.NoError(t, err) @@ -4738,7 +4738,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { u2 := model.User{ Email: MakeEmail(), DeleteAt: 0, - Roles: model.SYSTEM_GUEST_ROLE_ID, + Roles: model.SystemGuestRoleId, } _, err := ss.User().Save(&u2) require.NoError(t, err) @@ -4763,7 +4763,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { u3 := model.User{ Email: MakeEmail(), DeleteAt: 0, - Roles: model.SYSTEM_GUEST_ROLE_ID, + Roles: model.SystemGuestRoleId, } _, err := ss.User().Save(&u3) require.NoError(t, err) @@ -4788,7 +4788,7 @@ func testGetGuestCount(t *testing.T, ss store.Store) { u4 := &model.User{ Email: MakeEmail(), DeleteAt: 10000, - Roles: model.SYSTEM_GUEST_ROLE_ID, + Roles: model.SystemGuestRoleId, } _, err := ss.User().Save(u4) require.NoError(t, err) @@ -4818,7 +4818,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -4843,7 +4843,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: otherTeamId, DisplayName: "Channel2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -4860,7 +4860,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -4869,7 +4869,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelB", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -4878,7 +4878,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelC", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o5, -1) require.NoError(t, nErr) @@ -4887,7 +4887,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Topic", Name: "off-topic", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o6, -1) require.NoError(t, nErr) @@ -4896,7 +4896,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Set", Name: "off-set", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o7, -1) require.NoError(t, nErr) @@ -4905,7 +4905,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Limit", Name: "off-limit", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o8, -1) require.NoError(t, nErr) @@ -4915,7 +4915,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { DisplayName: "Channel With Purpose", Purpose: "This can now be searchable!", Name: "with-purpose", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o9, -1) require.NoError(t, nErr) @@ -4924,7 +4924,7 @@ func testChannelStoreSearchMore(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA", Name: "channel-a-deleted", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o10, -1) require.NoError(t, nErr) @@ -5009,7 +5009,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -5018,7 +5018,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: otherTeamId, DisplayName: "ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -5051,7 +5051,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA (alternate)", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -5060,7 +5060,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel B", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -5069,7 +5069,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel C", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o5, -1) require.NoError(t, nErr) @@ -5078,7 +5078,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Topic", Name: "off-topic", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o6, -1) require.NoError(t, nErr) @@ -5087,7 +5087,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Set", Name: "off-set", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o7, -1) require.NoError(t, nErr) @@ -5096,7 +5096,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Off-Limit", Name: "off-limit", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o8, -1) require.NoError(t, nErr) @@ -5105,7 +5105,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Town Square", Name: "town-square", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o9, -1) require.NoError(t, nErr) @@ -5114,7 +5114,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "The", Name: "thename", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o10, -1) require.NoError(t, nErr) @@ -5123,7 +5123,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Native Mobile Apps", Name: "native-mobile-apps", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o11, -1) require.NoError(t, nErr) @@ -5133,7 +5133,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { DisplayName: "ChannelZ", Purpose: "This can now be searchable!", Name: "with-purpose", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o12, -1) require.NoError(t, nErr) @@ -5142,7 +5142,7 @@ func testChannelStoreSearchInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "ChannelA (deleted)", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o13, -1) require.NoError(t, nErr) @@ -5202,7 +5202,7 @@ func testChannelStoreSearchForUserInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "test-dev-1", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -5211,7 +5211,7 @@ func testChannelStoreSearchForUserInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "test-dev-2", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -5220,7 +5220,7 @@ func testChannelStoreSearchForUserInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "dev-3", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -5229,7 +5229,7 @@ func testChannelStoreSearchForUserInTeam(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "dev-4", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -5238,7 +5238,7 @@ func testChannelStoreSearchForUserInTeam(t *testing.T, ss store.Store) { TeamId: otherTeamId, DisplayName: "other-team-dev-5", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o5, -1) require.NoError(t, nErr) @@ -5305,7 +5305,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -5313,7 +5313,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { t2.DisplayName = "Name2" t2.Name = "zz" + model.NewId() t2.Email = MakeEmail() - t2.Type = model.TEAM_OPEN + t2.Type = model.TeamOpen _, err = ss.Team().Save(&t2) require.NoError(t, err) @@ -5321,7 +5321,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A1 ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -5330,7 +5330,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t2.Id, DisplayName: "A2 ChannelA", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -5363,7 +5363,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A3 ChannelA (alternate)", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -5372,7 +5372,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A4 ChannelB", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o4, -1) require.NoError(t, nErr) @@ -5381,7 +5381,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A5 ChannelC", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, GroupConstrained: model.NewBool(true), } _, nErr = ss.Channel().Save(&o5, -1) @@ -5391,7 +5391,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A6 Off-Topic", Name: "off-topic", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o6, -1) require.NoError(t, nErr) @@ -5400,7 +5400,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A7 Off-Set", Name: "off-set", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o7, -1) require.NoError(t, nErr) @@ -5421,7 +5421,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A8 Off-Limit", Name: "off-limit", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } _, nErr = ss.Channel().Save(&o8, -1) require.NoError(t, nErr) @@ -5430,7 +5430,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "A9 Town Square", Name: "town-square", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o9, -1) require.NoError(t, nErr) @@ -5439,7 +5439,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "B10 Which", Name: "which", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o10, -1) require.NoError(t, nErr) @@ -5448,7 +5448,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "B11 Native Mobile Apps", Name: "native-mobile-apps", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o11, -1) require.NoError(t, nErr) @@ -5458,7 +5458,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { DisplayName: "B12 ChannelZ", Purpose: "This can now be searchable!", Name: "with-purpose", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o12, -1) require.NoError(t, nErr) @@ -5467,7 +5467,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t1.Id, DisplayName: "B13 ChannelA (deleted)", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o13, -1) require.NoError(t, nErr) @@ -5481,7 +5481,7 @@ func testChannelStoreSearchAllChannels(t *testing.T, ss store.Store) { TeamId: t2.Id, DisplayName: "B14 FOOBARDISPLAYNAME", Name: "whatever", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o14, -1) require.NoError(t, nErr) @@ -5560,7 +5560,7 @@ func testChannelStoreGetMembersByIds(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "ChannelA" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -5596,7 +5596,7 @@ func testChannelStoreGetMembersByChannelIds(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) @@ -5604,7 +5604,7 @@ func testChannelStoreGetMembersByChannelIds(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) @@ -5681,7 +5681,7 @@ func testChannelStoreSearchGroupChannels(t *testing.T, ss store.Store) { gc1 := model.Channel{} gc1.Name = model.GetGroupNameFromUserIds(userIds) gc1.DisplayName = "GroupChannel" + model.NewId() - gc1.Type = model.CHANNEL_GROUP + gc1.Type = model.ChannelTypeGroup _, nErr := ss.Channel().Save(&gc1, -1) require.NoError(t, nErr) @@ -5698,7 +5698,7 @@ func testChannelStoreSearchGroupChannels(t *testing.T, ss store.Store) { gc2 := model.Channel{} gc2.Name = model.GetGroupNameFromUserIds(userIds) gc2.DisplayName = "GroupChannel" + model.NewId() - gc2.Type = model.CHANNEL_GROUP + gc2.Type = model.ChannelTypeGroup _, nErr = ss.Channel().Save(&gc2, -1) require.NoError(t, nErr) @@ -5715,7 +5715,7 @@ func testChannelStoreSearchGroupChannels(t *testing.T, ss store.Store) { gc3 := model.Channel{} gc3.Name = model.GetGroupNameFromUserIds(userIds) gc3.DisplayName = "GroupChannel" + model.NewId() - gc3.Type = model.CHANNEL_GROUP + gc3.Type = model.ChannelTypeGroup _, nErr = ss.Channel().Save(&gc3, -1) require.NoError(t, nErr) @@ -5805,7 +5805,7 @@ func testChannelStoreAnalyticsDeletedTypeCount(t *testing.T, ss store.Store) { o1.TeamId = model.NewId() o1.DisplayName = "ChannelA" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_OPEN + o1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -5813,7 +5813,7 @@ func testChannelStoreAnalyticsDeletedTypeCount(t *testing.T, ss store.Store) { o2.TeamId = model.NewId() o2.DisplayName = "Channel2" o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -5821,7 +5821,7 @@ func testChannelStoreAnalyticsDeletedTypeCount(t *testing.T, ss store.Store) { p3.TeamId = model.NewId() p3.DisplayName = "Channel3" p3.Name = "zz" + model.NewId() + "b" - p3.Type = model.CHANNEL_PRIVATE + p3.Type = model.ChannelTypePrivate _, nErr = ss.Channel().Save(&p3, -1) require.NoError(t, nErr) @@ -5885,7 +5885,7 @@ func testChannelStoreGetPinnedPosts(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o1, nErr := ss.Channel().Save(ch1, -1) @@ -5907,7 +5907,7 @@ func testChannelStoreGetPinnedPosts(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o2, nErr := ss.Channel().Save(ch2, -1) @@ -5971,7 +5971,7 @@ func testChannelStoreGetPinnedPostCount(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o1, nErr := ss.Channel().Save(ch1, -1) @@ -6001,7 +6001,7 @@ func testChannelStoreGetPinnedPostCount(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } o2, nErr := ss.Channel().Save(ch2, -1) @@ -6031,7 +6031,7 @@ func testChannelStoreMaxChannelsPerTeam(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Channel", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(channel, 0) assert.Error(t, nErr) @@ -6049,14 +6049,14 @@ func testChannelStoreGetChannelsByScheme(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s2 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s1, err := ss.Scheme().Save(s1) @@ -6069,7 +6069,7 @@ func testChannelStoreGetChannelsByScheme(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1.Id, } @@ -6077,7 +6077,7 @@ func testChannelStoreGetChannelsByScheme(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1.Id, } @@ -6085,7 +6085,7 @@ func testChannelStoreGetChannelsByScheme(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, _ = ss.Channel().Save(c1, 100) @@ -6114,7 +6114,7 @@ func testChannelStoreMigrateChannelMembers(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1, } c1, _ = ss.Channel().Save(c1, 100) @@ -6185,7 +6185,7 @@ func testResetAllChannelSchemes(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s1, err := ss.Scheme().Save(s1) require.NoError(t, err) @@ -6194,7 +6194,7 @@ func testResetAllChannelSchemes(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1.Id, } @@ -6202,7 +6202,7 @@ func testResetAllChannelSchemes(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &s1.Id, } @@ -6227,7 +6227,7 @@ func testChannelStoreClearAllCustomRoleAssignments(t *testing.T, ss store.Store) TeamId: model.NewId(), DisplayName: "Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c, _ = ss.Channel().Save(c, 100) @@ -6295,7 +6295,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { TeamId: teamId, DisplayName: "Open Channel", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr := ss.Channel().Save(&o1, -1) require.NoError(t, nErr) @@ -6305,7 +6305,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { TeamId: teamId, DisplayName: "Open Channel 2", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -6336,7 +6336,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { require.Equal(t, &model.ChannelList{&o2}, channels) }) - o2.Type = model.CHANNEL_PRIVATE + o2.Type = model.ChannelTypePrivate _, err := ss.Channel().Update(&o2) require.NoError(t, err) @@ -6346,7 +6346,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { require.Equal(t, &model.ChannelList{}, channels) }) - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, err = ss.Channel().Update(&o2) require.NoError(t, err) @@ -6362,7 +6362,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { TeamId: teamId, DisplayName: "Open Channel 3", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, execerr := s.GetMaster().ExecNoTimeout(` @@ -6417,7 +6417,7 @@ func testMaterializedPublicChannels(t *testing.T, ss store.Store, s SqlStore) { TeamId: teamId, DisplayName: "Open Channel 4", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } _, nErr = ss.Channel().Save(&o4, -1) @@ -6449,7 +6449,7 @@ func testChannelStoreGetAllChannelsForExportAfter(t *testing.T, ss store.Store) t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -6457,7 +6457,7 @@ func testChannelStoreGetAllChannelsForExportAfter(t *testing.T, ss store.Store) c1.TeamId = t1.Id c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -6481,7 +6481,7 @@ func testChannelStoreGetChannelMembersForExport(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -6489,7 +6489,7 @@ func testChannelStoreGetChannelMembersForExport(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -6497,7 +6497,7 @@ func testChannelStoreGetChannelMembersForExport(t *testing.T, ss store.Store) { c2.TeamId = model.NewId() c2.DisplayName = "Channel2" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(&c2, -1) require.NoError(t, nErr) @@ -6538,7 +6538,7 @@ func testChannelStoreRemoveAllDeactivatedMembers(t *testing.T, ss store.Store, s t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -6546,7 +6546,7 @@ func testChannelStoreRemoveAllDeactivatedMembers(t *testing.T, ss store.Store, s c1.TeamId = t1.Id c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -6622,7 +6622,7 @@ func testChannelStoreExportAllDirectChannels(t *testing.T, ss store.Store, s Sql o1.TeamId = teamId o1.DisplayName = "Name" + model.NewId() o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect userIds := []string{model.NewId(), model.NewId(), model.NewId()} @@ -6630,7 +6630,7 @@ func testChannelStoreExportAllDirectChannels(t *testing.T, ss store.Store, s Sql o2.Name = model.GetGroupNameFromUserIds(userIds) o2.DisplayName = "GroupChannel" + model.NewId() o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_GROUP + o2.Type = model.ChannelTypeGroup _, nErr := ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -6679,13 +6679,13 @@ func testChannelStoreExportAllDirectChannelsExcludePrivateAndPublic(t *testing.T o1.TeamId = teamId o1.DisplayName = "The Direct Channel" + model.NewId() o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect o2 := model.Channel{} o2.TeamId = teamId o2.DisplayName = "Channel2" + model.NewId() o2.Name = "zz" + model.NewId() + "b" - o2.Type = model.CHANNEL_OPEN + o2.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&o2, -1) require.NoError(t, nErr) @@ -6693,7 +6693,7 @@ func testChannelStoreExportAllDirectChannelsExcludePrivateAndPublic(t *testing.T o3.TeamId = teamId o3.DisplayName = "Channel3" + model.NewId() o3.Name = "zz" + model.NewId() + "b" - o3.Type = model.CHANNEL_PRIVATE + o3.Type = model.ChannelTypePrivate _, nErr = ss.Channel().Save(&o3, -1) require.NoError(t, nErr) @@ -6741,7 +6741,7 @@ func testChannelStoreExportAllDirectChannelsDeletedChannel(t *testing.T, ss stor o1.TeamId = teamId o1.DisplayName = "Different Name" + model.NewId() o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect u1 := &model.User{} u1.Email = MakeEmail() @@ -6789,7 +6789,7 @@ func testChannelStoreGetChannelsBatchForIndexing(t *testing.T, ss store.Store) { c1 := &model.Channel{} c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -6798,7 +6798,7 @@ func testChannelStoreGetChannelsBatchForIndexing(t *testing.T, ss store.Store) { c2 := &model.Channel{} c2.DisplayName = "Channel2" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(c2, -1) require.NoError(t, nErr) @@ -6808,21 +6808,21 @@ func testChannelStoreGetChannelsBatchForIndexing(t *testing.T, ss store.Store) { c3 := &model.Channel{} c3.DisplayName = "Channel3" c3.Name = "zz" + model.NewId() + "b" - c3.Type = model.CHANNEL_OPEN + c3.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(c3, -1) require.NoError(t, nErr) c4 := &model.Channel{} c4.DisplayName = "Channel4" c4.Name = "zz" + model.NewId() + "b" - c4.Type = model.CHANNEL_PRIVATE + c4.Type = model.ChannelTypePrivate _, nErr = ss.Channel().Save(c4, -1) require.NoError(t, nErr) c5 := &model.Channel{} c5.DisplayName = "Channel5" c5.Name = "zz" + model.NewId() + "b" - c5.Type = model.CHANNEL_OPEN + c5.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(c5, -1) require.NoError(t, nErr) @@ -6831,7 +6831,7 @@ func testChannelStoreGetChannelsBatchForIndexing(t *testing.T, ss store.Store) { c6 := &model.Channel{} c6.DisplayName = "Channel6" c6.Name = "zz" + model.NewId() + "b" - c6.Type = model.CHANNEL_OPEN + c6.Type = model.ChannelTypeOpen _, nErr = ss.Channel().Save(c6, -1) require.NoError(t, nErr) @@ -6858,7 +6858,7 @@ func testGroupSyncedChannelCount(t *testing.T, ss store.Store) { channel1, nErr := ss.Channel().Save(&model.Channel{ DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, GroupConstrained: model.NewBool(true), }, 999) require.NoError(t, nErr) @@ -6868,7 +6868,7 @@ func testGroupSyncedChannelCount(t *testing.T, ss store.Store) { channel2, nErr := ss.Channel().Save(&model.Channel{ DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, 999) require.NoError(t, nErr) require.False(t, channel2.IsGroupConstrained()) @@ -6893,7 +6893,7 @@ func testSetShared(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "test_share_flag", Name: "test_share_flag", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelSaved, err := ss.Channel().Save(channel, 999) require.NoError(t, err) @@ -6923,7 +6923,7 @@ func testGetTeamForChannel(t *testing.T, ss store.Store) { Name: "myteam", DisplayName: "DisplayName", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) @@ -6931,7 +6931,7 @@ func testGetTeamForChannel(t *testing.T, ss store.Store) { TeamId: team.Id, DisplayName: "test_share_flag", Name: "test_share_flag", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channelSaved, err := ss.Channel().Save(channel, 999) require.NoError(t, err) diff --git a/store/storetest/channel_store_categories.go b/store/storetest/channel_store_categories.go index e0370b9e04..0603b6498c 100644 --- a/store/storetest/channel_store_categories.go +++ b/store/storetest/channel_store_categories.go @@ -141,7 +141,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { // Set up two channels, one favorited and one not channel1, nErr := ss.Channel().Save(&model.Channel{ TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "channel1", }, 1000) require.NoError(t, nErr) @@ -154,7 +154,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { channel2, nErr := ss.Channel().Save(&model.Channel{ TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "channel2", }, 1000) require.NoError(t, nErr) @@ -168,7 +168,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { nErr = ss.Preference().Save(&model.Preferences{ { UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel1.Id, Value: "true", }, @@ -197,7 +197,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { // Set up two channels channel1, nErr := ss.Channel().Save(&model.Channel{ TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "channel1", DisplayName: "zebra", }, 1000) @@ -211,7 +211,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { channel2, nErr := ss.Channel().Save(&model.Channel{ TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "channel2", DisplayName: "aardvark", }, 1000) @@ -226,13 +226,13 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { nErr = ss.Preference().Save(&model.Preferences{ { UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel1.Id, Value: "true", }, { UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel2.Id, Value: "true", }, @@ -263,7 +263,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { dmChannel1, err := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId1), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -279,7 +279,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { dmChannel2, err := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId2), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -295,7 +295,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { err = ss.Preference().Save(&model.Preferences{ { UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: dmChannel1.Id, Value: "true", }, @@ -325,7 +325,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { // Set up a channel on another team and favorite it channel1, nErr := ss.Channel().Save(&model.Channel{ TeamId: teamId2, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: "channel1", }, 1000) require.NoError(t, nErr) @@ -339,7 +339,7 @@ func testCreateInitialSidebarCategories(t *testing.T, ss store.Store) { nErr = ss.Preference().Save(&model.Preferences{ { UserId: userId, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Name: channel1.Id, Value: "true", }, @@ -451,13 +451,13 @@ func testCreateSidebarCategory(t *testing.T, ss store.Store) { // Create some channels channel1, err := ss.Channel().Save(&model.Channel{ - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, Name: model.NewId(), }, 100) require.NoError(t, err) channel2, err := ss.Channel().Save(&model.Channel{ - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, Name: model.NewId(), }, 100) @@ -498,13 +498,13 @@ func testCreateSidebarCategory(t *testing.T, ss store.Store) { // Create some channels channel1, nErr := ss.Channel().Save(&model.Channel{ - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, Name: model.NewId(), }, 100) require.NoError(t, nErr) channel2, nErr := ss.Channel().Save(&model.Channel{ - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, Name: model.NewId(), }, 100) @@ -594,7 +594,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { Name: "channel1", DisplayName: "DEF", TeamId: teamId, - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, 10) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ @@ -608,7 +608,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { Name: "channel2", DisplayName: "ABC", TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 10) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ @@ -656,7 +656,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { channel1, nErr := ss.Channel().Save(&model.Channel{ Name: "abc", TeamId: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 10) require.NoError(t, nErr) defer ss.Channel().PermanentDelete(channel1.Id) @@ -698,7 +698,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { Name: "channel1", DisplayName: "DEF", TeamId: teamId, - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, 10) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ @@ -712,7 +712,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { Name: "channel2", DisplayName: "ABC", TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 10) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ @@ -759,7 +759,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -799,7 +799,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { gmChannel, nErr := ss.Channel().Save(&model.Channel{ Name: "abc", TeamId: "", - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, }, 10) require.NoError(t, nErr) defer ss.Channel().PermanentDelete(gmChannel.Id) @@ -838,7 +838,7 @@ func testGetSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -1060,7 +1060,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { // Join a channel channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -1080,7 +1080,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr := ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr := ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1097,7 +1097,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.Error(t, nErr) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) @@ -1124,7 +1124,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -1146,7 +1146,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr := ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr := ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1163,7 +1163,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) assert.Error(t, nErr) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) @@ -1201,7 +1201,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -1223,7 +1223,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr := ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr := ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1238,7 +1238,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { assert.NoError(t, err) assert.Equal(t, []string{dmChannel.Id}, updated[0].Channels) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1252,7 +1252,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) require.Error(t, nErr) assert.Nil(t, res2) @@ -1265,7 +1265,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, dmChannel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, dmChannel.Id) require.Error(t, nErr) assert.Nil(t, res2) }) @@ -1305,7 +1305,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { // Have both users join a channel channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -1335,12 +1335,12 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr := ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr := ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) - res2, nErr = ss.Preference().Get(userId2, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId2, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) @@ -1357,12 +1357,12 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) - res2, nErr = ss.Preference().Get(userId2, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId2, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1380,11 +1380,11 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) - res2, nErr = ss.Preference().Get(userId2, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId2, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.NoError(t, nErr) assert.NotNil(t, res2) assert.Equal(t, "true", res2.Value) @@ -1402,11 +1402,11 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { }) assert.NoError(t, err) - res2, nErr = ss.Preference().Get(userId, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) - res2, nErr = ss.Preference().Get(userId2, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id) + res2, nErr = ss.Preference().Get(userId2, model.PreferenceCategoryFavoriteChannel, channel.Id) assert.True(t, errors.Is(nErr, sql.ErrNoRows)) assert.Nil(t, res2) }) @@ -1418,7 +1418,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { // Create some channels channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -1433,7 +1433,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -1488,7 +1488,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { dmChannel, nErr := ss.Channel().SaveDirectChannel( &model.Channel{ Name: model.GetDMNameFromIds(userId, otherUserId), - Type: model.CHANNEL_DIRECT, + Type: model.ChannelTypeDirect, }, &model.ChannelMember{ UserId: userId, @@ -1577,7 +1577,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { // Join a channel channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -1641,7 +1641,7 @@ func testUpdateSidebarCategories(t *testing.T, ss store.Store) { // Join a channel channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -1734,7 +1734,7 @@ func testClearSidebarOnTeamLeave(t *testing.T, ss store.Store, s SqlStore) { channel1, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 1000) require.NoError(t, nErr) @@ -1782,7 +1782,7 @@ func testClearSidebarOnTeamLeave(t *testing.T, ss store.Store, s SqlStore) { channel1, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 1000) require.NoError(t, nErr) @@ -1844,7 +1844,7 @@ func testClearSidebarOnTeamLeave(t *testing.T, ss store.Store, s SqlStore) { channel1, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 1000) require.NoError(t, nErr) @@ -1860,7 +1860,7 @@ func testClearSidebarOnTeamLeave(t *testing.T, ss store.Store, s SqlStore) { channel2, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId2, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 1000) require.NoError(t, nErr) @@ -1936,7 +1936,7 @@ func testDeleteSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { channel1, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 1000) require.NoError(t, nErr) defer ss.Channel().PermanentDelete(channel1.Id) @@ -1944,7 +1944,7 @@ func testDeleteSidebarCategory(t *testing.T, ss store.Store, s SqlStore) { channel2, nErr := ss.Channel().Save(&model.Channel{ Name: model.NewId(), TeamId: teamId, - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, 1000) require.NoError(t, nErr) defer ss.Channel().PermanentDelete(channel2.Id) @@ -2023,7 +2023,7 @@ func testUpdateSidebarChannelsByPreferences(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamId, }, 10) require.NoError(t, nErr) @@ -2031,7 +2031,7 @@ func testUpdateSidebarChannelsByPreferences(t *testing.T, ss store.Store) { err := ss.Channel().UpdateSidebarChannelsByPreferences(&model.Preferences{ model.Preference{ Name: channel.Id, - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Value: "true", }, }) @@ -2050,7 +2050,7 @@ func testUpdateSidebarChannelsByPreferences(t *testing.T, ss store.Store) { _ = ss.Channel().UpdateSidebarChannelsByPreferences(&model.Preferences{ model.Preference{ Name: "fakeid", - Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, + Category: model.PreferenceCategoryFavoriteChannel, Value: "true", }, }) @@ -2068,7 +2068,7 @@ func testSidebarCategoryDeadlock(t *testing.T, ss store.Store) { // Join a channel channel, err := ss.Channel().Save(&model.Channel{ Name: "channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, TeamId: teamID, }, 10) require.NoError(t, err) diff --git a/store/storetest/command_store.go b/store/storetest/command_store.go index b2ecb2dfef..692980776c 100644 --- a/store/storetest/command_store.go +++ b/store/storetest/command_store.go @@ -28,7 +28,7 @@ func TestCommandStore(t *testing.T, ss store.Store) { func testCommandStoreSave(t *testing.T, ss store.Store) { o1 := model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -43,7 +43,7 @@ func testCommandStoreSave(t *testing.T, ss store.Store) { func testCommandStoreGet(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -64,7 +64,7 @@ func testCommandStoreGet(t *testing.T, ss store.Store) { func testCommandStoreGetByTeam(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -85,14 +85,14 @@ func testCommandStoreGetByTeam(t *testing.T, ss store.Store) { func testCommandStoreGetByTrigger(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger1" o2 := &model.Command{} o2.CreatorId = model.NewId() - o2.Method = model.COMMAND_METHOD_POST + o2.Method = model.CommandMethodPost o2.TeamId = model.NewId() o2.URL = "http://nowhere.com/" o2.Trigger = "trigger1" @@ -120,7 +120,7 @@ func testCommandStoreGetByTrigger(t *testing.T, ss store.Store) { func testCommandStoreDelete(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -144,7 +144,7 @@ func testCommandStoreDelete(t *testing.T, ss store.Store) { func testCommandStoreDeleteByTeam(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -168,7 +168,7 @@ func testCommandStoreDeleteByTeam(t *testing.T, ss store.Store) { func testCommandStoreDeleteByUser(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -192,7 +192,7 @@ func testCommandStoreDeleteByUser(t *testing.T, ss store.Store) { func testCommandStoreUpdate(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" @@ -214,7 +214,7 @@ func testCommandStoreUpdate(t *testing.T, ss store.Store) { func testCommandCount(t *testing.T, ss store.Store) { o1 := &model.Command{} o1.CreatorId = model.NewId() - o1.Method = model.COMMAND_METHOD_POST + o1.Method = model.CommandMethodPost o1.TeamId = model.NewId() o1.URL = "http://nowhere.com/" o1.Trigger = "trigger" diff --git a/store/storetest/command_webhook_store.go b/store/storetest/command_webhook_store.go index c879a8e5ad..3531bc9ab0 100644 --- a/store/storetest/command_webhook_store.go +++ b/store/storetest/command_webhook_store.go @@ -38,7 +38,7 @@ func testCommandWebhookStore(t *testing.T, ss store.Store) { require.True(t, errors.As(nErr, &nfErr), "Should have set the status as not found for missing id") h2 := &model.CommandWebhook{} - h2.CreateAt = model.GetMillis() - 2*model.COMMAND_WEBHOOK_LIFETIME + h2.CreateAt = model.GetMillis() - 2*model.CommandWebhookLifetime h2.CommandId = model.NewId() h2.UserId = model.NewId() h2.ChannelId = model.NewId() diff --git a/store/storetest/compliance_store.go b/store/storetest/compliance_store.go index 74d4cea9d5..43543ed1b6 100644 --- a/store/storetest/compliance_store.go +++ b/store/storetest/compliance_store.go @@ -60,28 +60,28 @@ func TestComplianceStore(t *testing.T, ss store.Store) { } func testComplianceStore(t *testing.T, ss store.Store) { - compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_FAILED, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC} + compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.ComplianceStatusFailed, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.ComplianceTypeAdhoc} _, err := ss.Compliance().Save(compliance1) require.NoError(t, err) time.Sleep(100 * time.Millisecond) - compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_RUNNING, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC} + compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.ComplianceStatusRunning, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.ComplianceTypeAdhoc} _, err = ss.Compliance().Save(compliance2) require.NoError(t, err) time.Sleep(100 * time.Millisecond) compliances, _ := ss.Compliance().GetAll(0, 1000) - require.Equal(t, model.COMPLIANCE_STATUS_RUNNING, compliances[0].Status) + require.Equal(t, model.ComplianceStatusRunning, compliances[0].Status) require.Equal(t, compliance2.Id, compliances[0].Id) - compliance2.Status = model.COMPLIANCE_STATUS_FAILED + compliance2.Status = model.ComplianceStatusFailed _, err = ss.Compliance().Update(compliance2) require.NoError(t, err) compliances, _ = ss.Compliance().GetAll(0, 1000) - require.Equal(t, model.COMPLIANCE_STATUS_FAILED, compliances[0].Status) + require.Equal(t, model.ComplianceStatusFailed, compliances[0].Status) require.Equal(t, compliance2.Id, compliances[0].Id) compliances, _ = ss.Compliance().GetAll(0, 1) @@ -106,7 +106,7 @@ func testComplianceExport(t *testing.T, ss store.Store) { t1.DisplayName = "DisplayName" t1.Name = "zz" + model.NewId() + "b" t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen t1, err := ss.Team().Save(t1) require.NoError(t, err) @@ -130,7 +130,7 @@ func testComplianceExport(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel2" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr = ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -235,7 +235,7 @@ func testComplianceExportDirectMessages(t *testing.T, ss store.Store) { t1.DisplayName = "DisplayName" t1.Name = "zz" + model.NewId() + "b" t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen t1, err := ss.Team().Save(t1) require.NoError(t, err) @@ -259,7 +259,7 @@ func testComplianceExportDirectMessages(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel2" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr = ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -403,7 +403,7 @@ func testMessageExportPublicChannel(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -438,7 +438,7 @@ func testMessageExportPublicChannel(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Public Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -507,7 +507,7 @@ func testMessageExportPrivateChannel(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -542,7 +542,7 @@ func testMessageExportPrivateChannel(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Private Channel", - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -613,7 +613,7 @@ func testMessageExportDirectMessageChannel(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -694,7 +694,7 @@ func testMessageExportGroupMessageChannel(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -740,7 +740,7 @@ func testMessageExportGroupMessageChannel(t *testing.T, ss store.Store) { groupMessageChannel := &model.Channel{ TeamId: team.Id, Name: model.NewId(), - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, } groupMessageChannel, nErr = ss.Channel().Save(groupMessageChannel, -1) require.NoError(t, nErr) @@ -791,7 +791,7 @@ func testEditExportMessage(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -814,7 +814,7 @@ func testEditExportMessage(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Public Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -883,7 +883,7 @@ func testEditAfterExportMessage(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -906,7 +906,7 @@ func testEditAfterExportMessage(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Public Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -994,7 +994,7 @@ func testDeleteExportMessage(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -1017,7 +1017,7 @@ func testDeleteExportMessage(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Public Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -1054,7 +1054,7 @@ func testDeleteExportMessage(t *testing.T, ss store.Store) { e := json.Unmarshal([]byte(*v.PostProps), &props) require.NoError(t, e) - _, ok := props[model.POST_PROPS_DELETE_BY] + _, ok := props[model.PostPropsDeleteBy] assert.True(t, ok) assert.Equal(t, post1.Message, *v.PostMessage) @@ -1079,7 +1079,7 @@ func testDeleteAfterExportMessage(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "zz" + model.NewId() + "b", Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err = ss.Team().Save(team) require.NoError(t, err) @@ -1102,7 +1102,7 @@ func testDeleteAfterExportMessage(t *testing.T, ss store.Store) { TeamId: team.Id, Name: model.NewId(), DisplayName: "Public Channel", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr = ss.Channel().Save(channel, -1) require.NoError(t, nErr) @@ -1157,7 +1157,7 @@ func testDeleteAfterExportMessage(t *testing.T, ss store.Store) { e := json.Unmarshal([]byte(*v.PostProps), &props) require.NoError(t, e) - _, ok := props[model.POST_PROPS_DELETE_BY] + _, ok := props[model.PostPropsDeleteBy] assert.True(t, ok) assert.Equal(t, post1.Message, *v.PostMessage) diff --git a/store/storetest/emoji_store.go b/store/storetest/emoji_store.go index dc35f704bb..aca1fa7eb9 100644 --- a/store/storetest/emoji_store.go +++ b/store/storetest/emoji_store.go @@ -223,14 +223,14 @@ func testEmojiGetList(t *testing.T, ss store.Store) { require.Truef(t, found, "failed to get emoji with id %v", emoji.Id) } - remojis, err := ss.Emoji().GetList(0, 3, model.EMOJI_SORT_BY_NAME) + remojis, err := ss.Emoji().GetList(0, 3, model.EmojiSortByName) assert.NoError(t, err) assert.Equal(t, 3, len(remojis)) assert.Equal(t, emojis[0].Name, remojis[0].Name) assert.Equal(t, emojis[1].Name, remojis[1].Name) assert.Equal(t, emojis[2].Name, remojis[2].Name) - remojis, err = ss.Emoji().GetList(1, 2, model.EMOJI_SORT_BY_NAME) + remojis, err = ss.Emoji().GetList(1, 2, model.EmojiSortByName) assert.NoError(t, err) assert.Equal(t, 2, len(remojis)) assert.Equal(t, emojis[1].Name, remojis[0].Name) diff --git a/store/storetest/file_info_store.go b/store/storetest/file_info_store.go index 2509af771b..2f48b3212c 100644 --- a/store/storetest/file_info_store.go +++ b/store/storetest/file_info_store.go @@ -357,7 +357,7 @@ func testFileInfoGetWithOptions(t *testing.T, ss store.Store) { PerPage: 10, Opt: &model.GetFileInfosOptions{ IncludeDeleted: true, - SortBy: model.FILEINFO_SORT_BY_CREATED, + SortBy: model.FileinfoSortByCreated, }, ExpectedFileIds: []string{file1_1.Id, file1_2.Id, file1_3.Id, file2_1.Id, file2_2.Id}, }, @@ -367,7 +367,7 @@ func testFileInfoGetWithOptions(t *testing.T, ss store.Store) { PerPage: 10, Opt: &model.GetFileInfosOptions{ UserIds: []string{userId1}, - SortBy: model.FILEINFO_SORT_BY_CREATED, + SortBy: model.FileinfoSortByCreated, SortDescending: true, }, ExpectedFileIds: []string{file1_3.Id, file1_2.Id, file1_1.Id}, @@ -378,7 +378,7 @@ func testFileInfoGetWithOptions(t *testing.T, ss store.Store) { PerPage: 3, Opt: &model.GetFileInfosOptions{ IncludeDeleted: true, - SortBy: model.FILEINFO_SORT_BY_CREATED, + SortBy: model.FileinfoSortByCreated, SortDescending: true, }, ExpectedFileIds: []string{file1_2.Id, file1_1.Id}, @@ -610,14 +610,14 @@ func testFileInfoStoreGetFilesBatchForIndexing(t *testing.T, ss store.Store) { c1.TeamId = model.NewId() c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, _ = ss.Channel().Save(c1, -1) c2 := &model.Channel{} c2.TeamId = model.NewId() c2.DisplayName = "Channel2" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen c2, _ = ss.Channel().Save(c2, -1) o1 := &model.Post{} diff --git a/store/storetest/group_store.go b/store/storetest/group_store.go index 499369bc00..187966a21f 100644 --- a/store/storetest/group_store.go +++ b/store/storetest/group_store.go @@ -702,7 +702,7 @@ func testGroupGetMemberUsersInTeam(t *testing.T, ss store.Store) { CompanyName: "Some company name", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err := ss.Team().Save(team) require.NoError(t, err) @@ -788,7 +788,7 @@ func testGroupGetMemberUsersNotInChannel(t *testing.T, ss store.Store) { CompanyName: "Some company name", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err := ss.Team().Save(team) require.NoError(t, err) @@ -839,7 +839,7 @@ func testGroupGetMemberUsersNotInChannel(t *testing.T, ss store.Store) { TeamId: team.Id, DisplayName: "Channel", Name: model.NewId(), - Type: model.CHANNEL_OPEN, // Query does not look at type so this shouldn't matter. + Type: model.ChannelTypeOpen, // Query does not look at type so this shouldn't matter. } channel, nErr := ss.Channel().Save(channel, 9999) require.NoError(t, nErr) @@ -1085,7 +1085,7 @@ func testCreateGroupSyncable(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(t1) require.NoError(t, nErr) @@ -1122,7 +1122,7 @@ func testGetGroupSyncable(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(t1) require.NoError(t, nErr) @@ -1170,7 +1170,7 @@ func testGetAllGroupSyncablesByGroup(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } var team *model.Team team, nErr := ss.Team().Save(t1) @@ -1222,7 +1222,7 @@ func testUpdateGroupSyncable(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(t1) require.NoError(t, nErr) @@ -1290,7 +1290,7 @@ func testDeleteGroupSyncable(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(t1) require.NoError(t, nErr) @@ -1357,7 +1357,7 @@ func testTeamMembersToAdd(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr = ss.Team().Save(team) require.NoError(t, nErr) @@ -1558,7 +1558,7 @@ func testTeamMembersToAddSingleTeam(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team1, nErr = ss.Team().Save(team1) require.NoError(t, nErr) @@ -1571,7 +1571,7 @@ func testTeamMembersToAddSingleTeam(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team2, nErr = ss.Team().Save(team2) require.NoError(t, nErr) @@ -1622,7 +1622,7 @@ func testChannelMembersToAdd(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, // Query does not look at type so this shouldn't matter. + Type: model.ChannelTypeOpen, // Query does not look at type so this shouldn't matter. } channel, nErr = ss.Channel().Save(channel, 9999) require.NoError(t, nErr) @@ -1820,7 +1820,7 @@ func testChannelMembersToAddSingleChannel(t *testing.T, ss store.Store) { channel1 := &model.Channel{ DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel1, nErr = ss.Channel().Save(channel1, 999) require.NoError(t, nErr) @@ -1828,7 +1828,7 @@ func testChannelMembersToAddSingleChannel(t *testing.T, ss store.Store) { channel2 := &model.Channel{ DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel2, nErr = ss.Channel().Save(channel2, 999) require.NoError(t, nErr) @@ -1957,7 +1957,7 @@ func testTeamMembersToRemoveSingleTeam(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, GroupConstrained: model.NewBool(true), } team1, nErr := ss.Team().Save(team1) @@ -1971,7 +1971,7 @@ func testTeamMembersToRemoveSingleTeam(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, GroupConstrained: model.NewBool(true), } team2, nErr = ss.Team().Save(team2) @@ -2104,7 +2104,7 @@ func testChannelMembersToRemoveSingleChannel(t *testing.T, ss store.Store) { channel1 := &model.Channel{ DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, GroupConstrained: model.NewBool(true), } channel1, nErr := ss.Channel().Save(channel1, 999) @@ -2113,7 +2113,7 @@ func testChannelMembersToRemoveSingleChannel(t *testing.T, ss store.Store) { channel2 := &model.Channel{ DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, GroupConstrained: model.NewBool(true), } channel2, nErr = ss.Channel().Save(channel2, 999) @@ -2206,7 +2206,7 @@ func pendingMemberRemovalsDataSetup(t *testing.T, ss store.Store) *removalsData TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, GroupConstrained: model.NewBool(true), } channelConstrained, nErr = ss.Channel().Save(channelConstrained, 9999) @@ -2216,7 +2216,7 @@ func pendingMemberRemovalsDataSetup(t *testing.T, ss store.Store) *removalsData TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channelUnconstrained, nErr = ss.Channel().Save(channelUnconstrained, 9999) require.NoError(t, nErr) @@ -2230,7 +2230,7 @@ func pendingMemberRemovalsDataSetup(t *testing.T, ss store.Store) *removalsData InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, GroupConstrained: model.NewBool(true), } teamConstrained, nErr = ss.Team().Save(teamConstrained) @@ -2244,7 +2244,7 @@ func pendingMemberRemovalsDataSetup(t *testing.T, ss store.Store) *removalsData InviteId: "inviteid1", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, } teamUnconstrained, nErr = ss.Team().Save(teamUnconstrained) require.NoError(t, nErr) @@ -2318,7 +2318,7 @@ func testGetGroupsByChannel(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Channel1", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel1, err := ss.Channel().Save(channel1, 9999) require.NoError(t, err) @@ -2368,7 +2368,7 @@ func testGetGroupsByChannel(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Channel2", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel2, nErr := ss.Channel().Save(channel2, 9999) require.NoError(t, nErr) @@ -2556,7 +2556,7 @@ func testGetGroupsAssociatedToChannelsByTeam(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team1, errt := ss.Team().Save(team1) require.NoError(t, errt) @@ -2566,7 +2566,7 @@ func testGetGroupsAssociatedToChannelsByTeam(t *testing.T, ss store.Store) { TeamId: team1.Id, DisplayName: "Channel1", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel1, err := ss.Channel().Save(channel1, 9999) require.NoError(t, err) @@ -2616,7 +2616,7 @@ func testGetGroupsAssociatedToChannelsByTeam(t *testing.T, ss store.Store) { TeamId: team1.Id, DisplayName: "Channel2", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel2, err = ss.Channel().Save(channel2, 9999) require.NoError(t, err) @@ -2799,7 +2799,7 @@ func testGetGroupsByTeam(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team1, err := ss.Team().Save(team1) require.NoError(t, err) @@ -2853,7 +2853,7 @@ func testGetGroupsByTeam(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, } team2, err = ss.Team().Save(team2) require.NoError(t, err) @@ -3045,7 +3045,7 @@ func testGetGroups(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, GroupConstrained: model.NewBool(true), } team1, err := ss.Team().Save(team1) @@ -3058,7 +3058,7 @@ func testGetGroups(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Channel1", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channel1, nErr := ss.Channel().Save(channel1, 9999) require.NoError(t, nErr) @@ -3112,7 +3112,7 @@ func testGetGroups(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, } team2, err = ss.Team().Save(team2) require.NoError(t, err) @@ -3122,7 +3122,7 @@ func testGetGroups(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "Channel2", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channel2, nErr = ss.Channel().Save(channel2, 9999) require.NoError(t, nErr) @@ -3132,7 +3132,7 @@ func testGetGroups(t *testing.T, ss store.Store) { TeamId: team1.Id, DisplayName: "Channel3", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channel3, nErr = ss.Channel().Save(channel3, 9999) require.NoError(t, nErr) @@ -3216,7 +3216,7 @@ func testGetGroups(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, } team3, err = ss.Team().Save(team3) require.NoError(t, err) @@ -3225,7 +3225,7 @@ func testGetGroups(t *testing.T, ss store.Store) { TeamId: team3.Id, DisplayName: "Channel4", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } channel4, nErr = ss.Channel().Save(channel4, 9999) require.NoError(t, nErr) @@ -3475,7 +3475,7 @@ func testTeamMembersMinusGroupMembers(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, GroupConstrained: model.NewBool(true), } team, err := ss.Team().Save(team) @@ -3627,7 +3627,7 @@ func testChannelMembersMinusGroupMembers(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, GroupConstrained: model.NewBool(true), } channel, err := ss.Channel().Save(channel, 9999) @@ -3855,7 +3855,7 @@ func groupTestAdminRoleGroupsForSyncableMemberChannel(t *testing.T, ss store.Sto TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr := ss.Channel().Save(channel, 9999) require.NoError(t, nErr) @@ -3942,7 +3942,7 @@ func groupTestAdminRoleGroupsForSyncableMemberTeam(t *testing.T, ss store.Store) team := &model.Team{ DisplayName: "A Name", Name: "zz" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } team, nErr := ss.Team().Save(team) require.NoError(t, nErr) @@ -4045,7 +4045,7 @@ func groupTestPermittedSyncableAdminsTeam(t *testing.T, ss store.Store) { team := &model.Team{ DisplayName: "A Name", Name: "zz" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } team, nErr := ss.Team().Save(team) require.NoError(t, nErr) @@ -4152,7 +4152,7 @@ func groupTestPermittedSyncableAdminsChannel(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, nErr := ss.Channel().Save(channel, 9999) require.NoError(t, nErr) @@ -4214,7 +4214,7 @@ func groupTestpUpdateMembersRoleTeam(t *testing.T, ss store.Store) { InviteId: "inviteid0", Name: "z-z-" + model.NewId() + "a", Email: "success+" + model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err := ss.Team().Save(team) require.NoError(t, err) @@ -4314,7 +4314,7 @@ func groupTestpUpdateMembersRoleChannel(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: "A Name", Name: model.NewId(), - Type: model.CHANNEL_OPEN, // Query does not look at type so this shouldn't matter. + Type: model.ChannelTypeOpen, // Query does not look at type so this shouldn't matter. } channel, err := ss.Channel().Save(channel, 9999) require.NoError(t, err) @@ -4455,7 +4455,7 @@ func groupTestGroupTeamCount(t *testing.T, ss store.Store) { InviteId: model.NewId(), Name: "zz" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) defer ss.Team().PermanentDelete(team.Id) @@ -4500,7 +4500,7 @@ func groupTestGroupChannelCount(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, 9999) require.NoError(t, err) defer ss.Channel().Delete(channel.Id, 0) diff --git a/store/storetest/job_store.go b/store/storetest/job_store.go index 1f0269f298..0449afa3c0 100644 --- a/store/storetest/job_store.go +++ b/store/storetest/job_store.go @@ -445,9 +445,9 @@ func testJobStoreGetCountByStatusAndType(t *testing.T, ss store.Store) { func testJobUpdateOptimistically(t *testing.T, ss store.Store) { job := &model.Job{ Id: model.NewId(), - Type: model.JOB_TYPE_DATA_RETENTION, + Type: model.JobTypeDataRetention, CreateAt: model.GetMillis(), - Status: model.JOB_STATUS_PENDING, + Status: model.JobStatusPending, } _, err := ss.Job().Save(job) @@ -455,18 +455,18 @@ func testJobUpdateOptimistically(t *testing.T, ss store.Store) { defer ss.Job().Delete(job.Id) job.LastActivityAt = model.GetMillis() - job.Status = model.JOB_STATUS_IN_PROGRESS + job.Status = model.JobStatusInProgress job.Progress = 50 job.Data = map[string]string{ "Foo": "Bar", } - updated, err := ss.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS) + updated, err := ss.Job().UpdateOptimistically(job, model.JobStatusSuccess) require.False(t, err != nil && updated) time.Sleep(2 * time.Millisecond) - updated, err = ss.Job().UpdateOptimistically(job, model.JOB_STATUS_PENDING) + updated, err = ss.Job().UpdateOptimistically(job, model.JobStatusPending) require.NoError(t, err) require.True(t, updated) @@ -484,9 +484,9 @@ func testJobUpdateOptimistically(t *testing.T, ss store.Store) { func testJobUpdateStatusUpdateStatusOptimistically(t *testing.T, ss store.Store) { job := &model.Job{ Id: model.NewId(), - Type: model.JOB_TYPE_DATA_RETENTION, + Type: model.JobTypeDataRetention, CreateAt: model.GetMillis(), - Status: model.JOB_STATUS_SUCCESS, + Status: model.JobStatusSuccess, } var lastUpdateAt int64 @@ -498,35 +498,35 @@ func testJobUpdateStatusUpdateStatusOptimistically(t *testing.T, ss store.Store) time.Sleep(2 * time.Millisecond) - received, err = ss.Job().UpdateStatus(job.Id, model.JOB_STATUS_PENDING) + received, err = ss.Job().UpdateStatus(job.Id, model.JobStatusPending) require.NoError(t, err) - require.Equal(t, model.JOB_STATUS_PENDING, received.Status) + require.Equal(t, model.JobStatusPending, received.Status) require.Greater(t, received.LastActivityAt, lastUpdateAt) lastUpdateAt = received.LastActivityAt time.Sleep(2 * time.Millisecond) - updated, err := ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS) + updated, err := ss.Job().UpdateStatusOptimistically(job.Id, model.JobStatusInProgress, model.JobStatusSuccess) require.NoError(t, err) require.False(t, updated) received, err = ss.Job().Get(job.Id) require.NoError(t, err) - require.Equal(t, model.JOB_STATUS_PENDING, received.Status) + require.Equal(t, model.JobStatusPending, received.Status) require.Equal(t, received.LastActivityAt, lastUpdateAt) time.Sleep(2 * time.Millisecond) - updated, err = ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS) + updated, err = ss.Job().UpdateStatusOptimistically(job.Id, model.JobStatusPending, model.JobStatusInProgress) require.NoError(t, err) require.True(t, updated, "should have succeeded") var startAtSet int64 received, err = ss.Job().Get(job.Id) require.NoError(t, err) - require.Equal(t, model.JOB_STATUS_IN_PROGRESS, received.Status) + require.Equal(t, model.JobStatusInProgress, received.Status) require.NotEqual(t, 0, received.StartAt) require.Greater(t, received.LastActivityAt, lastUpdateAt) lastUpdateAt = received.LastActivityAt @@ -534,13 +534,13 @@ func testJobUpdateStatusUpdateStatusOptimistically(t *testing.T, ss store.Store) time.Sleep(2 * time.Millisecond) - updated, err = ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS) + updated, err = ss.Job().UpdateStatusOptimistically(job.Id, model.JobStatusInProgress, model.JobStatusSuccess) require.NoError(t, err) require.True(t, updated, "should have succeeded") received, err = ss.Job().Get(job.Id) require.NoError(t, err) - require.Equal(t, model.JOB_STATUS_SUCCESS, received.Status) + require.Equal(t, model.JobStatusSuccess, received.Status) require.Equal(t, startAtSet, received.StartAt) require.Greater(t, received.LastActivityAt, lastUpdateAt) } diff --git a/store/storetest/link_metadata_store.go b/store/storetest/link_metadata_store.go index 16615754c4..09f35e549f 100644 --- a/store/storetest/link_metadata_store.go +++ b/store/storetest/link_metadata_store.go @@ -35,7 +35,7 @@ func testLinkMetadataStoreSave(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -62,7 +62,7 @@ func testLinkMetadataStoreSave(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -81,7 +81,7 @@ func testLinkMetadataStoreSave(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -100,7 +100,7 @@ func testLinkMetadataStoreSave(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -126,7 +126,7 @@ func testLinkMetadataStoreGet(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -144,7 +144,7 @@ func testLinkMetadataStoreGet(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -162,7 +162,7 @@ func testLinkMetadataStoreGet(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{}, } @@ -182,7 +182,7 @@ func testLinkMetadataStoreTypes(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_IMAGE, + Type: model.LinkMetadataTypeImage, Data: &model.PostImage{ Width: 123, Height: 456, @@ -215,7 +215,7 @@ func testLinkMetadataStoreTypes(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_OPENGRAPH, + Type: model.LinkMetadataTypeOpengraph, Data: og, } @@ -236,7 +236,7 @@ func testLinkMetadataStoreTypes(t *testing.T, ss store.Store) { metadata := &model.LinkMetadata{ URL: "http://example.com", Timestamp: getNextLinkMetadataTimestamp(), - Type: model.LINK_METADATA_TYPE_NONE, + Type: model.LinkMetadataTypeNone, Data: nil, } diff --git a/store/storetest/oauth_store.go b/store/storetest/oauth_store.go index b28ef20269..2ea74d156d 100644 --- a/store/storetest/oauth_store.go +++ b/store/storetest/oauth_store.go @@ -302,7 +302,7 @@ func testOAuthGetAuthorizedApps(t *testing.T, ss store.Store) { // allow the app p := model.Preference{} p.UserId = a1.CreatorId - p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP + p.Category = model.PreferenceCategoryAuthorizedOAuthApp p.Name = a1.Id p.Value = "true" nErr := ss.Preference().Save(&model.Preferences{p}) @@ -325,7 +325,7 @@ func testOAuthGetAccessDataByUserForApp(t *testing.T, ss store.Store) { // allow the app p := model.Preference{} p.UserId = a1.CreatorId - p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP + p.Category = model.PreferenceCategoryAuthorizedOAuthApp p.Name = a1.Id p.Value = "true" nErr := ss.Preference().Save(&model.Preferences{p}) diff --git a/store/storetest/post_store.go b/store/storetest/post_store.go index 1516234b88..6131421fcc 100644 --- a/store/storetest/post_store.go +++ b/store/storetest/post_store.go @@ -148,7 +148,7 @@ func testPostStoreSave(t *testing.T, ss store.Store) { channel := model.Channel{} channel.Name = "zz" + model.NewId() + "b" channel.DisplayName = "zz" + model.NewId() + "b" - channel.Type = model.CHANNEL_OPEN + channel.Type = model.ChannelTypeOpen _, err := ss.Channel().Save(&channel, 100) require.NoError(t, err) @@ -328,7 +328,7 @@ func testPostStoreSaveMultiple(t *testing.T, ss store.Store) { channel := model.Channel{} channel.Name = "zz" + model.NewId() + "b" channel.DisplayName = "zz" + model.NewId() + "b" - channel.Type = model.CHANNEL_OPEN + channel.Type = model.ChannelTypeOpen _, err := ss.Channel().Save(&channel, 100) require.NoError(t, err) @@ -360,7 +360,7 @@ func testPostStoreSaveMultiple(t *testing.T, ss store.Store) { } func testPostStoreSaveChannelMsgCounts(t *testing.T, ss store.Store) { - c1 := &model.Channel{Name: model.NewId(), DisplayName: "posttestchannel", Type: model.CHANNEL_OPEN} + c1 := &model.Channel{Name: model.NewId(), DisplayName: "posttestchannel", Type: model.ChannelTypeOpen} _, err := ss.Channel().Save(c1, 1000000) require.NoError(t, err) @@ -377,12 +377,12 @@ func testPostStoreSaveChannelMsgCounts(t *testing.T, ss store.Store) { assert.Equal(t, int64(1), c1.TotalMsgCount, "Message count should update by 1") o1.Id = "" - o1.Type = model.POST_ADD_TO_TEAM + o1.Type = model.PostTypeAddToTeam _, err = ss.Post().Save(&o1) require.NoError(t, err) o1.Id = "" - o1.Type = model.POST_REMOVE_FROM_TEAM + o1.Type = model.PostTypeRemoveFromTeam _, err = ss.Post().Save(&o1) require.NoError(t, err) @@ -634,9 +634,9 @@ func testPostStoreDelete(t *testing.T, ss store.Store) { posts, _ := ss.Post().GetPostsCreatedAt(o1.ChannelId, o1.CreateAt) post := posts[0] - actual := post.GetProp(model.POST_PROPS_DELETE_BY) + actual := post.GetProp(model.PostPropsDeleteBy) - assert.Equal(t, deleteByID, actual, "Expected (*Post).Props[model.POST_PROPS_DELETE_BY] to be %v but got %v.", deleteByID, actual) + assert.Equal(t, deleteByID, actual, "Expected (*Post).Props[model.PostPropsDeleteBy] to be %v but got %v.", deleteByID, actual) r3, err := ss.Post().Get(context.Background(), o1.Id, false, false, false, "") require.Error(t, err, "Missing id should have failed - PostList %v", r3) @@ -1595,7 +1595,7 @@ func testPostStoreGetPostBeforeAfter(t *testing.T, ss store.Store) { o1 := &model.Post{} o1.ChannelId = channelId - o1.Type = model.POST_JOIN_CHANNEL + o1.Type = model.PostTypeJoinChannel o1.UserId = model.NewId() o1.Message = "system_join_channel message" _, err = ss.Post().Save(o1) @@ -1690,7 +1690,7 @@ func testUserCountsWithPostsByDay(t *testing.T, ss store.Store) { t1.DisplayName = "DisplayName" t1.Name = "zz" + model.NewId() + "b" t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen t1, err := ss.Team().Save(t1) require.NoError(t, err) @@ -1698,7 +1698,7 @@ func testUserCountsWithPostsByDay(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel2" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -1749,7 +1749,7 @@ func testPostCountsByDay(t *testing.T, ss store.Store) { t1.DisplayName = "DisplayName" t1.Name = "zz" + model.NewId() + "b" t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen t1, err := ss.Team().Save(t1) require.NoError(t, err) @@ -1757,7 +1757,7 @@ func testPostCountsByDay(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel2" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, nErr := ss.Channel().Save(c1, -1) require.NoError(t, nErr) @@ -1886,7 +1886,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor c1.TeamId = model.NewId() c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, err := ss.Channel().Save(c1, -1) require.NoError(t, err) @@ -1926,7 +1926,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor c2 := &model.Channel{} c2.DisplayName = "DMChannel1" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_DIRECT + c2.Type = model.ChannelTypeDirect m1 := &model.ChannelMember{} m1.ChannelId = c2.Id @@ -1957,7 +1957,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor preferences := model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o1.Id, Value: "true", }, @@ -1973,7 +1973,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o2.Id, Value: "true", }, @@ -2001,7 +2001,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o3.Id, Value: "true", }, @@ -2017,7 +2017,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o4.Id, Value: "true", }, @@ -2036,7 +2036,7 @@ func testPostStoreGetFlaggedPostsForTeam(t *testing.T, ss store.Store, s SqlStor preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o5.Id, Value: "true", }, @@ -2085,7 +2085,7 @@ func testPostStoreGetFlaggedPosts(t *testing.T, ss store.Store) { preferences := model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o1.Id, Value: "true", }, @@ -2101,7 +2101,7 @@ func testPostStoreGetFlaggedPosts(t *testing.T, ss store.Store) { preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o2.Id, Value: "true", }, @@ -2129,7 +2129,7 @@ func testPostStoreGetFlaggedPosts(t *testing.T, ss store.Store) { preferences = model.Preferences{ { UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o3.Id, Value: "true", }, @@ -2184,7 +2184,7 @@ func testPostStoreGetFlaggedPostsForChannel(t *testing.T, ss store.Store) { preference := model.Preference{ UserId: o1.UserId, - Category: model.PREFERENCE_CATEGORY_FLAGGED_POST, + Category: model.PreferenceCategoryFlaggedPost, Name: o1.Id, Value: "true", } @@ -2556,14 +2556,14 @@ func testPostStoreGetPostsBatchForIndexing(t *testing.T, ss store.Store) { c1.TeamId = model.NewId() c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, _ = ss.Channel().Save(c1, -1) c2 := &model.Channel{} c2.TeamId = model.NewId() c2.DisplayName = "Channel2" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen c2, _ = ss.Channel().Save(c2, -1) o1 := &model.Post{} @@ -2613,14 +2613,14 @@ func testPostStorePermanentDeleteBatch(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) @@ -2753,14 +2753,14 @@ func testPostStorePermanentDeleteBatch(t *testing.T, ss store.Store) { c1.TeamId = model.NewId() c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c1, _ = ss.Channel().Save(c1, -1) c2 := &model.Channel{} c2.TeamId = model.NewId() c2.DisplayName = "Channel2" c2.Name = "zz" + model.NewId() + "b" - c2.Type = model.CHANNEL_OPEN + c2.Type = model.ChannelTypeOpen c2, _ = ss.Channel().Save(c2, -1) channelPolicy, err2 := ss.RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ @@ -2846,8 +2846,8 @@ func testPostStoreGetOldest(t *testing.T, ss store.Store) { } func testGetMaxPostSize(t *testing.T, ss store.Store) { - assert.Equal(t, model.POST_MESSAGE_MAX_RUNES_V2, ss.Post().GetMaxPostSize()) - assert.Equal(t, model.POST_MESSAGE_MAX_RUNES_V2, ss.Post().GetMaxPostSize()) + assert.Equal(t, model.PostMessageMaxRunesV2, ss.Post().GetMaxPostSize()) + assert.Equal(t, model.PostMessageMaxRunesV2, ss.Post().GetMaxPostSize()) } func testPostStoreGetParentsForExportAfter(t *testing.T, ss store.Store) { @@ -2855,7 +2855,7 @@ func testPostStoreGetParentsForExportAfter(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -2863,7 +2863,7 @@ func testPostStoreGetParentsForExportAfter(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -2904,7 +2904,7 @@ func testPostStoreGetRepliesForExport(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = "zz" + model.NewId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -2912,7 +2912,7 @@ func testPostStoreGetRepliesForExport(t *testing.T, ss store.Store) { c1.TeamId = t1.Id c1.DisplayName = "Channel1" c1.Name = "zz" + model.NewId() + "b" - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen _, nErr := ss.Channel().Save(&c1, -1) require.NoError(t, nErr) @@ -2974,7 +2974,7 @@ func testPostStoreGetDirectPostParentsForExportAfter(t *testing.T, ss store.Stor o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect u1 := &model.User{} u1.Email = MakeEmail() @@ -3028,7 +3028,7 @@ func testPostStoreGetDirectPostParentsForExportAfterDeleted(t *testing.T, ss sto o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect u1 := &model.User{} u1.DeleteAt = 1 @@ -3094,7 +3094,7 @@ func testPostStoreGetDirectPostParentsForExportAfterBatched(t *testing.T, ss sto o1.TeamId = teamId o1.DisplayName = "Name" o1.Name = "zz" + model.NewId() + "b" - o1.Type = model.CHANNEL_DIRECT + o1.Type = model.ChannelTypeDirect var postIds []string for i := 0; i < 150; i++ { @@ -3188,7 +3188,7 @@ func testHasAutoResponsePostByUserSince(t *testing.T, ss store.Store) { ChannelId: channelId, UserId: userId, Message: "auto response message", - Type: model.POST_AUTO_RESPONDER, + Type: model.PostTypeAutoResponder, }) require.NoError(t, err) time.Sleep(time.Millisecond) diff --git a/store/storetest/preference_store.go b/store/storetest/preference_store.go index 2c8d38b07d..bb5054012e 100644 --- a/store/storetest/preference_store.go +++ b/store/storetest/preference_store.go @@ -31,13 +31,13 @@ func testPreferenceSave(t *testing.T, ss store.Store) { preferences := model.Preferences{ { UserId: id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: model.NewId(), Value: "value1a", }, { UserId: id, - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: model.NewId(), Value: "value1b", }, @@ -63,7 +63,7 @@ func testPreferenceSave(t *testing.T, ss store.Store) { func testPreferenceGet(t *testing.T, ss store.Store) { userId := model.NewId() - category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW + category := model.PreferenceCategoryDirectChannelShow name := model.NewId() preferences := model.Preferences{ @@ -103,7 +103,7 @@ func testPreferenceGet(t *testing.T, ss store.Store) { func testPreferenceGetCategory(t *testing.T, ss store.Store) { userId := model.NewId() - category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW + category := model.PreferenceCategoryDirectChannelShow name := model.NewId() preferences := model.Preferences{ @@ -152,7 +152,7 @@ func testPreferenceGetCategory(t *testing.T, ss store.Store) { func testPreferenceGetAll(t *testing.T, ss store.Store) { userId := model.NewId() - category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW + category := model.PreferenceCategoryDirectChannelShow name := model.NewId() preferences := model.Preferences{ @@ -196,7 +196,7 @@ func testPreferenceGetAll(t *testing.T, ss store.Store) { func testPreferenceDeleteByUser(t *testing.T, ss store.Store) { userId := model.NewId() - category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW + category := model.PreferenceCategoryDirectChannelShow name := model.NewId() preferences := model.Preferences{ @@ -235,7 +235,7 @@ func testPreferenceDeleteByUser(t *testing.T, ss store.Store) { func testPreferenceDelete(t *testing.T, ss store.Store) { preference := model.Preference{ UserId: model.NewId(), - Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, + Category: model.PreferenceCategoryDirectChannelShow, Name: model.NewId(), Value: "value1a", } @@ -336,17 +336,17 @@ func testPreferenceDeleteOrphanedRows(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) - category := model.PREFERENCE_CATEGORY_FLAGGED_POST + category := model.PreferenceCategoryFlaggedPost userId := model.NewId() olderPost, err := ss.Post().Save(&model.Post{ diff --git a/store/storetest/reaction_store.go b/store/storetest/reaction_store.go index c331ce65c8..57870a118e 100644 --- a/store/storetest/reaction_store.go +++ b/store/storetest/reaction_store.go @@ -391,13 +391,13 @@ func forceUpdateAt(reaction *model.Reaction, updateAt int64, s SqlStore) error { } sqlResult, err := s.GetMaster().Exec(` - UPDATE - Reactions - SET - UpdateAt=:UpdateAt - WHERE - UserId = :UserId AND - PostId = :PostId AND + UPDATE + Reactions + SET + UpdateAt=:UpdateAt + WHERE + UserId = :UserId AND + PostId = :PostId AND EmojiName = :EmojiName`, params, ) @@ -527,14 +527,14 @@ func testReactionStorePermanentDeleteBatch(t *testing.T, ss store.Store) { DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) olderPost, err := ss.Post().Save(&model.Post{ diff --git a/store/storetest/retention_policy_store.go b/store/storetest/retention_policy_store.go index fc6f08eb16..4970f3a24b 100644 --- a/store/storetest/retention_policy_store.go +++ b/store/storetest/retention_policy_store.go @@ -116,7 +116,7 @@ func createChannelsForRetentionPolicy(t *testing.T, ss store.Store, teamId strin TeamId: teamId, DisplayName: "Channel " + name, Name: name, - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } channel, err := ss.Channel().Save(channel, -1) require.NoError(t, err) @@ -132,7 +132,7 @@ func createTeamsForRetentionPolicy(t *testing.T, ss store.Store, numTeams int) ( team := &model.Team{ DisplayName: "Team " + name, Name: name, - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, err := ss.Team().Save(team) require.NoError(t, err) diff --git a/store/storetest/role_store.go b/store/storetest/role_store.go index 8fb4cdd107..fe076ac2b5 100644 --- a/store/storetest/role_store.go +++ b/store/storetest/role_store.go @@ -368,7 +368,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } teamScheme1, err := ss.Scheme().Save(teamScheme1) require.NoError(t, err) @@ -378,7 +378,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } teamScheme2, err = ss.Scheme().Save(teamScheme2) require.NoError(t, err) @@ -388,7 +388,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } channelScheme1, err = ss.Scheme().Save(channelScheme1) require.NoError(t, err) @@ -398,7 +398,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } channelScheme2, err = ss.Scheme().Save(channelScheme2) require.NoError(t, err) @@ -408,7 +408,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &teamScheme1.Id, } team1, err = ss.Team().Save(team1) @@ -419,7 +419,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &teamScheme2.Id, } team2, err = ss.Team().Save(team2) @@ -430,7 +430,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { TeamId: team1.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &channelScheme1.Id, } channel1, nErr := ss.Channel().Save(channel1, -1) @@ -441,7 +441,7 @@ func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { TeamId: team2.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &channelScheme2.Id, } channel2, nErr = ss.Channel().Save(channel2, -1) @@ -522,7 +522,7 @@ func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *t DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } teamScheme, err := ss.Scheme().Save(teamScheme) require.NoError(t, err) @@ -532,7 +532,7 @@ func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *t DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } channelScheme, err = ss.Scheme().Save(channelScheme) require.NoError(t, err) @@ -542,7 +542,7 @@ func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *t DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &teamScheme.Id, } team, err = ss.Team().Save(team) @@ -553,7 +553,7 @@ func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *t TeamId: team.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &channelScheme.Id, } channel, nErr := ss.Channel().Save(channel, -1) @@ -568,7 +568,7 @@ func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *t teamSchemeUserRole, err := ss.Role().GetByName(context.Background(), teamScheme.DefaultChannelUserRole) require.NoError(t, err) - teamSchemeUserRole.Permissions = []string{model.PERMISSION_UPLOAD_FILE.Id} + teamSchemeUserRole.Permissions = []string{model.PermissionUploadFile.Id} _, err = ss.Role().Save(teamSchemeUserRole) require.NoError(t, err) diff --git a/store/storetest/scheme_store.go b/store/storetest/scheme_store.go index 52a1d80239..811e641ad1 100644 --- a/store/storetest/scheme_store.go +++ b/store/storetest/scheme_store.go @@ -29,54 +29,54 @@ func TestSchemeStore(t *testing.T, ss store.Store) { func createDefaultRoles(ss store.Store) { ss.Role().Save(&model.Role{ - Name: model.TEAM_ADMIN_ROLE_ID, - DisplayName: model.TEAM_ADMIN_ROLE_ID, + Name: model.TeamAdminRoleId, + DisplayName: model.TeamAdminRoleId, Permissions: []string{ - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + model.PermissionDeleteOthersPosts.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.TEAM_USER_ROLE_ID, - DisplayName: model.TEAM_USER_ROLE_ID, + Name: model.TeamUserRoleId, + DisplayName: model.TeamUserRoleId, Permissions: []string{ - model.PERMISSION_VIEW_TEAM.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + model.PermissionViewTeam.Id, + model.PermissionAddUserToTeam.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.TEAM_GUEST_ROLE_ID, - DisplayName: model.TEAM_GUEST_ROLE_ID, + Name: model.TeamGuestRoleId, + DisplayName: model.TeamGuestRoleId, Permissions: []string{ - model.PERMISSION_VIEW_TEAM.Id, + model.PermissionViewTeam.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_ADMIN_ROLE_ID, - DisplayName: model.CHANNEL_ADMIN_ROLE_ID, + Name: model.ChannelAdminRoleId, + DisplayName: model.ChannelAdminRoleId, Permissions: []string{ - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + model.PermissionManagePublicChannelMembers.Id, + model.PermissionManagePrivateChannelMembers.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_USER_ROLE_ID, - DisplayName: model.CHANNEL_USER_ROLE_ID, + Name: model.ChannelUserRoleId, + DisplayName: model.ChannelUserRoleId, Permissions: []string{ - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_CREATE_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionCreatePost.Id, }, }) ss.Role().Save(&model.Role{ - Name: model.CHANNEL_GUEST_ROLE_ID, - DisplayName: model.CHANNEL_GUEST_ROLE_ID, + Name: model.ChannelGuestRoleId, + DisplayName: model.ChannelGuestRoleId, Permissions: []string{ - model.PERMISSION_READ_CHANNEL.Id, - model.PERMISSION_CREATE_POST.Id, + model.PermissionReadChannel.Id, + model.PermissionCreatePost.Id, }, }) } @@ -87,7 +87,7 @@ func testSchemeStoreSave(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } // Check all fields saved correctly. @@ -165,7 +165,7 @@ func testSchemeStoreSave(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } _, err = ss.Scheme().Save(s3) @@ -178,7 +178,7 @@ func testSchemeStoreGet(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } d1, err := ss.Scheme().Save(s1) @@ -214,7 +214,7 @@ func testSchemeStoreGetByName(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } d1, err := ss.Scheme().Save(s1) @@ -251,25 +251,25 @@ func testSchemeStoreGetAllPage(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }, { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }, { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, }, { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, }, } @@ -315,7 +315,7 @@ func testSchemeStoreDelete(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } // Check all fields saved correctly. @@ -406,7 +406,7 @@ func testSchemeStoreDelete(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } d4, err := ss.Scheme().Save(s4) assert.NoError(t, err) @@ -415,7 +415,7 @@ func testSchemeStoreDelete(t *testing.T, ss store.Store) { Name: "xx" + model.NewId(), DisplayName: model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &d4.Id, } t4, err = ss.Team().Save(t4) @@ -433,7 +433,7 @@ func testSchemeStoreDelete(t *testing.T, ss store.Store) { DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } d5, err := ss.Scheme().Save(s5) assert.NoError(t, err) @@ -442,7 +442,7 @@ func testSchemeStoreDelete(t *testing.T, ss store.Store) { TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, SchemeId: &d5.Id, } c5, nErr := ss.Channel().Save(c5, -1) @@ -461,14 +461,14 @@ func testSchemeStorePermanentDeleteAll(t *testing.T, ss store.Store) { Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s2 := &model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), - Scope: model.SCHEME_SCOPE_CHANNEL, + Scope: model.SchemeScopeChannel, } s1, err := ss.Scheme().Save(s1) @@ -492,11 +492,11 @@ func testSchemeStorePermanentDeleteAll(t *testing.T, ss store.Store) { func testSchemeStoreCountByScope(t *testing.T, ss store.Store) { testCounts := func(expectedTeamCount, expectedChannelCount int) { - actualCount, err := ss.Scheme().CountByScope(model.SCHEME_SCOPE_TEAM) + actualCount, err := ss.Scheme().CountByScope(model.SchemeScopeTeam) require.NoError(t, err) require.Equal(t, int64(expectedTeamCount), actualCount) - actualCount, err = ss.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL) + actualCount, err = ss.Scheme().CountByScope(model.SchemeScopeChannel) require.NoError(t, err) require.Equal(t, int64(expectedChannelCount), actualCount) } @@ -514,17 +514,17 @@ func testSchemeStoreCountByScope(t *testing.T, ss store.Store) { err := ss.Scheme().PermanentDeleteAll() require.NoError(t, err) - createScheme(model.SCHEME_SCOPE_CHANNEL) - createScheme(model.SCHEME_SCOPE_TEAM) + createScheme(model.SchemeScopeChannel) + createScheme(model.SchemeScopeTeam) testCounts(1, 1) - createScheme(model.SCHEME_SCOPE_TEAM) + createScheme(model.SchemeScopeTeam) testCounts(2, 1) - createScheme(model.SCHEME_SCOPE_CHANNEL) + createScheme(model.SchemeScopeChannel) testCounts(2, 2) } func testCountWithoutPermission(t *testing.T, ss store.Store) { - perm := model.PERMISSION_CREATE_POST.Id + perm := model.PermissionCreatePost.Id createScheme := func(scope string) *model.Scheme { scheme, err := ss.Scheme().Save(&model.Scheme{ @@ -548,13 +548,13 @@ func testCountWithoutPermission(t *testing.T, ss store.Store) { return } - teamScheme1 := createScheme(model.SCHEME_SCOPE_TEAM) + teamScheme1 := createScheme(model.SchemeScopeTeam) defer ss.Scheme().Delete(teamScheme1.Id) - teamScheme2 := createScheme(model.SCHEME_SCOPE_TEAM) + teamScheme2 := createScheme(model.SchemeScopeTeam) defer ss.Scheme().Delete(teamScheme2.Id) - channelScheme1 := createScheme(model.SCHEME_SCOPE_CHANNEL) + channelScheme1 := createScheme(model.SchemeScopeChannel) defer ss.Scheme().Delete(channelScheme1.Id) - channelScheme2 := createScheme(model.SCHEME_SCOPE_CHANNEL) + channelScheme2 := createScheme(model.SchemeScopeChannel) defer ss.Scheme().Delete(channelScheme2.Id) ts1User, ts1Guest := getRoles(teamScheme1) @@ -573,11 +573,11 @@ func testCountWithoutPermission(t *testing.T, ss store.Store) { cs2Guest, } - teamUserCount, err := ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_TEAM, perm, model.RoleScopeChannel, model.RoleTypeUser) + teamUserCount, err := ss.Scheme().CountWithoutPermission(model.SchemeScopeTeam, perm, model.RoleScopeChannel, model.RoleTypeUser) require.NoError(t, err) require.Equal(t, int64(0), teamUserCount) - teamGuestCount, err := ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_TEAM, perm, model.RoleScopeChannel, model.RoleTypeGuest) + teamGuestCount, err := ss.Scheme().CountWithoutPermission(model.SchemeScopeTeam, perm, model.RoleScopeChannel, model.RoleTypeGuest) require.NoError(t, err) require.Equal(t, int64(0), teamGuestCount) @@ -614,19 +614,19 @@ func testCountWithoutPermission(t *testing.T, ss store.Store) { for _, test := range tests { removePermission(test.removePermissionFromRole) - count, err := ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_TEAM, perm, model.RoleScopeChannel, model.RoleTypeUser) + count, err := ss.Scheme().CountWithoutPermission(model.SchemeScopeTeam, perm, model.RoleScopeChannel, model.RoleTypeUser) require.NoError(t, err) require.Equal(t, int64(test.expectTeamSchemeChannelUserCount), count) - count, err = ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_TEAM, perm, model.RoleScopeChannel, model.RoleTypeGuest) + count, err = ss.Scheme().CountWithoutPermission(model.SchemeScopeTeam, perm, model.RoleScopeChannel, model.RoleTypeGuest) require.NoError(t, err) require.Equal(t, int64(test.expectTeamSchemeChannelGuestCount), count) - count, err = ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, perm, model.RoleScopeChannel, model.RoleTypeUser) + count, err = ss.Scheme().CountWithoutPermission(model.SchemeScopeChannel, perm, model.RoleScopeChannel, model.RoleTypeUser) require.NoError(t, err) require.Equal(t, int64(test.expectChannelSchemeChannelUserCount), count) - count, err = ss.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, perm, model.RoleScopeChannel, model.RoleTypeGuest) + count, err = ss.Scheme().CountWithoutPermission(model.SchemeScopeChannel, perm, model.RoleScopeChannel, model.RoleTypeGuest) require.NoError(t, err) require.Equal(t, int64(test.expectChannelSchemeChannelGuestCount), count) } diff --git a/store/storetest/session_store.go b/store/storetest/session_store.go index 62ab216b46..d5954a783f 100644 --- a/store/storetest/session_store.go +++ b/store/storetest/session_store.go @@ -187,7 +187,7 @@ func testSessionUpdateDeviceId(t *testing.T, ss store.Store) { s1, err := ss.Session().Save(s1) require.NoError(t, err) - _, err = ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt) + _, err = ss.Session().UpdateDeviceId(s1.Id, model.PushNotifyApple+":1234567890", s1.ExpiresAt) require.NoError(t, err) s2 := &model.Session{} @@ -196,7 +196,7 @@ func testSessionUpdateDeviceId(t *testing.T, ss store.Store) { s2, err = ss.Session().Save(s2) require.NoError(t, err) - _, err = ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt) + _, err = ss.Session().UpdateDeviceId(s2.Id, model.PushNotifyApple+":1234567890", s1.ExpiresAt) require.NoError(t, err) } @@ -207,7 +207,7 @@ func testSessionUpdateDeviceId2(t *testing.T, ss store.Store) { s1, err := ss.Session().Save(s1) require.NoError(t, err) - _, err = ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt) + _, err = ss.Session().UpdateDeviceId(s1.Id, model.PushNotifyAppleReactNative+":1234567890", s1.ExpiresAt) require.NoError(t, err) s2 := &model.Session{} @@ -216,7 +216,7 @@ func testSessionUpdateDeviceId2(t *testing.T, ss store.Store) { s2, err = ss.Session().Save(s2) require.NoError(t, err) - _, err = ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt) + _, err = ss.Session().UpdateDeviceId(s2.Id, model.PushNotifyAppleReactNative+":1234567890", s1.ExpiresAt) require.NoError(t, err) } diff --git a/store/storetest/settings.go b/store/storetest/settings.go index b800f1acdf..77e70bfe63 100644 --- a/store/storetest/settings.go +++ b/store/storetest/settings.go @@ -161,9 +161,9 @@ func execAsRoot(settings *model.SqlSettings, sqlCommand string) error { var driver = *settings.DriverName switch driver { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: dsn = mySQLRootDSN(*settings.DataSource) - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: dsn = postgreSQLRootDSN(*settings.DataSource) default: return fmt.Errorf("unsupported driver %s", driver) @@ -196,7 +196,7 @@ func MakeSqlSettings(driver string, withReplica bool) *model.SqlSettings { var dbName string switch driver { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: settings = MySQLSettings(withReplica) dbName = mySQLDSNDatabase(*settings.DataSource) newDSRs := []string{} @@ -204,7 +204,7 @@ func MakeSqlSettings(driver string, withReplica bool) *model.SqlSettings { newDSRs = append(newDSRs, replaceMySQLDatabaseName(dataSource, dbName)) } settings.DataSourceReplicas = newDSRs - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: settings = PostgreSQLSettings() dbName = postgreSQLDSNDatabase(*settings.DataSource) default: @@ -216,11 +216,11 @@ func MakeSqlSettings(driver string, withReplica bool) *model.SqlSettings { } switch driver { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: if err := execAsRoot(settings, "GRANT ALL PRIVILEGES ON "+dbName+".* TO 'mmuser'"); err != nil { panic("failed to grant mmuser permission to " + dbName + ":" + err.Error()) } - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: if err := execAsRoot(settings, "GRANT ALL PRIVILEGES ON DATABASE \""+dbName+"\" TO mmuser"); err != nil { panic("failed to grant mmuser permission to " + dbName + ":" + err.Error()) } @@ -238,9 +238,9 @@ func CleanupSqlSettings(settings *model.SqlSettings) { var dbName string switch driver { - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: dbName = mySQLDSNDatabase(*settings.DataSource) - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: dbName = postgreSQLDSNDatabase(*settings.DataSource) default: panic("unsupported driver " + driver) diff --git a/store/storetest/shared_channel_store.go b/store/storetest/shared_channel_store.go index 04ed96d058..fa2c3f4c08 100644 --- a/store/storetest/shared_channel_store.go +++ b/store/storetest/shared_channel_store.go @@ -791,7 +791,7 @@ func createTestChannel(ss store.Store, name string) (*model.Channel, error) { func createSharedTestChannel(ss store.Store, name string, shared bool) (*model.Channel, error) { channel := &model.Channel{ TeamId: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: name, DisplayName: name + " display name", Header: name + " header", diff --git a/store/storetest/status_store.go b/store/storetest/status_store.go index d537932f3f..662b740920 100644 --- a/store/storetest/status_store.go +++ b/store/storetest/status_store.go @@ -20,7 +20,7 @@ func TestStatusStore(t *testing.T, ss store.Store) { } func testStatusStore(t *testing.T, ss store.Store) { - status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status := &model.Status{UserId: model.NewId(), Status: model.StatusOnline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} require.NoError(t, ss.Status().SaveOrUpdate(status)) status.LastActivityAt = 10 @@ -28,10 +28,10 @@ func testStatusStore(t *testing.T, ss store.Store) { _, err := ss.Status().Get(status.UserId) require.NoError(t, err) - status2 := &model.Status{UserId: model.NewId(), Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status2 := &model.Status{UserId: model.NewId(), Status: model.StatusAway, Manual: false, LastActivityAt: 0, ActiveChannel: ""} require.NoError(t, ss.Status().SaveOrUpdate(status2)) - status3 := &model.Status{UserId: model.NewId(), Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} + status3 := &model.Status{UserId: model.NewId(), Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""} require.NoError(t, ss.Status().SaveOrUpdate(status3)) statuses, err := ss.Status().GetByIds([]string{status.UserId, "junk"}) @@ -43,14 +43,14 @@ func testStatusStore(t *testing.T, ss store.Store) { statusParameter, err := ss.Status().Get(status.UserId) require.NoError(t, err) - require.Equal(t, statusParameter.Status, model.STATUS_OFFLINE, "should be offline") + require.Equal(t, statusParameter.Status, model.StatusOffline, "should be offline") err = ss.Status().UpdateLastActivityAt(status.UserId, 10) require.NoError(t, err) } func testActiveUserCount(t *testing.T, ss store.Store) { - status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} + status := &model.Status{UserId: model.NewId(), Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} require.NoError(t, ss.Status().SaveOrUpdate(status)) count, err := ss.Status().GetTotalActiveUsersCount() @@ -67,8 +67,8 @@ func (s ByUserId) Less(i, j int) bool { return s[i].UserId < s[j].UserId } func testUpdateExpiredDNDStatuses(t *testing.T, ss store.Store) { userID := NewTestId() - status := &model.Status{UserId: userID, Status: model.STATUS_DND, Manual: true, - DNDEndTime: time.Now().Add(5 * time.Second).Unix(), PrevStatus: model.STATUS_ONLINE} + status := &model.Status{UserId: userID, Status: model.StatusDnd, Manual: true, + DNDEndTime: time.Now().Add(5 * time.Second).Unix(), PrevStatus: model.StatusOnline} require.NoError(t, ss.Status().SaveOrUpdate(status)) time.Sleep(2 * time.Second) @@ -87,8 +87,8 @@ func testUpdateExpiredDNDStatuses(t *testing.T, ss store.Store) { updatedStatus := *statuses[0] require.Equal(t, updatedStatus.UserId, userID) - require.Equal(t, updatedStatus.Status, model.STATUS_ONLINE) + require.Equal(t, updatedStatus.Status, model.StatusOnline) require.Equal(t, updatedStatus.DNDEndTime, int64(0)) - require.Equal(t, updatedStatus.PrevStatus, model.STATUS_DND) + require.Equal(t, updatedStatus.PrevStatus, model.StatusDnd) require.Equal(t, updatedStatus.Manual, false) } diff --git a/store/storetest/system_store.go b/store/storetest/system_store.go index c3731c2ddf..dfcf5a696a 100644 --- a/store/storetest/system_store.go +++ b/store/storetest/system_store.go @@ -63,29 +63,29 @@ func testSystemStoreSaveOrUpdateWithWarnMetricHandling(t *testing.T, ss store.St err := ss.System().SaveOrUpdateWithWarnMetricHandling(system) require.NoError(t, err) - _, err = ss.System().GetByName(model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY) + _, err = ss.System().GetByName(model.SystemWarnMetricLastRunTimestampKey) assert.Error(t, err) system.Name = "warn_metric_number_of_active_users_100" - system.Value = model.WARN_METRIC_STATUS_RUNONCE + system.Value = model.WarnMetricStatusRunonce err = ss.System().SaveOrUpdateWithWarnMetricHandling(system) require.NoError(t, err) - val1, nerr := ss.System().GetByName(model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY) + val1, nerr := ss.System().GetByName(model.SystemWarnMetricLastRunTimestampKey) assert.NoError(t, nerr) system.Name = "warn_metric_number_of_active_users_100" - system.Value = model.WARN_METRIC_STATUS_ACK + system.Value = model.WarnMetricStatusAck err = ss.System().SaveOrUpdateWithWarnMetricHandling(system) require.NoError(t, err) - val2, nerr := ss.System().GetByName(model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY) + val2, nerr := ss.System().GetByName(model.SystemWarnMetricLastRunTimestampKey) assert.NoError(t, nerr) assert.Equal(t, val1, val2) } func testSystemStoreGetByNameNoEntries(t *testing.T, ss store.Store) { - res, nErr := ss.System().GetByName(model.SYSTEM_FIRST_ADMIN_VISIT_MARKETPLACE) + res, nErr := ss.System().GetByName(model.SystemFirstAdminVisitMarketplace) _, ok := nErr.(*store.ErrNotFound) require.Error(t, nErr) assert.True(t, ok) @@ -128,13 +128,13 @@ func testSystemStorePermanentDeleteByName(t *testing.T, ss store.Store) { func testInsertIfExists(t *testing.T, ss store.Store) { t.Run("Serial", func(t *testing.T) { - s1 := &model.System{Name: model.SYSTEM_CLUSTER_ENCRYPTION_KEY, Value: "somekey"} + s1 := &model.System{Name: model.SystemClusterEncryptionKey, Value: "somekey"} s2, err := ss.System().InsertIfExists(s1) require.NoError(t, err) assert.Equal(t, s1.Value, s2.Value) - s1New := &model.System{Name: model.SYSTEM_CLUSTER_ENCRYPTION_KEY, Value: "anotherKey"} + s1New := &model.System{Name: model.SystemClusterEncryptionKey, Value: "anotherKey"} s3, err := ss.System().InsertIfExists(s1New) require.NoError(t, err) @@ -147,7 +147,7 @@ func testInsertIfExists(t *testing.T, ss store.Store) { wg.Add(2) go func() { defer wg.Done() - s1 := &model.System{Name: model.SYSTEM_CLUSTER_ENCRYPTION_KEY, Value: "firstKey"} + s1 := &model.System{Name: model.SystemClusterEncryptionKey, Value: "firstKey"} var err error s2, err = ss.System().InsertIfExists(s1) require.NoError(t, err) @@ -155,7 +155,7 @@ func testInsertIfExists(t *testing.T, ss store.Store) { go func() { defer wg.Done() - s1 := &model.System{Name: model.SYSTEM_CLUSTER_ENCRYPTION_KEY, Value: "secondKey"} + s1 := &model.System{Name: model.SystemClusterEncryptionKey, Value: "secondKey"} var err error s3, err = ss.System().InsertIfExists(s1) require.NoError(t, err) diff --git a/store/storetest/team_store.go b/store/storetest/team_store.go index 23a245e91d..2087868023 100644 --- a/store/storetest/team_store.go +++ b/store/storetest/team_store.go @@ -79,7 +79,7 @@ func testTeamStoreSave(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen _, err := ss.Team().Save(&o1) require.NoError(t, err, "couldn't save item") @@ -97,7 +97,7 @@ func testTeamStoreUpdate(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -120,7 +120,7 @@ func testTeamStoreGet(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -137,7 +137,7 @@ func testTeamStoreGetByNames(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -146,7 +146,7 @@ func testTeamStoreGetByNames(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName2" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -190,7 +190,7 @@ func testTeamStoreGetByName(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -220,7 +220,7 @@ func testTeamStoreSearchAll(t *testing.T, ss store.Store) { o.DisplayName = "ADisplayName" + NewTestId() o.Name = "searchterm-" + NewTestId() o.Email = MakeEmail() - o.Type = model.TEAM_OPEN + o.Type = model.TeamOpen o.AllowOpenInvite = true _, err := ss.Team().Save(&o) @@ -230,7 +230,7 @@ func testTeamStoreSearchAll(t *testing.T, ss store.Store) { p.DisplayName = "BDisplayName" + NewTestId() p.Name = "searchterm-" + NewTestId() p.Email = MakeEmail() - p.Type = model.TEAM_OPEN + p.Type = model.TeamOpen p.AllowOpenInvite = false _, err = ss.Team().Save(&p) @@ -240,7 +240,7 @@ func testTeamStoreSearchAll(t *testing.T, ss store.Store) { g.DisplayName = "CDisplayName" + NewTestId() g.Name = "searchterm-" + NewTestId() g.Email = MakeEmail() - g.Type = model.TEAM_OPEN + g.Type = model.TeamOpen g.AllowOpenInvite = false g.GroupConstrained = model.NewBool(true) @@ -251,7 +251,7 @@ func testTeamStoreSearchAll(t *testing.T, ss store.Store) { q.DisplayName = "CHOCOLATE" q.Name = "ilovecake" q.Email = MakeEmail() - q.Type = model.TEAM_OPEN + q.Type = model.TeamOpen q.AllowOpenInvite = false q, err = ss.Team().Save(q) @@ -407,7 +407,7 @@ func testTeamStoreSearchOpen(t *testing.T, ss store.Store) { o.DisplayName = "ADisplayName" + NewTestId() o.Name = NewTestId() o.Email = MakeEmail() - o.Type = model.TEAM_OPEN + o.Type = model.TeamOpen o.AllowOpenInvite = true _, err := ss.Team().Save(&o) @@ -417,7 +417,7 @@ func testTeamStoreSearchOpen(t *testing.T, ss store.Store) { p.DisplayName = "ADisplayName" + NewTestId() p.Name = NewTestId() p.Email = MakeEmail() - p.Type = model.TEAM_OPEN + p.Type = model.TeamOpen p.AllowOpenInvite = false _, err = ss.Team().Save(&p) @@ -427,7 +427,7 @@ func testTeamStoreSearchOpen(t *testing.T, ss store.Store) { q.DisplayName = "PINEAPPLEPIE" q.Name = "ihadsomepineapplepiewithstrawberry" q.Email = MakeEmail() - q.Type = model.TEAM_OPEN + q.Type = model.TeamOpen q.AllowOpenInvite = true _, err = ss.Team().Save(&q) @@ -513,7 +513,7 @@ func testTeamStoreSearchPrivate(t *testing.T, ss store.Store) { o.DisplayName = "ADisplayName" + NewTestId() o.Name = NewTestId() o.Email = MakeEmail() - o.Type = model.TEAM_OPEN + o.Type = model.TeamOpen o.AllowOpenInvite = true _, err := ss.Team().Save(&o) @@ -523,7 +523,7 @@ func testTeamStoreSearchPrivate(t *testing.T, ss store.Store) { p.DisplayName = "ADisplayName" + NewTestId() p.Name = NewTestId() p.Email = MakeEmail() - p.Type = model.TEAM_OPEN + p.Type = model.TeamOpen p.AllowOpenInvite = false _, err = ss.Team().Save(&p) @@ -533,7 +533,7 @@ func testTeamStoreSearchPrivate(t *testing.T, ss store.Store) { q.DisplayName = "FOOBARDISPLAYNAME" q.Name = "averylongname" q.Email = MakeEmail() - q.Type = model.TEAM_OPEN + q.Type = model.TeamOpen q.AllowOpenInvite = false _, err = ss.Team().Save(&q) @@ -619,7 +619,7 @@ func testTeamStoreGetByInviteId(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.InviteId = model.NewId() save1, err := ss.Team().Save(&o1) @@ -629,7 +629,7 @@ func testTeamStoreGetByInviteId(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen r1, err := ss.Team().GetByInviteId(save1.InviteId) require.NoError(t, err) @@ -644,7 +644,7 @@ func testTeamStoreByUserId(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.InviteId = model.NewId() o1, err := ss.Team().Save(o1) require.NoError(t, err) @@ -664,7 +664,7 @@ func testTeamStoreGetAllPage(t *testing.T, ss store.Store) { o.DisplayName = "ADisplayName" + model.NewId() o.Name = "zz" + model.NewId() + "a" o.Email = MakeEmail() - o.Type = model.TEAM_OPEN + o.Type = model.TeamOpen o.AllowOpenInvite = true _, err := ss.Team().Save(&o) require.NoError(t, err) @@ -722,7 +722,7 @@ func testGetAllTeamListing(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -731,7 +731,7 @@ func testGetAllTeamListing(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -739,7 +739,7 @@ func testGetAllTeamListing(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_INVITE + o3.Type = model.TeamInvite o3.AllowOpenInvite = true _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -748,7 +748,7 @@ func testGetAllTeamListing(t *testing.T, ss store.Store) { o4.DisplayName = "DisplayName" o4.Name = NewTestId() o4.Email = MakeEmail() - o4.Type = model.TEAM_INVITE + o4.Type = model.TeamInvite _, err = ss.Team().Save(&o4) require.NoError(t, err) @@ -766,7 +766,7 @@ func testGetAllTeamPageListing(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -775,7 +775,7 @@ func testGetAllTeamPageListing(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen o2.AllowOpenInvite = false _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -784,7 +784,7 @@ func testGetAllTeamPageListing(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_INVITE + o3.Type = model.TeamInvite o3.AllowOpenInvite = true _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -793,7 +793,7 @@ func testGetAllTeamPageListing(t *testing.T, ss store.Store) { o4.DisplayName = "DisplayName" o4.Name = NewTestId() o4.Email = MakeEmail() - o4.Type = model.TEAM_INVITE + o4.Type = model.TeamInvite o4.AllowOpenInvite = false _, err = ss.Team().Save(&o4) require.NoError(t, err) @@ -813,7 +813,7 @@ func testGetAllTeamPageListing(t *testing.T, ss store.Store) { o5.DisplayName = "DisplayName" o5.Name = NewTestId() o5.Email = MakeEmail() - o5.Type = model.TEAM_OPEN + o5.Type = model.TeamOpen o5.AllowOpenInvite = true _, err = ss.Team().Save(&o5) require.NoError(t, err) @@ -842,7 +842,7 @@ func testGetAllPrivateTeamListing(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -851,7 +851,7 @@ func testGetAllPrivateTeamListing(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -859,7 +859,7 @@ func testGetAllPrivateTeamListing(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_INVITE + o3.Type = model.TeamInvite o3.AllowOpenInvite = true _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -868,7 +868,7 @@ func testGetAllPrivateTeamListing(t *testing.T, ss store.Store) { o4.DisplayName = "DisplayName" o4.Name = NewTestId() o4.Email = MakeEmail() - o4.Type = model.TEAM_INVITE + o4.Type = model.TeamInvite _, err = ss.Team().Save(&o4) require.NoError(t, err) @@ -886,7 +886,7 @@ func testGetAllPrivateTeamPageListing(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -895,7 +895,7 @@ func testGetAllPrivateTeamPageListing(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen o2.AllowOpenInvite = false _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -904,7 +904,7 @@ func testGetAllPrivateTeamPageListing(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_INVITE + o3.Type = model.TeamInvite o3.AllowOpenInvite = true _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -913,7 +913,7 @@ func testGetAllPrivateTeamPageListing(t *testing.T, ss store.Store) { o4.DisplayName = "DisplayName" o4.Name = NewTestId() o4.Email = MakeEmail() - o4.Type = model.TEAM_INVITE + o4.Type = model.TeamInvite o4.AllowOpenInvite = false _, err = ss.Team().Save(&o4) require.NoError(t, err) @@ -932,7 +932,7 @@ func testGetAllPrivateTeamPageListing(t *testing.T, ss store.Store) { o5.DisplayName = "DisplayName" o5.Name = NewTestId() o5.Email = MakeEmail() - o5.Type = model.TEAM_OPEN + o5.Type = model.TeamOpen o5.AllowOpenInvite = true _, err = ss.Team().Save(&o5) require.NoError(t, err) @@ -961,7 +961,7 @@ func testGetAllPublicTeamPageListing(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName1" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true t1, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -970,7 +970,7 @@ func testGetAllPublicTeamPageListing(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName2" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen o2.AllowOpenInvite = false _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -979,7 +979,7 @@ func testGetAllPublicTeamPageListing(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName3" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_INVITE + o3.Type = model.TeamInvite o3.AllowOpenInvite = true t3, err := ss.Team().Save(&o3) require.NoError(t, err) @@ -988,7 +988,7 @@ func testGetAllPublicTeamPageListing(t *testing.T, ss store.Store) { o4.DisplayName = "DisplayName4" o4.Name = NewTestId() o4.Email = MakeEmail() - o4.Type = model.TEAM_INVITE + o4.Type = model.TeamInvite o4.AllowOpenInvite = false _, err = ss.Team().Save(&o4) require.NoError(t, err) @@ -1003,7 +1003,7 @@ func testGetAllPublicTeamPageListing(t *testing.T, ss store.Store) { o5.DisplayName = "DisplayName5" o5.Name = NewTestId() o5.Email = MakeEmail() - o5.Type = model.TEAM_OPEN + o5.Type = model.TeamOpen o5.AllowOpenInvite = true t5, err := ss.Team().Save(&o5) require.NoError(t, err) @@ -1021,7 +1021,7 @@ func testDelete(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -1030,7 +1030,7 @@ func testDelete(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -1045,7 +1045,7 @@ func testPublicTeamCount(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -1054,7 +1054,7 @@ func testPublicTeamCount(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen o2.AllowOpenInvite = false _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -1063,7 +1063,7 @@ func testPublicTeamCount(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_OPEN + o3.Type = model.TeamOpen o3.AllowOpenInvite = true _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -1080,7 +1080,7 @@ func testPrivateTeamCount(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = false _, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -1089,7 +1089,7 @@ func testPrivateTeamCount(t *testing.T, ss store.Store) { o2.DisplayName = "DisplayName" o2.Name = NewTestId() o2.Email = MakeEmail() - o2.Type = model.TEAM_OPEN + o2.Type = model.TeamOpen o2.AllowOpenInvite = true _, err = ss.Team().Save(&o2) require.NoError(t, err) @@ -1098,7 +1098,7 @@ func testPrivateTeamCount(t *testing.T, ss store.Store) { o3.DisplayName = "DisplayName" o3.Name = NewTestId() o3.Email = MakeEmail() - o3.Type = model.TEAM_OPEN + o3.Type = model.TeamOpen o3.AllowOpenInvite = false _, err = ss.Team().Save(&o3) require.NoError(t, err) @@ -1113,7 +1113,7 @@ func testTeamCount(t *testing.T, ss store.Store) { o1.DisplayName = "DisplayName" o1.Name = NewTestId() o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.AllowOpenInvite = true team, err := ss.Team().Save(&o1) require.NoError(t, err) @@ -1381,7 +1381,7 @@ func testTeamSaveMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -1522,7 +1522,7 @@ func testTeamSaveMember(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -1531,7 +1531,7 @@ func testTeamSaveMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -1737,7 +1737,7 @@ func testTeamSaveMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -1890,7 +1890,7 @@ func testTeamSaveMultipleMembers(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -1899,7 +1899,7 @@ func testTeamSaveMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -2066,7 +2066,7 @@ func testTeamUpdateMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -2207,7 +2207,7 @@ func testTeamUpdateMember(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -2216,7 +2216,7 @@ func testTeamUpdateMember(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -2375,7 +2375,7 @@ func testTeamUpdateMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } team, nErr := ss.Team().Save(team) @@ -2524,7 +2524,7 @@ func testTeamUpdateMultipleMembers(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } ts, nErr := ss.Scheme().Save(ts) require.NoError(t, nErr) @@ -2533,7 +2533,7 @@ func testTeamUpdateMultipleMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &ts.Id, } @@ -2834,7 +2834,7 @@ func testSaveTeamMemberMaxMembers(t *testing.T, ss store.Store) { team, errSave := ss.Team().Save(&model.Team{ DisplayName: "DisplayName", Name: NewTestId(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, errSave) defer func() { @@ -2956,7 +2956,7 @@ func testGetTeamMember(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s2, nErr = ss.Scheme().Save(s2) require.NoError(t, nErr) @@ -2965,7 +2965,7 @@ func testGetTeamMember(t *testing.T, ss store.Store) { t2, nErr := ss.Team().Save(&model.Team{ DisplayName: "DisplayName", Name: NewTestId(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s2.Id, }) require.NoError(t, nErr) @@ -3078,11 +3078,11 @@ func testGetChannelUnreadsForAllTeams(t *testing.T, ss store.Store) { _, nErr = ss.Team().SaveMember(m2, -1) require.NoError(t, nErr) - c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} + c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.ChannelTypeOpen, TotalMsgCount: 100} _, nErr = ss.Channel().Save(c1, -1) require.NoError(t, nErr) - c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} + c2 := &model.Channel{TeamId: m2.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.ChannelTypeOpen, TotalMsgCount: 100} _, nErr = ss.Channel().Save(c2, -1) require.NoError(t, nErr) @@ -3132,11 +3132,11 @@ func testGetChannelUnreadsForTeam(t *testing.T, ss store.Store) { _, nErr := ss.Team().SaveMember(m1, -1) require.NoError(t, nErr) - c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} + c1 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.ChannelTypeOpen, TotalMsgCount: 100} _, nErr = ss.Channel().Save(c1, -1) require.NoError(t, nErr) - c2 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.CHANNEL_OPEN, TotalMsgCount: 100} + c2 := &model.Channel{TeamId: m1.TeamId, Name: model.NewId(), DisplayName: "Town Square", Type: model.ChannelTypeOpen, TotalMsgCount: 100} _, nErr = ss.Channel().Save(c2, -1) require.NoError(t, nErr) @@ -3163,7 +3163,7 @@ func testUpdateLastTeamIconUpdate(t *testing.T, ss store.Store) { o1.DisplayName = "Display Name" o1.Name = "z-z-z" + model.NewId() + "b" o1.Email = MakeEmail() - o1.Type = model.TEAM_OPEN + o1.Type = model.TeamOpen o1.LastTeamIconUpdate = lastTeamIconUpdateInitial o1, err := ss.Team().Save(o1) require.NoError(t, err) @@ -3185,14 +3185,14 @@ func testGetTeamsByScheme(t *testing.T, ss store.Store) { DisplayName: NewTestId(), Name: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s2 := &model.Scheme{ DisplayName: NewTestId(), Name: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, err := ss.Scheme().Save(s1) @@ -3205,7 +3205,7 @@ func testGetTeamsByScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } @@ -3213,7 +3213,7 @@ func testGetTeamsByScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } @@ -3221,7 +3221,7 @@ func testGetTeamsByScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } _, err = ss.Team().Save(t1) @@ -3255,7 +3255,7 @@ func testTeamStoreMigrateTeamMembers(t *testing.T, ss store.Store) { DisplayName: "Name", Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, InviteId: model.NewId(), SchemeId: &s1, } @@ -3323,7 +3323,7 @@ func testResetAllTeamSchemes(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, err := ss.Scheme().Save(s1) require.NoError(t, err) @@ -3332,7 +3332,7 @@ func testResetAllTeamSchemes(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } @@ -3340,7 +3340,7 @@ func testResetAllTeamSchemes(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } @@ -3414,7 +3414,7 @@ func testTeamStoreAnalyticsGetTeamCountForScheme(t *testing.T, ss store.Store) { DisplayName: NewTestId(), Name: NewTestId(), Description: NewTestId(), - Scope: model.SCHEME_SCOPE_TEAM, + Scope: model.SchemeScopeTeam, } s1, err := ss.Scheme().Save(s1) require.NoError(t, err) @@ -3427,7 +3427,7 @@ func testTeamStoreAnalyticsGetTeamCountForScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } _, err = ss.Team().Save(t1) @@ -3441,7 +3441,7 @@ func testTeamStoreAnalyticsGetTeamCountForScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, } _, err = ss.Team().Save(t2) @@ -3455,7 +3455,7 @@ func testTeamStoreAnalyticsGetTeamCountForScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, } _, err = ss.Team().Save(t3) require.NoError(t, err) @@ -3468,7 +3468,7 @@ func testTeamStoreAnalyticsGetTeamCountForScheme(t *testing.T, ss store.Store) { Name: NewTestId(), DisplayName: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, SchemeId: &s1.Id, DeleteAt: model.GetMillis(), } @@ -3485,7 +3485,7 @@ func testTeamStoreGetAllForExportAfter(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = NewTestId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -3509,7 +3509,7 @@ func testTeamStoreGetTeamMembersForExport(t *testing.T, ss store.Store) { t1.DisplayName = "Name" t1.Name = NewTestId() t1.Email = MakeEmail() - t1.Type = model.TEAM_OPEN + t1.Type = model.TeamOpen _, err := ss.Team().Save(&t1) require.NoError(t, err) @@ -3546,7 +3546,7 @@ func testGroupSyncedTeamCount(t *testing.T, ss store.Store) { DisplayName: NewTestId(), Name: NewTestId(), Email: MakeEmail(), - Type: model.TEAM_INVITE, + Type: model.TeamInvite, GroupConstrained: model.NewBool(true), }) require.NoError(t, err) @@ -3557,7 +3557,7 @@ func testGroupSyncedTeamCount(t *testing.T, ss store.Store) { DisplayName: NewTestId(), Name: "zz" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_INVITE, + Type: model.TeamInvite, }) require.NoError(t, err) require.False(t, team2.IsGroupConstrained()) diff --git a/store/storetest/thread_store.go b/store/storetest/thread_store.go index ecd445d565..4263936bdc 100644 --- a/store/storetest/thread_store.go +++ b/store/storetest/thread_store.go @@ -39,7 +39,7 @@ func testThreadStorePopulation(t *testing.T, ss store.Store) { c, err2 := ss.Channel().Save(&model.Channel{ DisplayName: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, Name: model.NewId(), }, 999) require.NoError(t, err2) @@ -455,14 +455,14 @@ func testThreadStorePermanentDeleteBatchForRetentionPolicies(t *testing.T, ss st DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) @@ -544,14 +544,14 @@ func testThreadStorePermanentDeleteBatchThreadMembershipsForRetentionPolicies(t DisplayName: "DisplayName", Name: "team" + model.NewId(), Email: MakeEmail(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) channel, err := ss.Channel().Save(&model.Channel{ TeamId: team.Id, DisplayName: "DisplayName", Name: "channel" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, err) post, err := ss.Post().Save(&model.Post{ diff --git a/store/storetest/user_store.go b/store/storetest/user_store.go index 5e91d50224..aec4a52bff 100644 --- a/store/storetest/user_store.go +++ b/store/storetest/user_store.go @@ -370,7 +370,7 @@ func testUserStoreGetAllProfiles(t *testing.T, ss store.Store) { u1, err := ss.User().Save(&model.User{ Email: MakeEmail(), Username: "u1" + model.NewId(), - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, }) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(u1.Id)) }() @@ -378,7 +378,7 @@ func testUserStoreGetAllProfiles(t *testing.T, ss store.Store) { u2, err := ss.User().Save(&model.User{ Email: MakeEmail(), Username: "u2" + model.NewId(), - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, }) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(u2.Id)) }() @@ -427,7 +427,7 @@ func testUserStoreGetAllProfiles(t *testing.T, ss store.Store) { Email: MakeEmail(), Username: "u7" + model.NewId(), DeleteAt: model.GetMillis(), - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, }) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(u7.Id)) }() @@ -846,7 +846,7 @@ func testUserStoreGetProfilesInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in channel", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) @@ -855,7 +855,7 @@ func testUserStoreGetProfilesInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) @@ -1013,7 +1013,7 @@ func testUserStoreGetProfilesInChannelByStatus(t *testing.T, ss store.Store, s S TeamId: teamId, DisplayName: "Profiles in channel", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) @@ -1022,7 +1022,7 @@ func testUserStoreGetProfilesInChannelByStatus(t *testing.T, ss store.Store, s S TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) @@ -1067,15 +1067,15 @@ func testUserStoreGetProfilesInChannelByStatus(t *testing.T, ss store.Store, s S require.NoError(t, nErr) require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{ UserId: u1.Id, - Status: model.STATUS_DND, + Status: model.StatusDnd, })) require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{ UserId: u2.Id, - Status: model.STATUS_AWAY, + Status: model.StatusAway, })) require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{ UserId: u3.Id, - Status: model.STATUS_ONLINE, + Status: model.StatusOnline, })) t.Run("get all users in channel 1, offset 0, limit 100", func(t *testing.T) { @@ -1230,7 +1230,7 @@ func testUserStoreGetAllProfilesInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in channel", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) @@ -1239,7 +1239,7 @@ func testUserStoreGetAllProfilesInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) @@ -1356,7 +1356,7 @@ func testUserStoreGetProfilesNotInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in channel", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) @@ -1365,7 +1365,7 @@ func testUserStoreGetProfilesNotInChannel(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) @@ -1595,7 +1595,7 @@ func testUserStoreGetProfileByGroupChannelIdsForUser(t *testing.T, ss store.Stor gc1, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, }, -1) require.NoError(t, nErr) @@ -1611,7 +1611,7 @@ func testUserStoreGetProfileByGroupChannelIdsForUser(t *testing.T, ss store.Stor gc2, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_GROUP, + Type: model.ChannelTypeGroup, }, -1) require.NoError(t, nErr) @@ -1760,7 +1760,7 @@ func testUserStoreGetSystemAdminProfiles(t *testing.T, ss store.Store) { u1, err := ss.User().Save(&model.User{ Email: MakeEmail(), - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, Username: "u1" + model.NewId(), }) require.NoError(t, err) @@ -1779,7 +1779,7 @@ func testUserStoreGetSystemAdminProfiles(t *testing.T, ss store.Store) { u3, err := ss.User().Save(&model.User{ Email: MakeEmail(), - Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID, + Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId, Username: "u3" + model.NewId(), }) require.NoError(t, err) @@ -2032,7 +2032,7 @@ func testUserStoreGetForLogin(t *testing.T, ss store.Store) { u1, err := ss.User().Save(&model.User{ Email: MakeEmail(), Username: "u1" + model.NewId(), - AuthService: model.USER_AUTH_SERVICE_GITLAB, + AuthService: model.UserAuthServiceGitlab, AuthData: &auth, }) @@ -2044,7 +2044,7 @@ func testUserStoreGetForLogin(t *testing.T, ss store.Store) { u2, err := ss.User().Save(&model.User{ Email: MakeEmail(), Username: "u2" + model.NewId(), - AuthService: model.USER_AUTH_SERVICE_LDAP, + AuthService: model.UserAuthServiceLdap, AuthData: &auth2, }) require.NoError(t, err) @@ -2055,7 +2055,7 @@ func testUserStoreGetForLogin(t *testing.T, ss store.Store) { u3, err := ss.User().Save(&model.User{ Email: MakeEmail(), Username: "u3" + model.NewId(), - AuthService: model.USER_AUTH_SERVICE_LDAP, + AuthService: model.UserAuthServiceLdap, AuthData: &auth3, }) require.NoError(t, err) @@ -2194,17 +2194,17 @@ func testUserStoreResetAuthDataToEmailForUsers(t *testing.T, ss store.Store) { resetAuthDataToID := func() { _, err = ss.User().UpdateAuthData( - user.Id, model.USER_AUTH_SERVICE_SAML, model.NewString("some-id"), "", false) + user.Id, model.UserAuthServiceSaml, model.NewString("some-id"), "", false) require.NoError(t, err) } resetAuthDataToID() // dry run - numAffected, err := ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, nil, false, true) + numAffected, err := ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, nil, false, true) require.NoError(t, err) require.Equal(t, 1, numAffected) // real run - numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, nil, false, false) + numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, nil, false, false) require.NoError(t, err) require.Equal(t, 1, numAffected) user, appErr := ss.User().Get(context.Background(), user.Id) @@ -2213,10 +2213,10 @@ func testUserStoreResetAuthDataToEmailForUsers(t *testing.T, ss store.Store) { resetAuthDataToID() // with specific user IDs - numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, []string{model.NewId()}, false, true) + numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, []string{model.NewId()}, false, true) require.NoError(t, err) require.Equal(t, 0, numAffected) - numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, []string{user.Id}, false, true) + numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, []string{user.Id}, false, true) require.NoError(t, err) require.Equal(t, 1, numAffected) @@ -2224,11 +2224,11 @@ func testUserStoreResetAuthDataToEmailForUsers(t *testing.T, ss store.Store) { user.DeleteAt = model.GetMillisForTime(time.Now()) ss.User().Update(user, true) // without deleted user - numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, nil, false, true) + numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, nil, false, true) require.NoError(t, err) require.Equal(t, 0, numAffected) // with deleted user - numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, nil, true, true) + numAffected, err = ss.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, nil, true, true) require.NoError(t, err) require.Equal(t, 1, numAffected) } @@ -2240,13 +2240,13 @@ func testUserUnreadCount(t *testing.T, ss store.Store) { c1.TeamId = teamId c1.DisplayName = "Unread Messages" c1.Name = "unread-messages-" + model.NewId() - c1.Type = model.CHANNEL_OPEN + c1.Type = model.ChannelTypeOpen c2 := model.Channel{} c2.TeamId = teamId c2.DisplayName = "Unread Direct" c2.Name = "unread-direct-" + model.NewId() - c2.Type = model.CHANNEL_DIRECT + c2.Type = model.ChannelTypeDirect u1 := &model.User{} u1.Username = "user1" + model.NewId() @@ -2414,9 +2414,9 @@ func testUserStoreGetRecentlyActiveUsersForTeam(t *testing.T, ss store.Store, s u2.LastActivityAt = millis - 1 u1.LastActivityAt = millis - 1 - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: u1.LastActivityAt, ActiveChannel: ""})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: u2.LastActivityAt, ActiveChannel: ""})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: u3.LastActivityAt, ActiveChannel: ""})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: u1.LastActivityAt, ActiveChannel: ""})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: u2.LastActivityAt, ActiveChannel: ""})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: u3.LastActivityAt, ActiveChannel: ""})) t.Run("get team 1, offset 0, limit 100", func(t *testing.T) { users, err := ss.User().GetRecentlyActiveUsersForTeam(teamId, 0, 100, nil) @@ -2603,7 +2603,7 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1, u3}, }, @@ -2613,8 +2613,8 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - TeamRoles: []string{model.TEAM_GUEST_ROLE_ID, model.TEAM_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + TeamRoles: []string{model.TeamGuestRoleId, model.TeamAdminRoleId}, }, []*model.User{u3}, }, @@ -2624,9 +2624,9 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, - TeamRoles: []string{model.TEAM_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + Roles: []string{model.SystemAdminRoleId}, + TeamRoles: []string{model.TeamAdminRoleId}, }, []*model.User{u1}, }, @@ -2636,8 +2636,8 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - TeamRoles: []string{model.TEAM_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + TeamRoles: []string{model.TeamAdminRoleId}, }, []*model.User{u2}, }, @@ -2647,8 +2647,8 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - TeamRoles: []string{model.TEAM_ADMIN_ROLE_ID, model.TEAM_GUEST_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + TeamRoles: []string{model.TeamAdminRoleId, model.TeamGuestRoleId}, }, []*model.User{u2, u3}, }, @@ -2658,9 +2658,9 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, - TeamRoles: []string{model.TEAM_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + Roles: []string{model.SystemAdminRoleId}, + TeamRoles: []string{model.TeamAdminRoleId}, }, []*model.User{u2, u1}, }, @@ -2670,8 +2670,8 @@ func testUserStoreSearch(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - Roles: []string{model.SYSTEM_GUEST_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + Roles: []string{model.SystemGuestRoleId}, TeamRoles: []string{}, }, []*model.User{u3}, @@ -2748,7 +2748,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { TeamId: tid, DisplayName: "NameName", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(&ch1, -1) require.NoError(t, nErr) @@ -2757,7 +2757,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { TeamId: tid, DisplayName: "NameName", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c2, nErr := ss.Channel().Save(&ch2, -1) require.NoError(t, nErr) @@ -2796,7 +2796,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -2808,7 +2808,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -2819,7 +2819,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -2830,7 +2830,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -2841,7 +2841,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -2853,7 +2853,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u3}, }, @@ -2864,7 +2864,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -2875,7 +2875,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -2886,7 +2886,7 @@ func testUserStoreSearchNotInChannel(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u2, u1}, }, @@ -2977,7 +2977,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { TeamId: tid, DisplayName: "NameName", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(&ch1, -1) require.NoError(t, nErr) @@ -2986,7 +2986,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { TeamId: tid, DisplayName: "NameName", Name: "zz" + model.NewId() + "b", - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c2, nErr := ss.Channel().Save(&ch2, -1) require.NoError(t, nErr) @@ -3029,7 +3029,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -3040,7 +3040,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1, u3}, }, @@ -3061,7 +3061,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3072,7 +3072,7 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3083,8 +3083,8 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + Roles: []string{model.SystemAdminRoleId}, }, []*model.User{u1}, }, @@ -3095,8 +3095,8 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID, model.SYSTEM_USER_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + Roles: []string{model.SystemAdminRoleId, model.SystemUserRoleId}, }, []*model.User{u1, u3}, }, @@ -3107,8 +3107,8 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + ChannelRoles: []string{model.ChannelUserRoleId}, }, []*model.User{u3}, }, @@ -3119,8 +3119,8 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + ChannelRoles: []string{model.ChannelUserRoleId, model.ChannelAdminRoleId}, }, []*model.User{u3}, }, @@ -3131,8 +3131,8 @@ func testUserStoreSearchInChannel(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID}, + Limit: model.UserSearchDefaultLimit, + ChannelRoles: []string{model.ChannelUserRoleId}, }, []*model.User{u2}, }, @@ -3260,7 +3260,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { "simo", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u4}, }, @@ -3271,7 +3271,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3282,7 +3282,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3292,7 +3292,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { "simo", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3302,7 +3302,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -3313,7 +3313,7 @@ func testUserStoreSearchNotInTeam(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1, u3}, }, @@ -3403,7 +3403,7 @@ func testUserStoreSearchWithoutTeam(t *testing.T, ss store.Store) { "", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u2, u1}, }, @@ -3412,7 +3412,7 @@ func testUserStoreSearchWithoutTeam(t *testing.T, ss store.Store) { "jim", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u2, u1}, }, @@ -3421,7 +3421,7 @@ func testUserStoreSearchWithoutTeam(t *testing.T, ss store.Store) { "* ", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u2, u1}, }, @@ -3526,7 +3526,7 @@ func testUserStoreSearchInGroup(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1}, }, @@ -3537,7 +3537,7 @@ func testUserStoreSearchInGroup(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{u1, u3}, }, @@ -3558,7 +3558,7 @@ func testUserStoreSearchInGroup(t *testing.T, ss store.Store) { "jimb", &model.UserSearchOptions{ AllowFullNames: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3569,7 +3569,7 @@ func testUserStoreSearchInGroup(t *testing.T, ss store.Store) { &model.UserSearchOptions{ AllowFullNames: true, AllowInactive: true, - Limit: model.USER_SEARCH_DEFAULT_LIMIT, + Limit: model.UserSearchDefaultLimit, }, []*model.User{}, }, @@ -3594,7 +3594,7 @@ func testCount(t *testing.T, ss store.Store) { channelId := model.NewId() regularUser := &model.User{} regularUser.Email = MakeEmail() - regularUser.Roles = model.SYSTEM_USER_ROLE_ID + regularUser.Roles = model.SystemUserRoleId _, err := ss.User().Save(regularUser) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(regularUser.Id)) }() @@ -3605,7 +3605,7 @@ func testCount(t *testing.T, ss store.Store) { guestUser := &model.User{} guestUser.Email = MakeEmail() - guestUser.Roles = model.SYSTEM_GUEST_ROLE_ID + guestUser.Roles = model.SystemGuestRoleId _, err = ss.User().Save(guestUser) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(guestUser.Id)) }() @@ -3616,7 +3616,7 @@ func testCount(t *testing.T, ss store.Store) { teamAdmin := &model.User{} teamAdmin.Email = MakeEmail() - teamAdmin.Roles = model.SYSTEM_USER_ROLE_ID + teamAdmin.Roles = model.SystemUserRoleId _, err = ss.User().Save(teamAdmin) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(teamAdmin.Id)) }() @@ -3627,7 +3627,7 @@ func testCount(t *testing.T, ss store.Store) { sysAdmin := &model.User{} sysAdmin.Email = MakeEmail() - sysAdmin.Roles = model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID + sysAdmin.Roles = model.SystemAdminRoleId + " " + model.SystemUserRoleId _, err = ss.User().Save(sysAdmin) require.NoError(t, err) defer func() { require.NoError(t, ss.User().PermanentDelete(sysAdmin.Id)) }() @@ -3752,7 +3752,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by system admins only", model.UserCountOptions{ TeamId: teamId, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, + Roles: []string{model.SystemAdminRoleId}, }, 1, }, @@ -3760,7 +3760,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by system users only", model.UserCountOptions{ TeamId: teamId, - Roles: []string{model.SYSTEM_USER_ROLE_ID}, + Roles: []string{model.SystemUserRoleId}, }, 2, }, @@ -3768,7 +3768,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by system guests only", model.UserCountOptions{ TeamId: teamId, - Roles: []string{model.SYSTEM_GUEST_ROLE_ID}, + Roles: []string{model.SystemGuestRoleId}, }, 1, }, @@ -3776,7 +3776,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by system admins and system users", model.UserCountOptions{ TeamId: teamId, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID, model.SYSTEM_USER_ROLE_ID}, + Roles: []string{model.SystemAdminRoleId, model.SystemUserRoleId}, }, 3, }, @@ -3784,7 +3784,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by system admins, system user and system guests", model.UserCountOptions{ TeamId: teamId, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID, model.SYSTEM_USER_ROLE_ID, model.SYSTEM_GUEST_ROLE_ID}, + Roles: []string{model.SystemAdminRoleId, model.SystemUserRoleId, model.SystemGuestRoleId}, }, 4, }, @@ -3792,7 +3792,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by team admins", model.UserCountOptions{ TeamId: teamId, - TeamRoles: []string{model.TEAM_ADMIN_ROLE_ID}, + TeamRoles: []string{model.TeamAdminRoleId}, }, 1, }, @@ -3800,7 +3800,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by team members", model.UserCountOptions{ TeamId: teamId, - TeamRoles: []string{model.TEAM_USER_ROLE_ID}, + TeamRoles: []string{model.TeamUserRoleId}, }, 1, }, @@ -3808,7 +3808,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by team guests", model.UserCountOptions{ TeamId: teamId, - TeamRoles: []string{model.TEAM_GUEST_ROLE_ID}, + TeamRoles: []string{model.TeamGuestRoleId}, }, 1, }, @@ -3816,8 +3816,8 @@ func testCount(t *testing.T, ss store.Store) { "Filter by team guests and any system role", model.UserCountOptions{ TeamId: teamId, - TeamRoles: []string{model.TEAM_GUEST_ROLE_ID}, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, + TeamRoles: []string{model.TeamGuestRoleId}, + Roles: []string{model.SystemAdminRoleId}, }, 2, }, @@ -3825,7 +3825,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by channel members", model.UserCountOptions{ ChannelId: channelId, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID}, + ChannelRoles: []string{model.ChannelUserRoleId}, }, 1, }, @@ -3833,8 +3833,8 @@ func testCount(t *testing.T, ss store.Store) { "Filter by channel members and system admins", model.UserCountOptions{ ChannelId: channelId, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID}, + Roles: []string{model.SystemAdminRoleId}, + ChannelRoles: []string{model.ChannelUserRoleId}, }, 2, }, @@ -3842,8 +3842,8 @@ func testCount(t *testing.T, ss store.Store) { "Filter by channel members and system admins and channel admins", model.UserCountOptions{ ChannelId: channelId, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, - ChannelRoles: []string{model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID}, + Roles: []string{model.SystemAdminRoleId}, + ChannelRoles: []string{model.ChannelUserRoleId, model.ChannelAdminRoleId}, }, 3, }, @@ -3851,7 +3851,7 @@ func testCount(t *testing.T, ss store.Store) { "Filter by channel guests", model.UserCountOptions{ ChannelId: channelId, - ChannelRoles: []string{model.CHANNEL_GUEST_ROLE_ID}, + ChannelRoles: []string{model.ChannelGuestRoleId}, }, 1, }, @@ -3859,8 +3859,8 @@ func testCount(t *testing.T, ss store.Store) { "Filter by channel guests and any system role", model.UserCountOptions{ ChannelId: channelId, - ChannelRoles: []string{model.CHANNEL_GUEST_ROLE_ID}, - Roles: []string{model.SYSTEM_ADMIN_ROLE_ID}, + ChannelRoles: []string{model.ChannelGuestRoleId}, + Roles: []string{model.SystemAdminRoleId}, }, 2, }, @@ -3927,11 +3927,11 @@ func testUserStoreAnalyticsActiveCount(t *testing.T, ss store.Store, s SqlStore) // u0 last activity status is two months ago. // u1 last activity status is two days ago. // u2, u3, u4 last activity is within last day - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u0.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u0.Id, Status: model.StatusOffline, LastActivityAt: millisTwoMonthsAgo})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.StatusOffline, LastActivityAt: millisTwoDaysAgo})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.StatusOffline, LastActivityAt: millis})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.StatusOffline, LastActivityAt: millis})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.StatusOffline, LastActivityAt: millis})) // Daily counts (without bots) count, err := ss.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true}) @@ -4015,11 +4015,11 @@ func testUserStoreAnalyticsActiveCountForPeriod(t *testing.T, ss store.Store, s // u2 last activity is one day ago // u3 last activity is within last day // u4 last activity is within last day - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u0.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo + MonthMilliseconds})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo + DayMilliseconds})) - require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u0.Id, Status: model.StatusOffline, LastActivityAt: millisTwoMonthsAgo})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.StatusOffline, LastActivityAt: millisTwoMonthsAgo + MonthMilliseconds})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.StatusOffline, LastActivityAt: millisTwoDaysAgo})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.StatusOffline, LastActivityAt: millisTwoDaysAgo + DayMilliseconds})) + require.NoError(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.StatusOffline, LastActivityAt: millis})) // Two months to two days (without bots) count, nerr := ss.User().AnalyticsActiveCountForPeriod(millisTwoMonthsAgo, millisTwoDaysAgo, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) @@ -4170,7 +4170,7 @@ func testUserStoreGetProfilesNotInTeam(t *testing.T, ss store.Store) { team, err := ss.Team().Save(&model.Team{ DisplayName: "Team", Name: "zz" + model.NewId(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) @@ -4482,27 +4482,27 @@ func testUserStoreGetUsersBatchForIndexing(t *testing.T, ss store.Store) { t1, err := ss.Team().Save(&model.Team{ DisplayName: "Team1", Name: "zz" + model.NewId(), - Type: model.TEAM_OPEN, + Type: model.TeamOpen, }) require.NoError(t, err) ch1 := &model.Channel{ Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } cPub1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) ch2 := &model.Channel{ Name: model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } cPub2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) ch3 := &model.Channel{ Name: model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } cPriv, nErr := ss.Channel().Save(ch3, -1) @@ -4619,7 +4619,7 @@ func testUserStoreGetTeamGroupUsers(t *testing.T, ss store.Store) { DisplayName: "dn_" + id, Name: "n-" + id, Email: id + "@test.com", - Type: model.TEAM_INVITE, + Type: model.TeamInvite, }) require.NoError(t, err) require.NotNil(t, team) @@ -4739,7 +4739,7 @@ func testUserStoreGetChannelGroupUsers(t *testing.T, ss store.Store) { channel, nErr := ss.Channel().Save(&model.Channel{ DisplayName: "dn_" + id, Name: "n-" + id, - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, }, 999) require.NoError(t, nErr) require.NotNil(t, channel) @@ -4878,7 +4878,7 @@ func testUserStorePromoteGuestToUser(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: true, SchemeUser: false, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -4924,7 +4924,7 @@ func testUserStorePromoteGuestToUser(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: true, SchemeUser: false, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5020,7 +5020,7 @@ func testUserStorePromoteGuestToUser(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: true, SchemeUser: false, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5065,7 +5065,7 @@ func testUserStorePromoteGuestToUser(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: true, SchemeUser: false, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5110,7 +5110,7 @@ func testUserStorePromoteGuestToUser(t *testing.T, ss store.Store) { TeamId: teamId1, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) @@ -5193,7 +5193,7 @@ func testUserStoreDemoteUserToGuest(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: false, SchemeUser: true, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5237,7 +5237,7 @@ func testUserStoreDemoteUserToGuest(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: true, SchemeUser: false, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5327,7 +5327,7 @@ func testUserStoreDemoteUserToGuest(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: false, SchemeUser: true, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5370,7 +5370,7 @@ func testUserStoreDemoteUserToGuest(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) _, nErr = ss.Channel().SaveMember(&model.ChannelMember{ChannelId: channel.Id, UserId: user.Id, SchemeGuest: false, SchemeUser: true, NotifyProps: model.GetDefaultChannelNotifyProps()}) @@ -5413,7 +5413,7 @@ func testUserStoreDemoteUserToGuest(t *testing.T, ss store.Store) { TeamId: teamId1, DisplayName: "Channel name", Name: "channel-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, }, -1) require.NoError(t, nErr) @@ -5633,7 +5633,7 @@ func testGetKnownUsers(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in channel", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_OPEN, + Type: model.ChannelTypeOpen, } c1, nErr := ss.Channel().Save(ch1, -1) require.NoError(t, nErr) @@ -5642,7 +5642,7 @@ func testGetKnownUsers(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c2, nErr := ss.Channel().Save(ch2, -1) require.NoError(t, nErr) @@ -5651,7 +5651,7 @@ func testGetKnownUsers(t *testing.T, ss store.Store) { TeamId: teamId, DisplayName: "Profiles in private", Name: "profiles-" + model.NewId(), - Type: model.CHANNEL_PRIVATE, + Type: model.ChannelTypePrivate, } c3, nErr := ss.Channel().Save(ch3, -1) require.NoError(t, nErr) diff --git a/testlib/cluster.go b/testlib/cluster.go index c40c30b07d..3158e50af7 100644 --- a/testlib/cluster.go +++ b/testlib/cluster.go @@ -66,7 +66,7 @@ func (c *FakeClusterInterface) ConfigChanged(previousConfig *model.Config, newCo func (c *FakeClusterInterface) SendClearRoleCacheMessage() { if c.clusterMessageHandler != nil { c.clusterMessageHandler(&model.ClusterMessage{ - Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLES, + Event: model.ClusterEventInvalidateCacheForRoles, }) } } diff --git a/testlib/helper.go b/testlib/helper.go index 3da6d203a1..e1b87c0d1a 100644 --- a/testlib/helper.go +++ b/testlib/helper.go @@ -104,7 +104,7 @@ func (h *MainHelper) Main(m *testing.M) { func (h *MainHelper) setupStore(withReadReplica bool) { driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") if driverName == "" { - driverName = model.DATABASE_DRIVER_POSTGRES + driverName = model.DatabaseDriverPostgres } h.Settings = storetest.MakeSqlSettings(driverName, withReadReplica) @@ -168,7 +168,7 @@ func (h *MainHelper) PreloadMigrations() { basePath := os.Getenv("MM_SERVER_PATH") relPath := "testlib/testdata" switch *h.Settings.DriverName { - case model.DATABASE_DRIVER_POSTGRES: + case model.DatabaseDriverPostgres: var finalPath string if basePath != "" { finalPath = filepath.Join(basePath, relPath, "postgres_migration_warmup.sql") @@ -179,7 +179,7 @@ func (h *MainHelper) PreloadMigrations() { if err != nil { panic(fmt.Errorf("cannot read file: %v", err)) } - case model.DATABASE_DRIVER_MYSQL: + case model.DatabaseDriverMysql: var finalPath string if basePath != "" { finalPath = filepath.Join(basePath, relPath, "mysql_migration_warmup.sql") @@ -259,8 +259,8 @@ func (h *MainHelper) GetSearchEngine() *searchengine.Broker { } func (h *MainHelper) SetReplicationLagForTesting(seconds int) error { - if dn := h.SQLStore.DriverName(); dn != model.DATABASE_DRIVER_MYSQL { - return fmt.Errorf("method not implemented for %q database driver, only %q is supported", dn, model.DATABASE_DRIVER_MYSQL) + if dn := h.SQLStore.DriverName(); dn != model.DatabaseDriverMysql { + return fmt.Errorf("method not implemented for %q database driver, only %q is supported", dn, model.DatabaseDriverMysql) } err := h.execOnEachReplica("STOP SLAVE SQL_THREAD FOR CHANNEL ''") diff --git a/testlib/store.go b/testlib/store.go index a1e476b787..4f8230cbb3 100644 --- a/testlib/store.go +++ b/testlib/store.go @@ -35,33 +35,33 @@ func GetMockStoreForSetupFunctions() *mocks.Store { systemStore.On("GetByName", "EmojisPermissionsMigrationComplete").Return(&model.System{Name: "EmojisPermissionsMigrationComplete", Value: "true"}, nil) systemStore.On("GetByName", "GuestRolesCreationMigrationComplete").Return(&model.System{Name: "GuestRolesCreationMigrationComplete", Value: "true"}, nil) systemStore.On("GetByName", "SystemConsoleRolesCreationMigrationComplete").Return(&model.System{Name: "SystemConsoleRolesCreationMigrationComplete", Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_EMOJI_PERMISSIONS_SPLIT).Return(&model.System{Name: model.MIGRATION_KEY_EMOJI_PERMISSIONS_SPLIT, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_WEBHOOK_PERMISSIONS_SPLIT).Return(&model.System{Name: model.MIGRATION_KEY_WEBHOOK_PERMISSIONS_SPLIT, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_LIST_JOIN_PUBLIC_PRIVATE_TEAMS).Return(&model.System{Name: model.MIGRATION_KEY_LIST_JOIN_PUBLIC_PRIVATE_TEAMS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_REMOVE_PERMANENT_DELETE_USER).Return(&model.System{Name: model.MIGRATION_KEY_REMOVE_PERMANENT_DELETE_USER, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_BOT_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_BOT_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_APPLY_CHANNEL_MANAGE_DELETE_TO_CHANNEL_USER).Return(&model.System{Name: model.MIGRATION_KEY_APPLY_CHANNEL_MANAGE_DELETE_TO_CHANNEL_USER, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_REMOVE_CHANNEL_MANAGE_DELETE_FROM_TEAM_USER).Return(&model.System{Name: model.MIGRATION_KEY_REMOVE_CHANNEL_MANAGE_DELETE_FROM_TEAM_USER, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_VIEW_MEMBERS_NEW_PERMISSION).Return(&model.System{Name: model.MIGRATION_KEY_VIEW_MEMBERS_NEW_PERMISSION, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_MANAGE_GUESTS_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_MANAGE_GUESTS_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_CHANNEL_MODERATIONS_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_CHANNEL_MODERATIONS_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_USE_GROUP_MENTIONS_PERMISSION).Return(&model.System{Name: model.MIGRATION_KEY_ADD_USE_GROUP_MENTIONS_PERMISSION, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_SYSTEM_CONSOLE_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_SYSTEM_CONSOLE_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_CONVERT_CHANNEL_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_CONVERT_CHANNEL_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_SYSTEM_ROLES_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_SYSTEM_ROLES_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_BILLING_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_BILLING_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_DOWNLOAD_COMPLIANCE_EXPORT_RESULTS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_DOWNLOAD_COMPLIANCE_EXPORT_RESULTS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_SITE_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_SITE_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_AUTHENTICATION_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_AUTHENTICATION_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_COMPLIANCE_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_ENVIRONMENT_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_ENVIRONMENT_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_TEST_EMAIL_ANCILLARY_PERMISSION).Return(&model.System{Name: model.MIGRATION_KEY_ADD_TEST_EMAIL_ANCILLARY_PERMISSION, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_ABOUT_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_ABOUT_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_INTEGRATIONS_SUBSECTION_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_INTEGRATIONS_SUBSECTION_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_MANAGE_SHARED_CHANNEL_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_MANAGE_SHARED_CHANNEL_PERMISSIONS, Value: "true"}, nil) - systemStore.On("GetByName", model.MIGRATION_KEY_ADD_MANAGE_SECURE_CONNECTIONS_PERMISSIONS).Return(&model.System{Name: model.MIGRATION_KEY_ADD_MANAGE_SECURE_CONNECTIONS_PERMISSIONS, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyEmojiPermissionsSplit).Return(&model.System{Name: model.MigrationKeyEmojiPermissionsSplit, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyWebhookPermissionsSplit).Return(&model.System{Name: model.MigrationKeyWebhookPermissionsSplit, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyListJoinPublicPrivateTeams).Return(&model.System{Name: model.MigrationKeyListJoinPublicPrivateTeams, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyRemovePermanentDeleteUser).Return(&model.System{Name: model.MigrationKeyRemovePermanentDeleteUser, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddBotPermissions).Return(&model.System{Name: model.MigrationKeyAddBotPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyApplyChannelManageDeleteToChannelUser).Return(&model.System{Name: model.MigrationKeyApplyChannelManageDeleteToChannelUser, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyRemoveChannelManageDeleteFromTeamUser).Return(&model.System{Name: model.MigrationKeyRemoveChannelManageDeleteFromTeamUser, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyViewMembersNewPermission).Return(&model.System{Name: model.MigrationKeyViewMembersNewPermission, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddManageGuestsPermissions).Return(&model.System{Name: model.MigrationKeyAddManageGuestsPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyChannelModerationsPermissions).Return(&model.System{Name: model.MigrationKeyChannelModerationsPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddUseGroupMentionsPermission).Return(&model.System{Name: model.MigrationKeyAddUseGroupMentionsPermission, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddSystemConsolePermissions).Return(&model.System{Name: model.MigrationKeyAddSystemConsolePermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddConvertChannelPermissions).Return(&model.System{Name: model.MigrationKeyAddConvertChannelPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddSystemRolesPermissions).Return(&model.System{Name: model.MigrationKeyAddSystemRolesPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddBillingPermissions).Return(&model.System{Name: model.MigrationKeyAddBillingPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddDownloadComplianceExportResults).Return(&model.System{Name: model.MigrationKeyAddDownloadComplianceExportResults, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddSiteSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddSiteSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddExperimentalSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddExperimentalSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddAuthenticationSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddAuthenticationSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddComplianceSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddExperimentalSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddEnvironmentSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddEnvironmentSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddReportingSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddReportingSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddTestEmailAncillaryPermission).Return(&model.System{Name: model.MigrationKeyAddTestEmailAncillaryPermission, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddAboutSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddAboutSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddIntegrationsSubsectionPermissions).Return(&model.System{Name: model.MigrationKeyAddIntegrationsSubsectionPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddManageSharedChannelPermissions).Return(&model.System{Name: model.MigrationKeyAddManageSharedChannelPermissions, Value: "true"}, nil) + systemStore.On("GetByName", model.MigrationKeyAddManageSecureConnectionsPermissions).Return(&model.System{Name: model.MigrationKeyAddManageSecureConnectionsPermissions, Value: "true"}, nil) systemStore.On("Get").Return(make(model.StringMap), nil) systemStore.On("Save", mock.AnythingOfType("*model.System")).Return(nil) @@ -80,7 +80,7 @@ func GetMockStoreForSetupFunctions() *mocks.Store { channelStore.On("ClearCaches").Return(nil) schemeStore := mocks.SchemeStore{} - schemeStore.On("GetAllPage", model.SCHEME_SCOPE_TEAM, mock.Anything, 100).Return([]*model.Scheme{}, nil) + schemeStore.On("GetAllPage", model.SchemeScopeTeam, mock.Anything, 100).Return([]*model.Scheme{}, nil) teamStore := mocks.TeamStore{} diff --git a/utils/authorization.go b/utils/authorization.go index fcd88b820a..af2be476af 100644 --- a/utils/authorization.go +++ b/utils/authorization.go @@ -10,284 +10,284 @@ import ( func SetRolePermissionsFromConfig(roles map[string]*model.Role, cfg *model.Config, isLicensed bool) map[string]*model.Role { if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelCreation { - case model.PERMISSIONS_ALL: - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, + case model.PermissionsAll: + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionCreatePublicChannel.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionCreatePublicChannel.Id, ) } } else { - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id, + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionCreatePublicChannel.Id, ) } if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement { - case model.PERMISSIONS_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, + case model.PermissionsAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePublicChannelProperties.Id, ) - case model.PERMISSIONS_CHANNEL_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, + case model.PermissionsChannelAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePublicChannelProperties.Id, ) - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions = append( - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, + roles[model.ChannelAdminRoleId].Permissions = append( + roles[model.ChannelAdminRoleId].Permissions, + model.PermissionManagePublicChannelProperties.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePublicChannelProperties.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePublicChannelProperties.Id, ) } if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelDeletion { - case model.PERMISSIONS_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, + case model.PermissionsAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePublicChannel.Id, ) - case model.PERMISSIONS_CHANNEL_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, + case model.PermissionsChannelAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePublicChannel.Id, ) - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions = append( - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, + roles[model.ChannelAdminRoleId].Permissions = append( + roles[model.ChannelAdminRoleId].Permissions, + model.PermissionDeletePublicChannel.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePublicChannel.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePublicChannel.Id, ) } if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelCreation { - case model.PERMISSIONS_ALL: - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, + case model.PermissionsAll: + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionCreatePrivateChannel.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionCreatePrivateChannel.Id, ) } } else { - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id, + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionCreatePrivateChannel.Id, ) } if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement { - case model.PERMISSIONS_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, + case model.PermissionsAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePrivateChannelProperties.Id, ) - case model.PERMISSIONS_CHANNEL_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, + case model.PermissionsChannelAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePrivateChannelProperties.Id, ) - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions = append( - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, + roles[model.ChannelAdminRoleId].Permissions = append( + roles[model.ChannelAdminRoleId].Permissions, + model.PermissionManagePrivateChannelProperties.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePrivateChannelProperties.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePrivateChannelProperties.Id, ) } if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelDeletion { - case model.PERMISSIONS_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, + case model.PermissionsAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePrivateChannel.Id, ) - case model.PERMISSIONS_CHANNEL_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, + case model.PermissionsChannelAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePrivateChannel.Id, ) - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions = append( - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, + roles[model.ChannelAdminRoleId].Permissions = append( + roles[model.ChannelAdminRoleId].Permissions, + model.PermissionDeletePrivateChannel.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePrivateChannel.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePrivateChannel.Id, ) } // Restrict permissions for Private Channel Manage Members if isLicensed { switch *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManageMembers { - case model.PERMISSIONS_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + case model.PermissionsAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePrivateChannelMembers.Id, ) - case model.PERMISSIONS_CHANNEL_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + case model.PermissionsChannelAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePrivateChannelMembers.Id, ) - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions = append( - roles[model.CHANNEL_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + roles[model.ChannelAdminRoleId].Permissions = append( + roles[model.ChannelAdminRoleId].Permissions, + model.PermissionManagePrivateChannelMembers.Id, ) - case model.PERMISSIONS_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + case model.PermissionsTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionManagePrivateChannelMembers.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionManagePrivateChannelMembers.Id, ) } if !*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_EnableOnlyAdminIntegrations { - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id, - model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionManageIncomingWebhooks.Id, + model.PermissionManageOutgoingWebhooks.Id, + model.PermissionManageSlashCommands.Id, ) - roles[model.SYSTEM_USER_ROLE_ID].Permissions = append( - roles[model.SYSTEM_USER_ROLE_ID].Permissions, - model.PERMISSION_MANAGE_OAUTH.Id, + roles[model.SystemUserRoleId].Permissions = append( + roles[model.SystemUserRoleId].Permissions, + model.PermissionManageOAuth.Id, ) } // Grant permissions for inviting and adding users to a team. if isLicensed { - if *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite == model.PERMISSIONS_TEAM_ADMIN { - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_INVITE_USER.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + if *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite == model.PermissionsTeamAdmin { + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionInviteUser.Id, + model.PermissionAddUserToTeam.Id, ) - } else if *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite == model.PERMISSIONS_ALL { - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_INVITE_USER.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + } else if *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite == model.PermissionsAll { + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionInviteUser.Id, + model.PermissionAddUserToTeam.Id, ) } } else { - roles[model.TEAM_USER_ROLE_ID].Permissions = append( - roles[model.TEAM_USER_ROLE_ID].Permissions, - model.PERMISSION_INVITE_USER.Id, - model.PERMISSION_ADD_USER_TO_TEAM.Id, + roles[model.TeamUserRoleId].Permissions = append( + roles[model.TeamUserRoleId].Permissions, + model.PermissionInviteUser.Id, + model.PermissionAddUserToTeam.Id, ) } if isLicensed { switch *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictPostDelete { - case model.PERMISSIONS_DELETE_POST_ALL: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_POST.Id, + case model.PermissionsDeletePostAll: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePost.Id, ) - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, ) - case model.PERMISSIONS_DELETE_POST_TEAM_ADMIN: - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + case model.PermissionsDeletePostTeamAdmin: + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_DELETE_POST.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionDeletePost.Id, ) - roles[model.TEAM_ADMIN_ROLE_ID].Permissions = append( - roles[model.TEAM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_DELETE_POST.Id, - model.PERMISSION_DELETE_OTHERS_POSTS.Id, + roles[model.TeamAdminRoleId].Permissions = append( + roles[model.TeamAdminRoleId].Permissions, + model.PermissionDeletePost.Id, + model.PermissionDeleteOthersPosts.Id, ) } if *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_EnableTeamCreation { - roles[model.SYSTEM_USER_ROLE_ID].Permissions = append( - roles[model.SYSTEM_USER_ROLE_ID].Permissions, - model.PERMISSION_CREATE_TEAM.Id, + roles[model.SystemUserRoleId].Permissions = append( + roles[model.SystemUserRoleId].Permissions, + model.PermissionCreateTeam.Id, ) } if isLicensed { switch *cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost { - case model.ALLOW_EDIT_POST_ALWAYS, model.ALLOW_EDIT_POST_TIME_LIMIT: - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_EDIT_POST.Id, + case model.AllowEditPostAlways, model.AllowEditPostTimeLimit: + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionEditPost.Id, ) - roles[model.SYSTEM_ADMIN_ROLE_ID].Permissions = append( - roles[model.SYSTEM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_EDIT_POST.Id, + roles[model.SystemAdminRoleId].Permissions = append( + roles[model.SystemAdminRoleId].Permissions, + model.PermissionEditPost.Id, ) } } else { - roles[model.CHANNEL_USER_ROLE_ID].Permissions = append( - roles[model.CHANNEL_USER_ROLE_ID].Permissions, - model.PERMISSION_EDIT_POST.Id, + roles[model.ChannelUserRoleId].Permissions = append( + roles[model.ChannelUserRoleId].Permissions, + model.PermissionEditPost.Id, ) - roles[model.SYSTEM_ADMIN_ROLE_ID].Permissions = append( - roles[model.SYSTEM_ADMIN_ROLE_ID].Permissions, - model.PERMISSION_EDIT_POST.Id, + roles[model.SystemAdminRoleId].Permissions = append( + roles[model.SystemAdminRoleId].Permissions, + model.PermissionEditPost.Id, ) } diff --git a/utils/license.go b/utils/license.go index b10d1f31d0..8ce8226850 100644 --- a/utils/license.go +++ b/utils/license.go @@ -51,7 +51,7 @@ type LicenseValidatorImpl struct { func (l *LicenseValidatorImpl) LicenseFromBytes(licenseBytes []byte) (*model.License, *model.AppError) { success, licenseStr := l.ValidateLicense(licenseBytes) if !success { - return nil, model.NewAppError("LicenseFromBytes", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest) + return nil, model.NewAppError("LicenseFromBytes", model.InvalidLicenseError, nil, "", http.StatusBadRequest) } license := model.LicenseFromJson(strings.NewReader(licenseStr)) diff --git a/utils/subpath.go b/utils/subpath.go index 35461a576e..55870a49ca 100644 --- a/utils/subpath.go +++ b/utils/subpath.go @@ -142,7 +142,7 @@ func UpdateAssetsSubpathInDir(subpath, directory string) error { // UpdateAssetsSubpath rewrites assets in the /client directory to assume the application is hosted // at the given subpath instead of at the root. No changes are written unless necessary. func UpdateAssetsSubpath(subpath string) error { - return UpdateAssetsSubpathInDir(subpath, model.CLIENT_DIR) + return UpdateAssetsSubpathInDir(subpath, model.ClientDir) } // UpdateAssetsSubpathFromConfig uses UpdateAssetsSubpath and any path defined in the SiteURL. diff --git a/utils/subpath_test.go b/utils/subpath_test.go index cf3746e215..0433935407 100644 --- a/utils/subpath_test.go +++ b/utils/subpath_test.go @@ -68,7 +68,7 @@ func TestUpdateAssetsSubpath(t *testing.T) { defer os.RemoveAll(tempDir) os.Chdir(tempDir) - err = os.Mkdir(model.CLIENT_DIR, 0700) + err = os.Mkdir(model.ClientDir, 0700) require.NoError(t, err) testCases := []struct { @@ -163,9 +163,9 @@ func TestUpdateAssetsSubpath(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.Description, func(t *testing.T) { - ioutil.WriteFile(filepath.Join(tempDir, model.CLIENT_DIR, "root.html"), []byte(testCase.RootHTML), 0700) - ioutil.WriteFile(filepath.Join(tempDir, model.CLIENT_DIR, "main.css"), []byte(testCase.MainCSS), 0700) - ioutil.WriteFile(filepath.Join(tempDir, model.CLIENT_DIR, "manifest.json"), []byte(testCase.ManifestJSON), 0700) + ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "root.html"), []byte(testCase.RootHTML), 0700) + ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "main.css"), []byte(testCase.MainCSS), 0700) + ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "manifest.json"), []byte(testCase.ManifestJSON), 0700) err := utils.UpdateAssetsSubpath(testCase.Subpath) if testCase.ExpectedError != nil { require.Equal(t, testCase.ExpectedError, err) @@ -173,7 +173,7 @@ func TestUpdateAssetsSubpath(t *testing.T) { require.NoError(t, err) } - contents, err := ioutil.ReadFile(filepath.Join(tempDir, model.CLIENT_DIR, "root.html")) + contents, err := ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "root.html")) require.NoError(t, err) // Rewrite the expected and contents for simpler diffs when failed. @@ -181,11 +181,11 @@ func TestUpdateAssetsSubpath(t *testing.T) { contentsStr := strings.Replace(string(contents), ">", ">\n", -1) require.Equal(t, expectedRootHTML, contentsStr) - contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.CLIENT_DIR, "main.css")) + contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "main.css")) require.NoError(t, err) require.Equal(t, testCase.ExpectedMainCSS, string(contents)) - contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.CLIENT_DIR, "manifest.json")) + contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "manifest.json")) require.NoError(t, err) require.Equal(t, testCase.ExpectedManifestJSON, string(contents)) }) diff --git a/web/context.go b/web/context.go index bd4bb2d65b..43ea4d9868 100644 --- a/web/context.go +++ b/web/context.go @@ -107,13 +107,13 @@ func (c *Context) LogErrorByCode(err *model.AppError) { } func (c *Context) IsSystemAdmin() bool { - return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) + return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) } func (c *Context) SessionRequired() { if !*c.App.Config().ServiceSettings.EnableUserAccessTokens && - c.AppContext.Session().Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN && - c.AppContext.Session().Props[model.SESSION_PROP_IS_BOT] != model.SESSION_PROP_IS_BOT_VALUE { + c.AppContext.Session().Props[model.SessionPropType] == model.SessionTypeUserAccessToken && + c.AppContext.Session().Props[model.SessionPropIsBot] != model.SessionPropIsBotValue { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized) return @@ -126,14 +126,14 @@ func (c *Context) SessionRequired() { } func (c *Context) CloudKeyRequired() { - if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_CLOUD_KEY { + if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.AppContext.Session().Props[model.SessionPropType] != model.SessionTypeCloudKey { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized) return } } func (c *Context) RemoteClusterTokenRequired() { - if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_REMOTECLUSTER_TOKEN { + if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.AppContext.Session().Props[model.SessionPropType] != model.SessionTypeRemoteclusterToken { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized) return } @@ -161,8 +161,8 @@ func (c *Context) MfaRequired() { } // Only required for email and ldap accounts if user.AuthService != "" && - user.AuthService != model.USER_AUTH_SERVICE_EMAIL && - user.AuthService != model.USER_AUTH_SERVICE_LDAP { + user.AuthService != model.UserAuthServiceEmail && + user.AuthService != model.UserAuthServiceLdap { return } @@ -195,7 +195,7 @@ func (c *Context) RemoveSessionCookie(w http.ResponseWriter, r *http.Request) { subpath, _ := utils.GetSubpathFromConfig(c.App.Config()) cookie := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: "", Path: subpath, MaxAge: -1, @@ -235,9 +235,9 @@ func (c *Context) SetCommandNotFoundError() { func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { metrics := c.App.Metrics() - if et := r.Header.Get(model.HEADER_ETAG_CLIENT); etag != "" { + if et := r.Header.Get(model.HeaderEtagClient); etag != "" { if et == etag { - w.Header().Set(model.HEADER_ETAG_SERVER, etag) + w.Header().Set(model.HeaderEtagServer, etag) w.WriteHeader(http.StatusNotModified) if metrics != nil { metrics.IncrementEtagHitCounter(routeName) @@ -298,7 +298,7 @@ func (c *Context) RequireUserId() *Context { return c } - if c.Params.UserId == model.ME { + if c.Params.UserId == model.Me { c.Params.UserId = c.AppContext.Session().UserId } @@ -579,7 +579,7 @@ func (c *Context) RequireEmojiName() *Context { validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`) - if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EMOJI_NAME_MAX_LENGTH || !validName.MatchString(c.Params.EmojiName) { + if c.Params.EmojiName == "" || len(c.Params.EmojiName) > model.EmojiNameMaxLength || !validName.MatchString(c.Params.EmojiName) { c.SetInvalidUrlParam("emoji_name") } @@ -733,5 +733,5 @@ func (c *Context) RequireInvoiceId() *Context { } func (c *Context) GetRemoteID(r *http.Request) string { - return r.Header.Get(model.HEADER_REMOTECLUSTER_ID) + return r.Header.Get(model.HeaderRemoteclusterId) } diff --git a/web/handlers.go b/web/handlers.go index 96864ce2f6..1f650a72a7 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -158,8 +158,8 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { siteURLHeader := app.GetProtocol(r) + "://" + r.Host + subpath c.SetSiteURLHeader(siteURLHeader) - w.Header().Set(model.HEADER_REQUEST_ID, c.AppContext.RequestId()) - w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil)) + w.Header().Set(model.HeaderRequestId, c.AppContext.RequestId()) + w.Header().Set(model.HeaderVersionId, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil)) if *c.App.Config().ServiceSettings.TLSStrictTransport { w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", *c.App.Config().ServiceSettings.TLSStrictTransportMaxAge)) @@ -336,7 +336,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if c.App.Metrics() != nil { c.App.Metrics().IncrementHttpRequest() - if r.URL.Path != model.API_URL_SUFFIX+"/websocket" { + if r.URL.Path != model.ApiUrlSuffix+"/websocket" { elapsed := float64(time.Since(now)) / float64(time.Second) c.App.Metrics().ObserveApiEndpointDuration(h.HandlerName, r.Method, statusCode, elapsed) } @@ -350,11 +350,11 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke csrfCheckPassed := false if csrfCheckNeeded { - csrfHeader := r.Header.Get(model.HEADER_CSRF_TOKEN) + csrfHeader := r.Header.Get(model.HeaderCsrfToken) if csrfHeader == session.GetCSRF() { csrfCheckPassed = true - } else if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML { + } else if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml { // ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657) csrfErrorMessage := "CSRF Header check failed for request - Please upgrade your web application or custom app to set a CSRF Header" diff --git a/web/handlers_test.go b/web/handlers_test.go index 53b86b79db..340e399602 100644 --- a/web/handlers_test.go +++ b/web/handlers_test.go @@ -126,7 +126,7 @@ func TestHandlerServeCSRFToken(t *testing.T) { session := &model.Session{ UserId: th.BasicUser.Id, CreateAt: model.GetMillis(), - Roles: model.SYSTEM_USER_ROLE_ID, + Roles: model.SystemUserRoleId, IsOAuth: false, } session.GenerateCSRF() @@ -148,15 +148,15 @@ func TestHandlerServeCSRFToken(t *testing.T) { } cookie := &http.Cookie{ - Name: model.SESSION_COOKIE_USER, + Name: model.SessionCookieUser, Value: th.BasicUser.Username, } cookie2 := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: session.Token, } cookie3 := &http.Cookie{ - Name: model.SESSION_COOKIE_CSRF, + Name: model.SessionCookieCsrf, Value: session.GetCSRF(), } @@ -166,7 +166,7 @@ func TestHandlerServeCSRFToken(t *testing.T) { request.AddCookie(cookie) request.AddCookie(cookie2) request.AddCookie(cookie3) - request.Header.Add(model.HEADER_CSRF_TOKEN, session.GetCSRF()) + request.Header.Add(model.HeaderCsrfToken, session.GetCSRF()) response := httptest.NewRecorder() handler.ServeHTTP(response, request) @@ -196,7 +196,7 @@ func TestHandlerServeCSRFToken(t *testing.T) { request.AddCookie(cookie) request.AddCookie(cookie2) request.AddCookie(cookie3) - request.Header.Add(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) + request.Header.Add(model.HeaderRequestedWith, model.HeaderRequestedWithXml) response = httptest.NewRecorder() handler.ServeHTTP(response, request) @@ -233,7 +233,7 @@ func TestHandlerServeCSRFToken(t *testing.T) { request.AddCookie(cookie) request.AddCookie(cookie2) request.AddCookie(cookie3) - request.Header.Add(model.HEADER_CSRF_TOKEN, session.GetCSRF()) + request.Header.Add(model.HeaderCsrfToken, session.GetCSRF()) response = httptest.NewRecorder() handlerNoSession.ServeHTTP(response, request) @@ -392,7 +392,7 @@ func TestHandlerServeInvalidToken(t *testing.T) { } cookie := &http.Cookie{ - Name: model.SESSION_COOKIE_TOKEN, + Name: model.SessionCookieToken, Value: "invalid", } @@ -426,7 +426,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HEADER_CSRF_TOKEN, token) + r.Header.Set(model.HeaderCsrfToken, token) session := &model.Session{ Props: map[string]string{ "csrf": token, @@ -458,7 +458,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) + r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml) session := &model.Session{ Props: map[string]string{ "csrf": token, @@ -508,7 +508,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) + r.Header.Set(model.HeaderRequestedWith, model.HeaderRequestedWithXml) session := &model.Session{ Props: map[string]string{ "csrf": token, @@ -629,7 +629,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HEADER_CSRF_TOKEN, token) + r.Header.Set(model.HeaderCsrfToken, token) checked, passed := h.checkCSRFToken(c, r, token, tokenLocation, nil) @@ -655,7 +655,7 @@ func TestCheckCSRFToken(t *testing.T) { AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) - r.Header.Set(model.HEADER_CSRF_TOKEN, token) + r.Header.Set(model.HeaderCsrfToken, token) session := &model.Session{ Props: map[string]string{ "csrf": token, diff --git a/web/oauth.go b/web/oauth.go index 69a9763317..c1ebd901db 100644 --- a/web/oauth.go +++ b/web/oauth.go @@ -56,7 +56,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } if c.AppContext.Session().IsOAuth { - c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) + c.SetPermissionError(model.PermissionEditOtherUsers) c.Err.DetailedError += ", attempted access by oauth app" return } @@ -136,7 +136,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { // here we should check if the user is logged in if c.AppContext.Session().UserId == "" { - if loginHint == model.USER_AUTH_SERVICE_SAML { + if loginHint == model.UserAuthServiceSaml { http.Redirect(w, r, c.GetSiteURLHeader()+"/login/sso/saml?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound) } else { http.Redirect(w, r, c.GetSiteURLHeader()+"/login?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound) @@ -156,7 +156,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { isAuthorized := false - if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.AppContext.Session().UserId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, authRequest.ClientId); err == nil { + if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.AppContext.Session().UserId, model.PreferenceCategoryAuthorizedOAuthApp, authRequest.ClientId); err == nil { // when we support scopes we should check if the scopes match isAuthorized = true } @@ -179,7 +179,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, max-age=31556926") - staticDir, _ := fileutils.FindDir(model.CLIENT_DIR) + staticDir, _ := fileutils.FindDir(model.ClientDir) http.ServeFile(w, r, filepath.Join(staticDir, "root.html")) } @@ -191,12 +191,12 @@ func getAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { grantType := r.FormValue("grant_type") switch grantType { - case model.ACCESS_TOKEN_GRANT_TYPE: + case model.AccessTokenGrantType: if code == "" { c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_code.app_error", nil, "", http.StatusBadRequest) return } - case model.REFRESH_TOKEN_GRANT_TYPE: + case model.RefreshTokenGrantType: if refreshToken == "" { c.Err = model.NewAppError("getAccessToken", "api.oauth.get_access_token.missing_refresh_token.app_error", nil, "", http.StatusBadRequest) return @@ -280,7 +280,7 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { redirectURL := "" if props != nil { action = props["action"] - isMobile = action == model.OAUTH_ACTION_MOBILE + isMobile = action == model.OAuthActionMobile if val, ok := props["redirect_to"]; ok { redirectURL = val hasRedirectURL = redirectURL != "" @@ -310,9 +310,9 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - if action == model.OAUTH_ACTION_EMAIL_TO_SSO { + if action == model.OAuthActionEmailToSSO { redirectURL = c.GetSiteURLHeader() + "/login?extra=signin_change" - } else if action == model.OAUTH_ACTION_SSO_TO_EMAIL { + } else if action == model.OAuthActionSSOToEmail { redirectURL = app.GetProtocol(r) + "://" + r.Host + "/claim?email=" + url.QueryEscape(props["email"]) } else { err = c.App.DoLogin(c.AppContext, w, r, user, "", isMobile, false, false) @@ -331,8 +331,8 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { // New mobile version if isMobile && hasRedirectURL { redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{ - model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token, - model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(), + model.SessionCookieToken: c.AppContext.Session().Token, + model.SessionCookieCsrf: c.AppContext.Session().GetCSRF(), }) utils.RenderMobileAuthComplete(w, redirectURL) return @@ -370,7 +370,7 @@ func loginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAUTH_ACTION_LOGIN, redirectURL, loginHint, false) + authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionLogin, redirectURL, loginHint, false) if err != nil { c.Err = err return @@ -399,7 +399,7 @@ func mobileLoginWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAUTH_ACTION_MOBILE, redirectURL, "", true) + authUrl, err := c.App.GetOAuthLoginEndpoint(w, r, c.Params.Service, teamId, model.OAuthActionMobile, redirectURL, "", true) if err != nil { c.Err = err return diff --git a/web/oauth_test.go b/web/oauth_test.go index 5d2893e802..10d7b1ffff 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -74,7 +74,7 @@ func TestAuthorizeOAuthApp(t *testing.T) { require.Nil(t, appErr) authRequest := &model.AuthorizeRequest{ - ResponseType: model.AUTHCODE_RESPONSE_TYPE, + ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, RedirectUri: rapp.CallbackUrls[0], Scope: "", @@ -93,7 +93,7 @@ func TestAuthorizeOAuthApp(t *testing.T) { require.Equal(t, ru.Query().Get("state"), authRequest.State, "returned state doesn't match") // Test implicit flow - authRequest.ResponseType = model.IMPLICIT_RESPONSE_TYPE + authRequest.ResponseType = model.ImplicitResponseType ruri, resp = ApiClient.AuthorizeOAuthApp(authRequest) require.Nil(t, resp.Error) require.False(t, ruri == "", "redirect url should be set") @@ -125,7 +125,7 @@ func TestAuthorizeOAuthApp(t *testing.T) { _, resp = ApiClient.AuthorizeOAuthApp(authRequest) CheckBadRequestStatus(t, resp) - authRequest.ResponseType = model.AUTHCODE_RESPONSE_TYPE + authRequest.ResponseType = model.AuthCodeResponseType authRequest.ClientId = "" _, resp = ApiClient.AuthorizeOAuthApp(authRequest) CheckBadRequestStatus(t, resp) @@ -168,7 +168,7 @@ func TestDeauthorizeOAuthApp(t *testing.T) { require.Nil(t, appErr) authRequest := &model.AuthorizeRequest{ - ResponseType: model.AUTHCODE_RESPONSE_TYPE, + ResponseType: model.AuthCodeResponseType, ClientId: rapp.Id, RedirectUri: rapp.CallbackUrls[0], Scope: "", @@ -213,8 +213,8 @@ func TestOAuthAccessToken(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) oauthApp := &model.OAuthApp{ Name: "TestApp5" + model.NewId(), @@ -234,7 +234,7 @@ func TestOAuthAccessToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) authRequest := &model.AuthorizeRequest{ - ResponseType: model.AUTHCODE_RESPONSE_TYPE, + ResponseType: model.AuthCodeResponseType, ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], Scope: "all", @@ -252,7 +252,7 @@ func TestOAuthAccessToken(t *testing.T) { _, resp = ApiClient.GetOAuthAccessToken(data) require.NotNil(t, resp.Error, "should have failed - bad grant type") - data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) + data.Set("grant_type", model.AccessTokenGrantType) data.Set("client_id", "") _, resp = ApiClient.GetOAuthAccessToken(data) require.NotNil(t, resp.Error, "should have failed - missing client id") @@ -285,7 +285,7 @@ func TestOAuthAccessToken(t *testing.T) { require.NotNil(t, resp.Error, "should have failed - non-matching redirect uri") // reset data for successful request - data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) + data.Set("grant_type", model.AccessTokenGrantType) data.Set("client_id", oauthApp.Id) data.Set("client_secret", oauthApp.ClientSecret) data.Set("code", rurl.Query().Get("code")) @@ -298,7 +298,7 @@ func TestOAuthAccessToken(t *testing.T) { require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") token, refreshToken = rsp.AccessToken, rsp.RefreshToken - require.Equal(t, rsp.TokenType, model.ACCESS_TOKEN_TYPE, "access token type incorrect") + require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") _, err := ApiClient.DoApiGet("/oauth_test", "") require.Nil(t, err) @@ -318,7 +318,7 @@ func TestOAuthAccessToken(t *testing.T) { _, resp = ApiClient.GetOAuthAccessToken(data) require.NotNil(t, resp.Error, "should have failed - tried to reuse auth code") - data.Set("grant_type", model.REFRESH_TOKEN_GRANT_TYPE) + data.Set("grant_type", model.RefreshTokenGrantType) data.Set("client_id", oauthApp.Id) data.Set("client_secret", oauthApp.ClientSecret) data.Set("refresh_token", "") @@ -333,7 +333,7 @@ func TestOAuthAccessToken(t *testing.T) { require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update") - require.Equal(t, rsp.TokenType, model.ACCESS_TOKEN_TYPE, "access token type incorrect") + require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") ApiClient.SetOAuthToken(rsp.AccessToken) _, err = ApiClient.DoApiGet("/oauth_test", "") @@ -345,7 +345,7 @@ func TestOAuthAccessToken(t *testing.T) { require.NotEmpty(t, rsp.AccessToken, "access token not returned") require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned") require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update") - require.Equal(t, rsp.TokenType, model.ACCESS_TOKEN_TYPE, "access token type incorrect") + require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect") ApiClient.SetOAuthToken(rsp.AccessToken) _, err = ApiClient.DoApiGet("/oauth_test", "") @@ -355,7 +355,7 @@ func TestOAuthAccessToken(t *testing.T) { _, nErr := th.App.Srv().Store.OAuth().SaveAuthData(authData) require.NoError(t, nErr) - data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) + data.Set("grant_type", model.AccessTokenGrantType) data.Set("client_id", oauthApp.Id) data.Set("client_secret", oauthApp.ClientSecret) data.Set("redirect_uri", oauthApp.CallbackUrls[0]) @@ -386,7 +386,7 @@ func TestMobileLoginWithOAuth(t *testing.T) { buffer := &bytes.Buffer{} c.Logger = mlog.NewTestingLogger(t, buffer) provider := &MattermostTestProvider{} - einterfaces.RegisterOauthProvider(model.SERVICE_GITLAB, provider) + einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider) t.Run("Should include redirect URL in the output when valid URL Scheme is passed", func(t *testing.T) { responseWriter := httptest.NewRecorder() @@ -452,7 +452,7 @@ func TestOAuthComplete(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Id = model.NewId() }) stateProps := map[string]string{} - stateProps["action"] = model.OAUTH_ACTION_LOGIN + stateProps["action"] = model.OAuthActionLogin stateProps["team_id"] = th.BasicTeam.Id stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint @@ -474,16 +474,16 @@ func TestOAuthComplete(t *testing.T) { defer func() { th.RestoreDefaultRolePermissions(defaultRolePermissions) }() - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.TEAM_USER_ROLE_ID) - th.AddPermissionToRole(model.PERMISSION_MANAGE_OAUTH.Id, model.SYSTEM_USER_ROLE_ID) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.TeamUserRoleId) + th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId) oauthApp := &model.OAuthApp{ Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{ - ApiClient.Url + "/signup/" + model.SERVICE_GITLAB + "/complete", - ApiClient.Url + "/login/" + model.SERVICE_GITLAB + "/complete", + ApiClient.Url + "/signup/" + model.ServiceGitlab + "/complete", + ApiClient.Url + "/login/" + model.ServiceGitlab + "/complete", }, CreatorId: th.SystemAdminUser.Id, IsTrusted: true, @@ -500,7 +500,7 @@ func TestOAuthComplete(t *testing.T) { provider := &MattermostTestProvider{} authRequest := &model.AuthorizeRequest{ - ResponseType: model.AUTHCODE_RESPONSE_TYPE, + ResponseType: model.AuthCodeResponseType, ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], Scope: "all", @@ -512,31 +512,31 @@ func TestOAuthComplete(t *testing.T) { rurl, _ := url.Parse(redirect) code := rurl.Query().Get("code") - stateProps["action"] = model.OAUTH_ACTION_EMAIL_TO_SSO + stateProps["action"] = model.OAuthActionEmailToSSO delete(stateProps, "team_id") stateProps["redirect_to"] = *th.App.Config().GitLabSettings.AuthEndpoint stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id) stateProps["redirect_to"] = "/oauth/authorize" state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - r, err = HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) + r, err = HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) if err == nil { closeBody(r) } - einterfaces.RegisterOauthProvider(model.SERVICE_GITLAB, provider) + einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider) redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest) require.Nil(t, resp.Error) rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") - r, err = HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) + r, err = HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false) if err == nil { closeBody(r) } _, nErr := th.App.Srv().Store.User().UpdateAuthData( - th.BasicUser.Id, model.SERVICE_GITLAB, &th.BasicUser.Email, th.BasicUser.Email, true) + th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true) require.NoError(t, nErr) redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest) @@ -544,9 +544,9 @@ func TestOAuthComplete(t *testing.T) { rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") - stateProps["action"] = model.OAUTH_ACTION_LOGIN + stateProps["action"] = model.OAuthActionLogin state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { closeBody(r) } @@ -557,7 +557,7 @@ func TestOAuthComplete(t *testing.T) { code = rurl.Query().Get("code") delete(stateProps, "action") state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { closeBody(r) } @@ -566,9 +566,9 @@ func TestOAuthComplete(t *testing.T) { rurl, _ = url.Parse(redirect) code = rurl.Query().Get("code") - stateProps["action"] = model.OAUTH_ACTION_SIGNUP + stateProps["action"] = model.OAuthActionSignup state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) - if r, err := HttpGet(ApiClient.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { + if r, err := HttpGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HttpClient, "", false); err == nil { closeBody(r) } } @@ -591,7 +591,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true }) provider := &MattermostTestProvider{} - einterfaces.RegisterOauthProvider(model.SERVICE_GITLAB, provider) + einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider) responseWriter := httptest.NewRecorder() @@ -603,7 +603,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) { // Renders for mobile app with redirect url stateProps := map[string]string{} - stateProps["action"] = model.OAUTH_ACTION_MOBILE + stateProps["action"] = model.OAuthActionMobile stateProps["redirect_to"] = th.App.Config().NativeAppSettings.AppCustomURLSchemes[0] state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) request2, _ := http.NewRequest(http.MethodGet, th.App.GetSiteURL()+"/signup/gitlab/complete?code=1234&state="+url.QueryEscape(state), nil) @@ -617,7 +617,7 @@ func HttpGet(url string, httpClient *http.Client, authToken string, followRedire rq.Close = true if authToken != "" { - rq.Header.Set(model.HEADER_AUTH, authToken) + rq.Header.Set(model.HeaderAuth, authToken) } if !followRedirect { @@ -710,7 +710,7 @@ func (th *TestHelper) Login(client *model.Client4, user *model.User) { } session, _ = th.App.CreateSession(session) client.AuthToken = session.Token - client.AuthType = model.HEADER_BEARER + client.AuthType = model.HeaderBearer } func (th *TestHelper) Logout(client *model.Client4) { diff --git a/web/saml.go b/web/saml.go index dc0700f35c..205c74ceb9 100644 --- a/web/saml.go +++ b/web/saml.go @@ -35,7 +35,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { return } action := r.URL.Query().Get("action") - isMobile := action == model.OAUTH_ACTION_MOBILE + isMobile := action == model.OAuthActionMobile redirectURL := html.EscapeString(r.URL.Query().Get("redirect_to")) relayProps := map[string]string{} relayState := "" @@ -43,7 +43,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { if action != "" { relayProps["team_id"] = teamId relayProps["action"] = action - if action == model.OAUTH_ACTION_EMAIL_TO_SSO { + if action == model.OAuthActionEmailToSSO { relayProps["email"] = r.URL.Query().Get("email") } } @@ -57,7 +57,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { relayProps["redirect_to"] = redirectURL } - relayProps[model.USER_AUTH_SERVICE_IS_MOBILE] = strconv.FormatBool(isMobile) + relayProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile) if len(relayProps) > 0 { relayState = b64.StdEncoding.EncodeToString([]byte(model.MapToJson(relayProps))) @@ -103,7 +103,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { action := relayProps["action"] auditRec.AddMeta("action", action) - isMobile := action == model.OAUTH_ACTION_MOBILE + isMobile := action == model.OAuthActionMobile redirectURL := "" hasRedirectURL := false if val, ok := relayProps["redirect_to"]; ok { @@ -136,7 +136,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { } switch action { - case model.OAUTH_ACTION_SIGNUP: + case model.OAuthActionSignup: if teamId := relayProps["team_id"]; teamId != "" { if err = c.App.AddUserToTeamByTeamId(c.AppContext, teamId, user); err != nil { c.LogErrorByCode(err) @@ -144,7 +144,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.AddDirectChannels(teamId, user) } - case model.OAUTH_ACTION_EMAIL_TO_SSO: + case model.OAuthActionEmailToSSO: if err = c.App.RevokeAllSessions(user.Id); err != nil { c.Err = err return @@ -154,7 +154,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(user.Id, "Revoked all sessions for user") c.App.Srv().Go(func() { - if err := c.App.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(model.USER_AUTH_SERVICE_SAML)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil { + if err := c.App.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(model.UserAuthServiceSaml)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil { c.LogErrorByCode(model.NewAppError("SendSignInChangeEmail", "api.user.send_sign_in_change_email_and_forget.error", nil, err.Error(), http.StatusInternalServerError)) } }) @@ -179,8 +179,8 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { if isMobile { // Mobile clients with redirect url support redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{ - model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token, - model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(), + model.SessionCookieToken: c.AppContext.Session().Token, + model.SessionCookieCsrf: c.AppContext.Session().GetCSRF(), }) utils.RenderMobileAuthComplete(w, redirectURL) } else { @@ -192,9 +192,9 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { switch action { // Mobile clients with web view implementation - case model.OAUTH_ACTION_MOBILE: + case model.OAuthActionMobile: ReturnStatusOK(w) - case model.OAUTH_ACTION_EMAIL_TO_SSO: + case model.OAuthActionEmailToSSO: http.Redirect(w, r, c.GetSiteURLHeader()+"/login?extra=signin_change", http.StatusFound) default: http.Redirect(w, r, c.GetSiteURLHeader(), http.StatusFound) diff --git a/web/static.go b/web/static.go index 7600ee32ac..6ed5210912 100644 --- a/web/static.go +++ b/web/static.go @@ -26,7 +26,7 @@ func (w *Web) InitStatic() { mlog.Error("Failed to update assets subpath from config", mlog.Err(err)) } - staticDir, _ := fileutils.FindDir(model.CLIENT_DIR) + staticDir, _ := fileutils.FindDir(model.ClientDir) mlog.Debug("Using client directory", mlog.String("clientDir", staticDir)) subpath, _ := utils.GetSubpathFromConfig(w.app.Config()) @@ -72,7 +72,7 @@ func root(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-cache, max-age=31556926, public") - staticDir, _ := fileutils.FindDir(model.CLIENT_DIR) + staticDir, _ := fileutils.FindDir(model.ClientDir) http.ServeFile(w, r, filepath.Join(staticDir, "root.html")) } diff --git a/web/web.go b/web/web.go index e59cf06bbc..c1af1bd326 100644 --- a/web/web.go +++ b/web/web.go @@ -102,6 +102,6 @@ func IsOAuthApiCall(a app.AppIface, r *http.Request) bool { func ReturnStatusOK(w http.ResponseWriter) { m := make(map[string]string) - m[model.STATUS] = model.STATUS_OK + m[model.STATUS] = model.StatusOk w.Write([]byte(model.MapToJson(m))) } diff --git a/web/web_test.go b/web/web_test.go index d4862503a3..23fffd00e0 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -148,15 +148,15 @@ func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API { } func (th *TestHelper) InitBasic() *TestHelper { - th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_ADMIN_ROLE_ID}) + th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemAdminRoleId}) - user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_USER_ROLE_ID}) + user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SystemUserRoleId}) - team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TEAM_OPEN}) + team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TeamOpen}) th.App.JoinUserToTeam(th.Context, team, user, "") - channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id, CreatorId: user.Id}, true) + channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id, CreatorId: user.Id}, true) th.BasicUser = user th.BasicChannel = channel diff --git a/web/webhook_test.go b/web/webhook_test.go index eb84792948..723453b5be 100644 --- a/web/webhook_test.go +++ b/web/webhook_test.go @@ -134,7 +134,7 @@ func TestIncomingWebhook(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) // Read only default channel should fail. - resp, err := http.Post(url, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL))) + resp, err := http.Post(url, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName))) require.NoError(t, err) assert.True(t, resp.StatusCode != http.StatusOK) @@ -148,7 +148,7 @@ func TestIncomingWebhook(t *testing.T) { require.Nil(t, appErr) adminUrl := ApiClient.Url + "/hooks/" + adminHook.Id - resp, err = http.Post(adminUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DEFAULT_CHANNEL))) + resp, err = http.Post(adminUrl, "application/json", strings.NewReader(fmt.Sprintf("{\"text\":\"this is a test\", \"channel\":\"%s\"}", model.DefaultChannelName))) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) @@ -232,7 +232,7 @@ func TestIncomingWebhook(t *testing.T) { }) t.Run("ChannelLockedWebhook", func(t *testing.T) { - channel, err := th.App.CreateChannel(th.Context, &model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.CHANNEL_OPEN, CreatorId: th.BasicUser.Id}, true) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.ChannelTypeOpen, CreatorId: th.BasicUser.Id}, true) require.Nil(t, err) hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id, ChannelLocked: true}) @@ -271,7 +271,7 @@ func TestCommandWebhooks(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, URL: "http://nowhere.com", - Method: model.COMMAND_METHOD_POST, + Method: model.CommandMethodPost, Trigger: "delayed"}) require.Nil(t, appErr) diff --git a/wsapi/user.go b/wsapi/user.go index b4effc9f50..607a0eab50 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -26,7 +26,7 @@ func (api *API) userTyping(req *model.WebSocketRequest) (map[string]interface{}, return nil, NewInvalidWebSocketParamError(req.Action, "channel_id") } - if !api.App.SessionHasPermissionToChannel(req.Session, channelId, model.PERMISSION_CREATE_POST) { + if !api.App.SessionHasPermissionToChannel(req.Session, channelId, model.PermissionCreatePost) { return nil, NewInvalidWebSocketParamError(req.Action, "channel_id") } diff --git a/wsapi/websocket_handler.go b/wsapi/websocket_handler.go index fcd7b9745d..c90700e93b 100644 --- a/wsapi/websocket_handler.go +++ b/wsapi/websocket_handler.go @@ -68,7 +68,7 @@ func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketR return } - resp := model.NewWebSocketResponse(model.STATUS_OK, r.Seq, data) + resp := model.NewWebSocketResponse(model.StatusOk, r.Seq, data) hub.SendMessage(conn, resp) }