From 8e19ba029f889519d93cf272960dce858971106c Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 18 Oct 2017 15:36:43 -0700 Subject: Reduce utils.Cfg references (#7650) * app.UpdateConfig method * test fix * another test fix * the config override option as-was is just error prone, remove it for now * derp --- api/admin.go | 6 +- api/admin_test.go | 62 +++++----- api/api.go | 2 +- api/apitestlib.go | 17 +-- api/channel_test.go | 228 ++++++++++++++++++++++++------------- api/command_help_test.go | 11 +- api/command_loadtest_test.go | 31 +++-- api/command_test.go | 51 +++++---- api/context.go | 8 +- api/emoji.go | 14 +-- api/emoji_test.go | 42 +++---- api/file.go | 20 ++-- api/file_test.go | 74 ++++++------ api/general.go | 2 +- api/general_test.go | 11 +- api/license.go | 2 +- api/oauth.go | 2 +- api/oauth_test.go | 106 ++++++++--------- api/post.go | 2 +- api/post_test.go | 70 +++++++----- api/status_test.go | 7 +- api/team.go | 4 +- api/team_test.go | 18 +-- api/user.go | 40 +++---- api/user_test.go | 184 +++++++++++++++--------------- api/webhook_test.go | 166 +++++++++++++-------------- api/websocket_test.go | 11 +- api4/apitestlib.go | 17 +-- api4/brand.go | 4 +- api4/channel_test.go | 112 ++++++++++++------ api4/command_help_test.go | 11 +- api4/command_test.go | 97 +++++++++------- api4/context.go | 6 +- api4/elasticsearch.go | 2 +- api4/emoji.go | 12 +- api4/emoji_test.go | 44 +++---- api4/file.go | 12 +- api4/file_test.go | 55 +++++---- api4/oauth.go | 4 +- api4/oauth_test.go | 134 +++++++++++----------- api4/openGraph.go | 2 +- api4/openGraph_test.go | 21 ++-- api4/plugin.go | 9 +- api4/plugin_test.go | 19 ++-- api4/post_test.go | 34 +++--- api4/system.go | 12 +- api4/system_test.go | 37 +++--- api4/team_test.go | 46 ++++---- api4/user.go | 24 ++-- api4/user_test.go | 166 +++++++++++++-------------- api4/webhook.go | 2 +- api4/webhook_test.go | 164 +++++++++++++------------- api4/webrtc_test.go | 9 +- app/admin.go | 24 ++-- app/analytics.go | 7 +- app/app.go | 10 +- app/apptestlib.go | 9 +- app/authentication.go | 4 +- app/brand.go | 5 +- app/channel.go | 12 +- app/cluster_discovery.go | 2 +- app/command.go | 22 ++-- app/command_channel_rename_test.go | 2 +- app/command_help.go | 3 +- app/command_invite_people.go | 4 +- app/command_loadtest.go | 2 +- app/compliance.go | 6 +- app/diagnostics.go | 4 +- app/elasticsearch.go | 5 +- app/email.go | 4 +- app/email_batching.go | 16 +-- app/emoji.go | 4 +- app/file.go | 2 +- app/import.go | 4 +- app/ldap.go | 4 +- app/login.go | 7 +- app/notification.go | 36 +++--- app/oauth.go | 32 +++--- app/options.go | 28 ----- app/plugins.go | 8 +- app/post.go | 20 ++-- app/post_test.go | 4 +- app/security_update_check.go | 4 +- app/server.go | 24 ++-- app/session.go | 8 +- app/status.go | 12 +- app/team.go | 6 +- app/user.go | 28 ++--- app/webhook.go | 38 +++---- app/webhook_test.go | 2 +- web/web_test.go | 8 +- 91 files changed, 1390 insertions(+), 1276 deletions(-) diff --git a/api/admin.go b/api/admin.go index 5b532c81a..ff5971734 100644 --- a/api/admin.go +++ b/api/admin.go @@ -235,12 +235,12 @@ func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { } func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadBrandImage", "api.admin.upload_brand_image.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { c.Err = model.NewAppError("uploadBrandImage", "api.admin.upload_brand_image.parse.app_error", nil, "", http.StatusBadRequest) return } @@ -358,7 +358,7 @@ func samlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { } func addCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize) + err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/api/admin_test.go b/api/admin_test.go index e4ff1c202..5c11d5a5c 100644 --- a/api/admin_test.go +++ b/api/admin_test.go @@ -118,8 +118,8 @@ func TestReloadConfig(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.TeamSettings.EnableOpenServer = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) } func TestInvalidateAllCache(t *testing.T) { @@ -143,13 +143,13 @@ func TestSaveConfig(t *testing.T) { t.Fatal("Shouldn't have permissions") } - *utils.Cfg.TeamSettings.EnableOpenServer = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) if _, err := th.SystemAdminClient.SaveConfig(utils.Cfg); err != nil { t.Fatal(err) } - *utils.Cfg.TeamSettings.EnableOpenServer = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) } func TestRecycleDatabaseConnection(t *testing.T) { @@ -169,27 +169,27 @@ func TestEmailTest(t *testing.T) { th := Setup().InitBasic().InitSystemAdmin() defer th.TearDown() - SendEmailNotifications := utils.Cfg.EmailSettings.SendEmailNotifications - SMTPServer := utils.Cfg.EmailSettings.SMTPServer - SMTPPort := utils.Cfg.EmailSettings.SMTPPort - FeedbackEmail := utils.Cfg.EmailSettings.FeedbackEmail + SendEmailNotifications := th.App.Config().EmailSettings.SendEmailNotifications + SMTPServer := th.App.Config().EmailSettings.SMTPServer + SMTPPort := th.App.Config().EmailSettings.SMTPPort + FeedbackEmail := th.App.Config().EmailSettings.FeedbackEmail defer func() { - utils.Cfg.EmailSettings.SendEmailNotifications = SendEmailNotifications - utils.Cfg.EmailSettings.SMTPServer = SMTPServer - utils.Cfg.EmailSettings.SMTPPort = SMTPPort - utils.Cfg.EmailSettings.FeedbackEmail = FeedbackEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = SendEmailNotifications }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPServer = SMTPServer }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPPort = SMTPPort }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.FeedbackEmail = FeedbackEmail }) }() - utils.Cfg.EmailSettings.SendEmailNotifications = false - utils.Cfg.EmailSettings.SMTPServer = "" - utils.Cfg.EmailSettings.SMTPPort = "" - utils.Cfg.EmailSettings.FeedbackEmail = "" + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPServer = "" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPPort = "" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.FeedbackEmail = "" }) - if _, err := th.BasicClient.TestEmail(utils.Cfg); err == nil { + if _, err := th.BasicClient.TestEmail(th.App.Config()); err == nil { t.Fatal("Shouldn't have permissions") } - if _, err := th.SystemAdminClient.TestEmail(utils.Cfg); err == nil { + if _, err := th.SystemAdminClient.TestEmail(th.App.Config()); err == nil { t.Fatal("should have errored") } else { if err.Id != "api.admin.test_email.missing_server" { @@ -202,11 +202,11 @@ func TestLdapTest(t *testing.T) { th := Setup().InitBasic().InitSystemAdmin() defer th.TearDown() - if _, err := th.BasicClient.TestLdap(utils.Cfg); err == nil { + if _, err := th.BasicClient.TestLdap(th.App.Config()); err == nil { t.Fatal("Shouldn't have permissions") } - if _, err := th.SystemAdminClient.TestLdap(utils.Cfg); err == nil { + if _, err := th.SystemAdminClient.TestLdap(th.App.Config()); err == nil { t.Fatal("should have errored") } } @@ -221,11 +221,11 @@ func TestGetTeamAnalyticsStandard(t *testing.T) { t.Fatal("Shouldn't have permissions") } - maxUsersForStats := *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics + maxUsersForStats := *th.App.Config().AnalyticsSettings.MaxUsersForStatistics defer func() { - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = maxUsersForStats + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = maxUsersForStats }) }() - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = 1000000 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = 1000000 }) if result, err := th.SystemAdminClient.GetTeamAnalytics(th.BasicTeam.Id, "standard"); err != nil { t.Fatal(err) @@ -339,7 +339,7 @@ func TestGetTeamAnalyticsStandard(t *testing.T) { } } - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = 1 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = 1 }) if result, err := th.SystemAdminClient.GetSystemAnalytics("standard"); err != nil { t.Fatal(err) @@ -452,11 +452,11 @@ func TestGetTeamAnalyticsExtra(t *testing.T) { t.Fatal("Shouldn't have permissions") } - maxUsersForStats := *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics + maxUsersForStats := *th.App.Config().AnalyticsSettings.MaxUsersForStatistics defer func() { - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = maxUsersForStats + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = maxUsersForStats }) }() - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = 1000000 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = 1000000 }) if result, err := th.SystemAdminClient.GetTeamAnalytics(th.BasicTeam.Id, "extra_counts"); err != nil { t.Fatal(err) @@ -560,7 +560,7 @@ func TestGetTeamAnalyticsExtra(t *testing.T) { } } - *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics = 1 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnalyticsSettings.MaxUsersForStatistics = 1 }) if result, err := th.SystemAdminClient.GetSystemAnalytics("extra_counts"); err != nil { t.Fatal(err) @@ -678,11 +678,11 @@ func TestDisableAPIv3(t *testing.T) { Client := th.BasicClient - enableAPIv3 := *utils.Cfg.ServiceSettings.EnableAPIv3 + enableAPIv3 := *th.App.Config().ServiceSettings.EnableAPIv3 defer func() { - *utils.Cfg.ServiceSettings.EnableAPIv3 = enableAPIv3 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableAPIv3 = enableAPIv3 }) }() - *utils.Cfg.ServiceSettings.EnableAPIv3 = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableAPIv3 = false }) _, err := Client.GetUser(th.BasicUser.Id, "") diff --git a/api/api.go b/api/api.go index 59fc87c71..4f593cfa5 100644 --- a/api/api.go +++ b/api/api.go @@ -117,7 +117,7 @@ func Init(a *app.App, root *mux.Router) *API { a.InitEmailBatching() - if *utils.Cfg.ServiceSettings.EnableAPIv3 { + if *a.Config().ServiceSettings.EnableAPIv3 { l4g.Info("API version 3 is scheduled for deprecation. Please see https://api.mattermost.com for details.") } diff --git a/api/apitestlib.go b/api/apitestlib.go index 4c4773318..5fc94cfec 100644 --- a/api/apitestlib.go +++ b/api/apitestlib.go @@ -71,28 +71,29 @@ func setupTestHelper(enterprise bool) *TestHelper { var options []app.Option if testStore != nil { options = append(options, app.StoreOverride(testStore)) - options = append(options, app.ConfigOverride(func(cfg *model.Config) { - cfg.ServiceSettings.ListenAddress = new(string) - *cfg.ServiceSettings.ListenAddress = ":0" - })) } th := &TestHelper{ App: app.New(options...), } - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.Cfg.EmailSettings.SendEmailNotifications = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = true }) utils.DisableDebugLogForTest() + prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress + if testStore != nil { + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) + } th.App.StartServer() + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) api4.Init(th.App, th.App.Srv.Router, false) Init(th.App, th.App.Srv.Router) wsapi.Init(th.App, th.App.Srv.WebSocketRouter) utils.EnableDebugLogForTest() th.App.Srv.Store.MarkSystemRanUnitTests() - *utils.Cfg.TeamSettings.EnableOpenServer = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) utils.SetIsLicensed(enterprise) if enterprise { diff --git a/api/channel_test.go b/api/channel_test.go index 64a09f78d..ade7993b5 100644 --- a/api/channel_test.go +++ b/api/channel_test.go @@ -99,17 +99,17 @@ func TestCreateChannel(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetDefaultRolesBasedOnConfig() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) @@ -124,8 +124,12 @@ func TestCreateChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic2() @@ -150,8 +154,12 @@ func TestCreateChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() channel2.Name = "zz" + model.NewId() + "a" @@ -186,8 +194,8 @@ func TestCreateChannel(t *testing.T) { t.Fatal("should have succeeded") } - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_ALL }) utils.SetDefaultRolesBasedOnConfig() } @@ -361,17 +369,17 @@ func TestUpdateChannel(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -394,8 +402,12 @@ func TestUpdateChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -433,8 +445,12 @@ func TestUpdateChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -459,8 +475,12 @@ func TestUpdateChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -600,17 +620,17 @@ func TestUpdateChannelHeader(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -637,8 +657,12 @@ func TestUpdateChannelHeader(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.MakeUserChannelUser(th.BasicUser, channel2) th.MakeUserChannelUser(th.BasicUser, channel3) @@ -662,8 +686,12 @@ func TestUpdateChannelHeader(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.UpdateChannelHeader(data2); err == nil { @@ -685,8 +713,12 @@ func TestUpdateChannelHeader(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.UpdateChannelHeader(data2); err == nil { @@ -784,17 +816,17 @@ func TestUpdateChannelPurpose(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -821,8 +853,12 @@ func TestUpdateChannelPurpose(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.MakeUserChannelUser(th.BasicUser, channel2) th.MakeUserChannelUser(th.BasicUser, channel3) @@ -846,8 +882,12 @@ func TestUpdateChannelPurpose(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.UpdateChannelPurpose(data2); err == nil { @@ -869,8 +909,12 @@ func TestUpdateChannelPurpose(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.UpdateChannelPurpose(data2); err == nil { @@ -1358,17 +1402,17 @@ func TestDeleteChannel(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1397,8 +1441,12 @@ func TestDeleteChannel(t *testing.T) { utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginSystemAdmin() @@ -1453,8 +1501,12 @@ func TestDeleteChannel(t *testing.T) { utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginSystemAdmin() @@ -1488,8 +1540,12 @@ func TestDeleteChannel(t *testing.T) { utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginSystemAdmin() @@ -1540,8 +1596,8 @@ func TestDeleteChannel(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_ALL }) utils.SetDefaultRolesBasedOnConfig() } @@ -1619,11 +1675,15 @@ func TestAddChannelMember(t *testing.T) { } // Test policy does not apply to TE. - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManageMembers defer func() { - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + }) }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() channel3 := &model.Channel{DisplayName: "A Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} @@ -1641,7 +1701,7 @@ func TestAddChannelMember(t *testing.T) { utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1656,7 +1716,9 @@ func TestAddChannelMember(t *testing.T) { } // Test with CHANNEL_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1681,7 +1743,9 @@ func TestAddChannelMember(t *testing.T) { } // Test with TEAM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1706,7 +1770,9 @@ func TestAddChannelMember(t *testing.T) { } // Test with SYSTEM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1794,11 +1860,15 @@ func TestRemoveChannelMember(t *testing.T) { th.LoginBasic() // Test policy does not apply to TE. - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManageMembers defer func() { - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + }) }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() channel3 := &model.Channel{DisplayName: "A Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, TeamId: team.Id} @@ -1817,7 +1887,7 @@ func TestRemoveChannelMember(t *testing.T) { utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1833,7 +1903,9 @@ func TestRemoveChannelMember(t *testing.T) { } // Test with CHANNEL_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1858,7 +1930,9 @@ func TestRemoveChannelMember(t *testing.T) { } // Test with TEAM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1884,7 +1958,9 @@ func TestRemoveChannelMember(t *testing.T) { } // Test with SYSTEM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() diff --git a/api/command_help_test.go b/api/command_help_test.go index 4ca9ef152..181298d7e 100644 --- a/api/command_help_test.go +++ b/api/command_help_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestHelpCommand(t *testing.T) { @@ -17,18 +16,20 @@ func TestHelpCommand(t *testing.T) { Client := th.BasicClient channel := th.BasicChannel - HelpLink := *utils.Cfg.SupportSettings.HelpLink + HelpLink := *th.App.Config().SupportSettings.HelpLink defer func() { - *utils.Cfg.SupportSettings.HelpLink = HelpLink + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = HelpLink }) }() - *utils.Cfg.SupportSettings.HelpLink = "" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" }) rs1 := Client.Must(Client.Command(channel.Id, "/help ")).Data.(*model.CommandResponse) if rs1.GotoLocation != model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK { t.Fatal("failed to default help link") } - *utils.Cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" + }) rs2 := Client.Must(Client.Command(channel.Id, "/help ")).Data.(*model.CommandResponse) if rs2.GotoLocation != "https://docs.mattermost.com/guides/user.html" { t.Fatal("failed to help link") diff --git a/api/command_loadtest_test.go b/api/command_loadtest_test.go index 346b3379e..62545ae64 100644 --- a/api/command_loadtest_test.go +++ b/api/command_loadtest_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestLoadTestHelpCommands(t *testing.T) { @@ -20,12 +19,12 @@ func TestLoadTestHelpCommands(t *testing.T) { channel := th.BasicChannel // enable testing to use /test but don't save it since we don't want to overwrite config.json - enableTesting := utils.Cfg.ServiceSettings.EnableTesting + enableTesting := th.App.Config().ServiceSettings.EnableTesting defer func() { - utils.Cfg.ServiceSettings.EnableTesting = enableTesting + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = enableTesting }) }() - utils.Cfg.ServiceSettings.EnableTesting = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = true }) rs := Client.Must(Client.Command(channel.Id, "/test help")).Data.(*model.CommandResponse) if !strings.Contains(rs.Text, "Mattermost testing commands to help") { @@ -43,12 +42,12 @@ func TestLoadTestSetupCommands(t *testing.T) { channel := th.BasicChannel // enable testing to use /test but don't save it since we don't want to overwrite config.json - enableTesting := utils.Cfg.ServiceSettings.EnableTesting + enableTesting := th.App.Config().ServiceSettings.EnableTesting defer func() { - utils.Cfg.ServiceSettings.EnableTesting = enableTesting + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = enableTesting }) }() - utils.Cfg.ServiceSettings.EnableTesting = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = true }) rs := Client.Must(Client.Command(channel.Id, "/test setup fuzz 1 1 1")).Data.(*model.CommandResponse) if rs.Text != "Created enviroment" { @@ -66,12 +65,12 @@ func TestLoadTestUsersCommands(t *testing.T) { channel := th.BasicChannel // enable testing to use /test but don't save it since we don't want to overwrite config.json - enableTesting := utils.Cfg.ServiceSettings.EnableTesting + enableTesting := th.App.Config().ServiceSettings.EnableTesting defer func() { - utils.Cfg.ServiceSettings.EnableTesting = enableTesting + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = enableTesting }) }() - utils.Cfg.ServiceSettings.EnableTesting = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = true }) rs := Client.Must(Client.Command(channel.Id, "/test users fuzz 1 2")).Data.(*model.CommandResponse) if rs.Text != "Added users" { @@ -89,12 +88,12 @@ func TestLoadTestChannelsCommands(t *testing.T) { channel := th.BasicChannel // enable testing to use /test but don't save it since we don't want to overwrite config.json - enableTesting := utils.Cfg.ServiceSettings.EnableTesting + enableTesting := th.App.Config().ServiceSettings.EnableTesting defer func() { - utils.Cfg.ServiceSettings.EnableTesting = enableTesting + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = enableTesting }) }() - utils.Cfg.ServiceSettings.EnableTesting = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = true }) rs := Client.Must(Client.Command(channel.Id, "/test channels fuzz 1 2")).Data.(*model.CommandResponse) if rs.Text != "Added channels" { @@ -112,12 +111,12 @@ func TestLoadTestPostsCommands(t *testing.T) { channel := th.BasicChannel // enable testing to use /test but don't save it since we don't want to overwrite config.json - enableTesting := utils.Cfg.ServiceSettings.EnableTesting + enableTesting := th.App.Config().ServiceSettings.EnableTesting defer func() { - utils.Cfg.ServiceSettings.EnableTesting = enableTesting + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = enableTesting }) }() - utils.Cfg.ServiceSettings.EnableTesting = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableTesting = true }) rs := Client.Must(Client.Command(channel.Id, "/test posts fuzz 2 3 2")).Data.(*model.CommandResponse) if rs.Text != "Added posts" { diff --git a/api/command_test.go b/api/command_test.go index 948193852..7eadca124 100644 --- a/api/command_test.go +++ b/api/command_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestListCommands(t *testing.T) { @@ -45,11 +44,11 @@ func TestCreateCommand(t *testing.T) { user := th.SystemAdminUser team := th.SystemAdminTeam - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd1 := &model.Command{ CreatorId: user.Id, @@ -108,11 +107,11 @@ func TestListTeamCommands(t *testing.T) { Client := th.SystemAdminClient - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd1 := &model.Command{URL: "http://nowhere.com", Method: model.COMMAND_METHOD_POST, Trigger: "trigger"} cmd1 = Client.Must(Client.CreateCommand(cmd1)).Data.(*model.Command) @@ -136,11 +135,11 @@ func TestUpdateCommand(t *testing.T) { user := th.SystemAdminUser team := th.SystemAdminTeam - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd1 := &model.Command{ CreatorId: user.Id, @@ -175,11 +174,11 @@ func TestRegenToken(t *testing.T) { Client := th.SystemAdminClient - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd := &model.Command{URL: "http://nowhere.com", Method: model.COMMAND_METHOD_POST, Trigger: "trigger"} cmd = Client.Must(Client.CreateCommand(cmd)).Data.(*model.Command) @@ -202,14 +201,14 @@ func TestDeleteCommand(t *testing.T) { Client := th.SystemAdminClient - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - onlyAdminIntegration := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + onlyAdminIntegration := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - *utils.Cfg.ServiceSettings.EnableCommands = enableCommands - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = onlyAdminIntegration + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = onlyAdminIntegration }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) cmd := &model.Command{URL: "http://nowhere.com", Method: model.COMMAND_METHOD_POST, Trigger: "trigger"} cmd = Client.Must(Client.CreateCommand(cmd)).Data.(*model.Command) @@ -248,14 +247,16 @@ func TestTestCommand(t *testing.T) { Client := th.SystemAdminClient channel1 := th.SystemAdminChannel - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) cmd1 := &model.Command{ URL: fmt.Sprintf("http://localhost:%v", th.App.Srv.ListenAddr.Port) + model.API_URL_SUFFIX_V3 + "/teams/command_test", diff --git a/api/context.go b/api/context.go index 0322b6c43..aa5f2a163 100644 --- a/api/context.go +++ b/api/context.go @@ -191,7 +191,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Path = "/" + strings.Join(splitURL[2:], "/") } - if h.isApi && !*utils.Cfg.ServiceSettings.EnableAPIv3 { + if h.isApi && !*c.App.Config().ServiceSettings.EnableAPIv3 { c.Err = model.NewAppError("ServeHTTP", "api.context.v3_disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -229,7 +229,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Err.Where = r.URL.Path // Block out detailed error when not in developer mode - if !*utils.Cfg.ServiceSettings.EnableDeveloper { + if !*c.App.Config().ServiceSettings.EnableDeveloper { c.Err.DetailedError = "" } @@ -294,7 +294,7 @@ func (c *Context) LogDebug(err *model.AppError) { } func (c *Context) UserRequired() { - if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens && c.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN { + if !*c.App.Config().ServiceSettings.EnableUserAccessTokens && c.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized) return } @@ -307,7 +307,7 @@ func (c *Context) UserRequired() { func (c *Context) MfaRequired() { // Must be licensed for MFA and have it configured for enforcement - if !utils.IsLicensed() || !*utils.License().Features.MFA || !*utils.Cfg.ServiceSettings.EnableMultifactorAuthentication || !*utils.Cfg.ServiceSettings.EnforceMultifactorAuthentication { + if !utils.IsLicensed() || !*utils.License().Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication { return } diff --git a/api/emoji.go b/api/emoji.go index b4ad9fa2c..4a9995d64 100644 --- a/api/emoji.go +++ b/api/emoji.go @@ -31,7 +31,7 @@ func (api *API) InitEmoji() { } func getEmoji(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("getEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -46,7 +46,7 @@ func getEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("createEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -57,7 +57,7 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("createEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return } @@ -124,12 +124,12 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("deleteEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("deleteImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return } @@ -163,12 +163,12 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } func getEmojiImage(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("getEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("getEmojiImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api/emoji_test.go b/api/emoji_test.go index 5ee034e9c..8aae047d4 100644 --- a/api/emoji_test.go +++ b/api/emoji_test.go @@ -22,11 +22,11 @@ func TestGetEmoji(t *testing.T) { Client := th.BasicClient - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) emojis := []*model.Emoji{ { @@ -102,11 +102,11 @@ func TestCreateEmoji(t *testing.T) { Client := th.BasicClient - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false }) emoji := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -118,7 +118,7 @@ func TestCreateEmoji(t *testing.T) { t.Fatal("shouldn't be able to create an emoji when they're disabled") } - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) // try to create a valid gif emoji when they're enabled if emojiResult, err := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif"); err != nil { @@ -226,11 +226,11 @@ func TestDeleteEmoji(t *testing.T) { Client := th.BasicClient - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false }) emoji1 := createTestEmoji(t, th.App, &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -241,7 +241,7 @@ func TestDeleteEmoji(t *testing.T) { t.Fatal("shouldn't have been able to delete an emoji when they're disabled") } - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) if deleted, err := Client.DeleteEmoji(emoji1.Id); err != nil { t.Fatal(err) @@ -286,14 +286,18 @@ func TestGetEmojiImage(t *testing.T) { Client := th.BasicClient - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji - RestrictCustomEmojiCreation := *utils.Cfg.ServiceSettings.RestrictCustomEmojiCreation + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji + RestrictCustomEmojiCreation := *th.App.Config().ServiceSettings.RestrictCustomEmojiCreation defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji - *utils.Cfg.ServiceSettings.RestrictCustomEmojiCreation = RestrictCustomEmojiCreation + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.RestrictCustomEmojiCreation = RestrictCustomEmojiCreation + }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true - *utils.Cfg.ServiceSettings.RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ALL + }) emoji1 := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -302,13 +306,13 @@ func TestGetEmojiImage(t *testing.T) { emoji1 = Client.MustGeneric(Client.CreateEmoji(emoji1, utils.CreateTestGif(t, 10, 10), "image.gif")).(*model.Emoji) defer func() { Client.MustGeneric(Client.DeleteEmoji(emoji1.Id)) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false }) if _, err := Client.DoApiGet(Client.GetCustomEmojiImageUrl(emoji1.Id), "", ""); err == nil { t.Fatal("should've failed to get emoji image when disabled") } - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) if resp, err := Client.DoApiGet(Client.GetCustomEmojiImageUrl(emoji1.Id), "", ""); err != nil { t.Fatal(err) diff --git a/api/file.go b/api/file.go index 28007f222..bcb79bd5c 100644 --- a/api/file.go +++ b/api/file.go @@ -46,17 +46,17 @@ func (api *API) InitFile() { } func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.FileSettings.EnableFileAttachments { + if !*c.App.Config().FileSettings.EnableFileAttachments { c.Err = model.NewAppError("uploadFile", "api.file.attachments.disabled.app_error", nil, "", http.StatusNotImplemented) return } - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadFile", "api.file.upload_file.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -159,7 +159,7 @@ func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) { } func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { - if !utils.Cfg.FileSettings.EnablePublicLink { + if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -173,7 +173,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { hash := r.URL.Query().Get("h") if len(hash) > 0 { - correctHash := app.GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) + correctHash := app.GeneratePublicLinkHash(info.Id, *c.App.Config().FileSettings.PublicLinkSalt) if hash != correctHash { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) @@ -196,7 +196,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { } func getFileInfoForRequest(c *Context, r *http.Request, requireFileVisible bool) (*model.FileInfo, *model.AppError) { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { return nil, model.NewAppError("getFileInfoForRequest", "api.file.get_info_for_request.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -231,10 +231,10 @@ func getFileInfoForRequest(c *Context, r *http.Request, requireFileVisible bool) } func getPublicFileOld(c *Context, w http.ResponseWriter, r *http.Request) { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("getPublicFile", "api.file.get_public_file_old.storage.app_error", nil, "", http.StatusNotImplemented) return - } else if !utils.Cfg.FileSettings.EnablePublicLink { + } else if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -249,7 +249,7 @@ func getPublicFileOld(c *Context, w http.ResponseWriter, r *http.Request) { hash := r.URL.Query().Get("h") if len(hash) > 0 { - correctHash := app.GeneratePublicLinkHash(filename, *utils.Cfg.FileSettings.PublicLinkSalt) + correctHash := app.GeneratePublicLinkHash(filename, *c.App.Config().FileSettings.PublicLinkSalt) if hash != correctHash { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) @@ -316,7 +316,7 @@ func writeFileResponse(filename string, contentType string, bytes []byte, w http } func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) { - if !utils.Cfg.FileSettings.EnablePublicLink { + if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api/file_test.go b/api/file_test.go index 2935f0804..31eb3daef 100644 --- a/api/file_test.go +++ b/api/file_test.go @@ -27,7 +27,7 @@ func TestUploadFile(t *testing.T) { th := Setup().InitBasic().InitSystemAdmin() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Logf("skipping because no file driver is enabled") return } @@ -121,11 +121,11 @@ func TestUploadFile(t *testing.T) { t.Fatal("should have failed - bad channel id") } - enableFileAttachments := *utils.Cfg.FileSettings.EnableFileAttachments + enableFileAttachments := *th.App.Config().FileSettings.EnableFileAttachments defer func() { - *utils.Cfg.FileSettings.EnableFileAttachments = enableFileAttachments + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = enableFileAttachments }) }() - *utils.Cfg.FileSettings.EnableFileAttachments = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = false }) if data, err := readTestFile("test.png"); err != nil { t.Fatal(err) @@ -145,7 +145,7 @@ func TestGetFileInfo(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -215,7 +215,7 @@ func TestGetFile(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -298,7 +298,7 @@ func TestGetFileThumbnail(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -355,7 +355,7 @@ func TestGetFilePreview(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -412,18 +412,18 @@ func TestGetPublicFile(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } - enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink - publicLinkSalt := *utils.Cfg.FileSettings.PublicLinkSalt + enablePublicLink := th.App.Config().FileSettings.EnablePublicLink + publicLinkSalt := *th.App.Config().FileSettings.PublicLinkSalt defer func() { - utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink - *utils.Cfg.FileSettings.PublicLinkSalt = publicLinkSalt + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = enablePublicLink }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = publicLinkSalt }) }() - utils.Cfg.FileSettings.EnablePublicLink = true - *utils.Cfg.FileSettings.PublicLinkSalt = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewId() }) Client := th.BasicClient channel := th.BasicChannel @@ -453,15 +453,15 @@ func TestGetPublicFile(t *testing.T) { t.Fatal("should've failed to get image with public link without hash", resp.Status) } - utils.Cfg.FileSettings.EnablePublicLink = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = false }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusNotImplemented { t.Fatal("should've failed to get image with disabled public link") } - utils.Cfg.FileSettings.EnablePublicLink = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) // test after the salt has changed - *utils.Cfg.FileSettings.PublicLinkSalt = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewId() }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusBadRequest { t.Fatal("should've failed to get image with public link after salt changed") @@ -480,18 +480,18 @@ func TestGetPublicFileOld(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } - enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink - publicLinkSalt := *utils.Cfg.FileSettings.PublicLinkSalt + enablePublicLink := th.App.Config().FileSettings.EnablePublicLink + publicLinkSalt := *th.App.Config().FileSettings.PublicLinkSalt defer func() { - utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink - *utils.Cfg.FileSettings.PublicLinkSalt = publicLinkSalt + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = enablePublicLink }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = publicLinkSalt }) }() - utils.Cfg.FileSettings.EnablePublicLink = true - *utils.Cfg.FileSettings.PublicLinkSalt = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewId() }) channel := th.BasicChannel @@ -530,15 +530,15 @@ func TestGetPublicFileOld(t *testing.T) { t.Fatal("should've failed to get image with public link without hash", resp.Status) } - utils.Cfg.FileSettings.EnablePublicLink = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = false }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusNotImplemented { t.Fatal("should've failed to get image with disabled public link") } - utils.Cfg.FileSettings.EnablePublicLink = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) // test after the salt has changed - *utils.Cfg.FileSettings.PublicLinkSalt = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewId() }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusBadRequest { t.Fatal("should've failed to get image with public link after salt changed") @@ -562,15 +562,15 @@ func TestGetPublicLink(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } - enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink + enablePublicLink := th.App.Config().FileSettings.EnablePublicLink defer func() { - utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = enablePublicLink }) }() - utils.Cfg.FileSettings.EnablePublicLink = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) Client := th.BasicClient channel := th.BasicChannel @@ -590,13 +590,13 @@ func TestGetPublicLink(t *testing.T) { // Hacky way to assign file to a post (usually would be done by CreatePost call) store.Must(th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id)) - utils.Cfg.FileSettings.EnablePublicLink = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = false }) if _, err := Client.GetPublicLink(fileId); err == nil { t.Fatal("should've failed to get public link when disabled") } - utils.Cfg.FileSettings.EnablePublicLink = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) if link, err := Client.GetPublicLink(fileId); err != nil { t.Fatal(err) @@ -632,7 +632,7 @@ func TestMigrateFilenamesToFileInfos(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -745,7 +745,7 @@ func TestFindTeamIdForFilename(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -812,7 +812,7 @@ func TestGetInfoForFilename(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } diff --git a/api/general.go b/api/general.go index 015baec4e..5e7780fdb 100644 --- a/api/general.go +++ b/api/general.go @@ -30,7 +30,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { func logClient(c *Context, w http.ResponseWriter, r *http.Request) { forceToDebug := false - if !*utils.Cfg.ServiceSettings.EnableDeveloper { + if !*c.App.Config().ServiceSettings.EnableDeveloper { if c.Session.UserId == "" { c.Err = model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "", http.StatusForbidden) return diff --git a/api/general_test.go b/api/general_test.go index 3de39ca83..3f61d9d32 100644 --- a/api/general_test.go +++ b/api/general_test.go @@ -4,9 +4,8 @@ package api import ( + "github.com/mattermost/mattermost-server/model" "testing" - - "github.com/mattermost/mattermost-server/utils" ) func TestGetClientProperties(t *testing.T) { @@ -30,11 +29,11 @@ func TestLogClient(t *testing.T) { t.Fatal("failed to log") } - enableDeveloper := *utils.Cfg.ServiceSettings.EnableDeveloper + enableDeveloper := *th.App.Config().ServiceSettings.EnableDeveloper defer func() { - *utils.Cfg.ServiceSettings.EnableDeveloper = enableDeveloper + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = enableDeveloper }) }() - *utils.Cfg.ServiceSettings.EnableDeveloper = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = false }) th.BasicClient.Logout() @@ -42,7 +41,7 @@ func TestLogClient(t *testing.T) { t.Fatal("should have failed") } - *utils.Cfg.ServiceSettings.EnableDeveloper = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = true }) if ret, _ := th.BasicClient.LogClient("this is a test"); !ret { t.Fatal("failed to log") diff --git a/api/license.go b/api/license.go index 18d6a20a3..371f4be02 100644 --- a/api/license.go +++ b/api/license.go @@ -24,7 +24,7 @@ func (api *API) InitLicense() { func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize) + err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/api/oauth.go b/api/oauth.go index 0a26a6f98..51a1828d1 100644 --- a/api/oauth.go +++ b/api/oauth.go @@ -173,7 +173,7 @@ func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) service := params["service"] - if !utils.Cfg.TeamSettings.EnableUserCreation { + if !c.App.Config().TeamSettings.EnableUserCreation { c.Err = model.NewAppError("signupWithOAuth", "api.oauth.singup_with_oauth.disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api/oauth_test.go b/api/oauth_test.go index 0f809dfe6..1510e3520 100644 --- a/api/oauth_test.go +++ b/api/oauth_test.go @@ -25,14 +25,14 @@ func TestOAuthRegisterApp(t *testing.T) { oauthApp := &model.OAuthApp{Name: "TestApp" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}, IsTrusted: true} - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := Client.RegisterApp(oauthApp); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) // calling the endpoint without an app if _, err := Client.DoApiPost("/oauth/register", ""); err == nil { @@ -88,12 +88,12 @@ func TestOAuthRegisterApp(t *testing.T) { t.Fatal("should have failed. not enough permissions") } - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -115,18 +115,18 @@ func TestOAuthAllow(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oauthApp := &model.OAuthApp{Name: "TestApp" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} oauthApp = AdminClient.Must(AdminClient.RegisterApp(oauthApp)).Data.(*model.OAuthApp) state := "123" - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) if _, err := Client.AllowOAuth(model.AUTHCODE_RESPONSE_TYPE, oauthApp.Id, oauthApp.CallbackUrls[0], "all", state); err == nil { t.Fatal("should have failed - oauth providing turned off") } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) if result, err := Client.AllowOAuth(model.AUTHCODE_RESPONSE_TYPE, oauthApp.Id, oauthApp.CallbackUrls[0], "all", state); err != nil { t.Fatal(err) @@ -202,21 +202,21 @@ func TestOAuthGetAppsByUser(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := Client.GetOAuthAppsByUser(); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) if _, err := Client.GetOAuthAppsByUser(); err == nil { t.Fatal("Should have failed.") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if result, err := Client.GetOAuthAppsByUser(); err != nil { @@ -274,15 +274,15 @@ func TestOAuthGetAppInfo(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := Client.GetOAuthAppInfo("fakeId"); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oauthApp := &model.OAuthApp{Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -304,15 +304,15 @@ func TestOAuthGetAuthorizedApps(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := Client.GetOAuthAuthorizedApps(); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oauthApp := &model.OAuthApp{Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} oauthApp = AdminClient.Must(AdminClient.RegisterApp(oauthApp)).Data.(*model.OAuthApp) @@ -339,15 +339,15 @@ func TestOAuthDeauthorizeApp(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if err := Client.OAuthDeauthorizeApp(model.NewId()); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oauthApp := &model.OAuthApp{Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -392,15 +392,15 @@ func TestOAuthRegenerateAppSecret(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := AdminClient.RegenerateOAuthAppSecret(model.NewId()); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) oauthApp := &model.OAuthApp{Name: "TestApp6" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -435,16 +435,16 @@ func TestOAuthDeleteApp(t *testing.T) { Client := th.BasicClient AdminClient := th.SystemAdminClient - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) + if !th.App.Config().ServiceSettings.EnableOAuthServiceProvider { if _, err := Client.DeleteOAuthApp("fakeId"); err == nil { t.Fatal("should have failed - oauth providing turned off") } } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oauthApp := &model.OAuthApp{Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -567,27 +567,27 @@ func TestOAuthAccessToken(t *testing.T) { Client := th.BasicClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oauthApp := &model.OAuthApp{Name: "TestApp5" + model.NewId(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} oauthApp = Client.Must(Client.RegisterApp(oauthApp)).Data.(*model.OAuthApp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) data := url.Values{"grant_type": []string{"junk"}, "client_id": []string{"12345678901234567890123456"}, "client_secret": []string{"12345678901234567890123456"}, "code": []string{"junk"}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}} if _, err := Client.GetAccessToken(data); err == nil { t.Fatal("should have failed - oauth providing turned off") } - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) redirect := Client.Must(Client.AllowOAuth(model.AUTHCODE_RESPONSE_TYPE, oauthApp.Id, oauthApp.CallbackUrls[0], "all", "123")).Data.(map[string]string)["redirect"] rurl, _ := url.Parse(redirect) @@ -788,19 +788,19 @@ func TestOAuthComplete(t *testing.T) { closeBody(r) } - utils.Cfg.GitLabSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = true }) if r, err := HttpGet(Client.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", Client.HttpClient, "", true); err == nil { t.Fatal("should have failed - gitlab disabled") closeBody(r) } - utils.Cfg.GitLabSettings.AuthEndpoint = Client.Url + "/oauth/authorize" - utils.Cfg.GitLabSettings.Id = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.AuthEndpoint = Client.Url + "/oauth/authorize" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Id = model.NewId() }) stateProps := map[string]string{} stateProps["action"] = model.OAUTH_ACTION_LOGIN stateProps["team_id"] = th.BasicTeam.Id - stateProps["redirect_to"] = utils.Cfg.GitLabSettings.AuthEndpoint + stateProps["redirect_to"] = th.App.Config().GitLabSettings.AuthEndpoint state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) if r, err := HttpGet(Client.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), Client.HttpClient, "", true); err == nil { @@ -808,7 +808,7 @@ func TestOAuthComplete(t *testing.T) { closeBody(r) } - stateProps["hash"] = utils.HashSha256(utils.Cfg.GitLabSettings.Id) + stateProps["hash"] = utils.HashSha256(th.App.Config().GitLabSettings.Id) state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps))) if r, err := HttpGet(Client.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), Client.HttpClient, "", true); err == nil { t.Fatal("should have failed - no connection") @@ -816,14 +816,14 @@ func TestOAuthComplete(t *testing.T) { } // We are going to use mattermost as the provider emulating gitlab - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oauthApp := &model.OAuthApp{ @@ -838,11 +838,11 @@ func TestOAuthComplete(t *testing.T) { } oauthApp = Client.Must(Client.RegisterApp(oauthApp)).Data.(*model.OAuthApp) - utils.Cfg.GitLabSettings.Id = oauthApp.Id - utils.Cfg.GitLabSettings.Secret = oauthApp.ClientSecret - utils.Cfg.GitLabSettings.AuthEndpoint = Client.Url + "/oauth/authorize" - utils.Cfg.GitLabSettings.TokenEndpoint = Client.Url + "/oauth/access_token" - utils.Cfg.GitLabSettings.UserApiEndpoint = Client.ApiUrl + "/users/me" + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Id = oauthApp.Id }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Secret = oauthApp.ClientSecret }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.AuthEndpoint = Client.Url + "/oauth/authorize" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.TokenEndpoint = Client.Url + "/oauth/access_token" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.UserApiEndpoint = Client.ApiUrl + "/users/me" }) provider := &MattermostTestProvider{} @@ -851,8 +851,8 @@ func TestOAuthComplete(t *testing.T) { code := rurl.Query().Get("code") stateProps["action"] = model.OAUTH_ACTION_EMAIL_TO_SSO delete(stateProps, "team_id") - stateProps["redirect_to"] = utils.Cfg.GitLabSettings.AuthEndpoint - stateProps["hash"] = utils.HashSha256(utils.Cfg.GitLabSettings.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))) if r, err := HttpGet(Client.Url+"/login/"+model.SERVICE_GITLAB+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), Client.HttpClient, "", false); err == nil { diff --git a/api/post.go b/api/post.go index b2b8e3d0e..e85b9870d 100644 --- a/api/post.go +++ b/api/post.go @@ -534,7 +534,7 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { } func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableLinkPreviews { + if !*c.App.Config().ServiceSettings.EnableLinkPreviews { c.Err = model.NewAppError("getOpenGraphMetadata", "api.post.link_preview_disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api/post_test.go b/api/post_test.go index 58a9fae73..8b5cbd454 100644 --- a/api/post_test.go +++ b/api/post_test.go @@ -158,14 +158,14 @@ func TestCreatePost(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - disableTownSquareReadOnly := utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly + disableTownSquareReadOnly := th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly defer func() { - utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = disableTownSquareReadOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = disableTownSquareReadOnly }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) utils.SetDefaultRolesBasedOnConfig() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) @@ -237,14 +237,18 @@ func testCreatePostWithOutgoingHook( user := th.SystemAdminUser channel := th.CreateChannel(Client, team) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + }) var hook *model.OutgoingWebhook var post *model.Post @@ -398,14 +402,14 @@ func TestUpdatePost(t *testing.T) { Client := th.BasicClient channel1 := th.BasicChannel - allowEditPost := *utils.Cfg.ServiceSettings.AllowEditPost - postEditTimeLimit := *utils.Cfg.ServiceSettings.PostEditTimeLimit + allowEditPost := *th.App.Config().ServiceSettings.AllowEditPost + postEditTimeLimit := *th.App.Config().ServiceSettings.PostEditTimeLimit defer func() { - *utils.Cfg.ServiceSettings.AllowEditPost = allowEditPost - *utils.Cfg.ServiceSettings.PostEditTimeLimit = postEditTimeLimit + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = allowEditPost }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.PostEditTimeLimit = postEditTimeLimit }) }() - *utils.Cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS }) post1 := &model.Post{ChannelId: channel1.Id, Message: "zz" + model.NewId() + "a"} rpost1, err := Client.CreatePost(post1) @@ -480,7 +484,7 @@ func TestUpdatePost(t *testing.T) { utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_NEVER + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_NEVER }) post4 := &model.Post{ChannelId: channel1.Id, Message: "zz" + model.NewId() + "a", RootId: rpost1.Data.(*model.Post).Id} rpost4, err := Client.CreatePost(post4) @@ -493,8 +497,8 @@ func TestUpdatePost(t *testing.T) { t.Fatal("shouldn't have been able to update a message when not allowed") } - *utils.Cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_TIME_LIMIT - *utils.Cfg.ServiceSettings.PostEditTimeLimit = 1 //seconds + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_TIME_LIMIT }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.PostEditTimeLimit = 1 }) //seconds post5 := &model.Post{ChannelId: channel1.Id, Message: "zz" + model.NewId() + "a", RootId: rpost1.Data.(*model.Post).Id} rpost5, err := Client.CreatePost(post5) @@ -969,12 +973,12 @@ func TestDeletePosts(t *testing.T) { channel1 := th.BasicChannel team1 := th.BasicTeam - restrictPostDelete := *utils.Cfg.ServiceSettings.RestrictPostDelete + restrictPostDelete := *th.App.Config().ServiceSettings.RestrictPostDelete defer func() { - *utils.Cfg.ServiceSettings.RestrictPostDelete = restrictPostDelete + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.RestrictPostDelete = restrictPostDelete }) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_ALL }) utils.SetDefaultRolesBasedOnConfig() time.Sleep(10 * time.Millisecond) @@ -1050,7 +1054,9 @@ func TestDeletePosts(t *testing.T) { SystemAdminClient.Must(SystemAdminClient.DeletePost(channel1.Id, post4b.Id)) - *utils.Cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -1073,7 +1079,9 @@ func TestDeletePosts(t *testing.T) { SystemAdminClient.Must(SystemAdminClient.DeletePost(channel1.Id, post5b.Id)) - *utils.Cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.RestrictPostDelete = model.PERMISSIONS_DELETE_POST_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -1466,14 +1474,18 @@ func TestGetOpenGraphMetadata(t *testing.T) { Client := th.BasicClient - enableLinkPreviews := *utils.Cfg.ServiceSettings.EnableLinkPreviews - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - *utils.Cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableLinkPreviews = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = true }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + }) ogDataCacheMissCount := 0 @@ -1524,7 +1536,7 @@ func TestGetOpenGraphMetadata(t *testing.T) { } } - *utils.Cfg.ServiceSettings.EnableLinkPreviews = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = false }) if _, err := Client.DoApiPost("/get_opengraph_metadata", "{\"url\":\"/og-data/\"}"); err == nil || err.StatusCode != http.StatusNotImplemented { t.Fatal("should have failed with 501 - disabled link previews") } diff --git a/api/status_test.go b/api/status_test.go index 2d7e27326..19d422b16 100644 --- a/api/status_test.go +++ b/api/status_test.go @@ -10,7 +10,6 @@ import ( "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/store" - "github.com/mattermost/mattermost-server/utils" ) func TestStatuses(t *testing.T) { @@ -141,11 +140,11 @@ func TestStatuses(t *testing.T) { th.App.SetStatusAwayIfNeeded(th.BasicUser.Id, false) - awayTimeout := *utils.Cfg.TeamSettings.UserStatusAwayTimeout + awayTimeout := *th.App.Config().TeamSettings.UserStatusAwayTimeout defer func() { - *utils.Cfg.TeamSettings.UserStatusAwayTimeout = awayTimeout + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.UserStatusAwayTimeout = awayTimeout }) }() - *utils.Cfg.TeamSettings.UserStatusAwayTimeout = 1 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.UserStatusAwayTimeout = 1 }) time.Sleep(1500 * time.Millisecond) diff --git a/api/team.go b/api/team.go index 49b20686d..9bb76af2a 100644 --- a/api/team.go +++ b/api/team.go @@ -123,9 +123,9 @@ func inviteMembers(c *Context, w http.ResponseWriter, r *http.Request) { if utils.IsLicensed() && !app.SessionHasPermissionToTeam(c.Session, c.TeamId, model.PERMISSION_INVITE_USER) { errorId := "" - if *utils.Cfg.TeamSettings.RestrictTeamInvite == model.PERMISSIONS_SYSTEM_ADMIN { + if *c.App.Config().TeamSettings.RestrictTeamInvite == model.PERMISSIONS_SYSTEM_ADMIN { errorId = "api.team.invite_members.restricted_system_admin.app_error" - } else if *utils.Cfg.TeamSettings.RestrictTeamInvite == model.PERMISSIONS_TEAM_ADMIN { + } else if *c.App.Config().TeamSettings.RestrictTeamInvite == model.PERMISSIONS_TEAM_ADMIN { errorId = "api.team.invite_members.restricted_team_admin.app_error" } diff --git a/api/team_test.go b/api/team_test.go index 1e4b36433..680bd7ea7 100644 --- a/api/team_test.go +++ b/api/team_test.go @@ -140,18 +140,18 @@ func TestAddUserToTeam(t *testing.T) { } // Restore config/license at end of test case. - restrictTeamInvite := *utils.Cfg.TeamSettings.RestrictTeamInvite + restrictTeamInvite := *th.App.Config().TeamSettings.RestrictTeamInvite isLicensed := utils.IsLicensed() license := utils.License() defer func() { - *utils.Cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() // Set the config so that only team admins can add a user to a team. - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() // Test without the EE license to see that the permission restriction is ignored. @@ -175,7 +175,7 @@ func TestAddUserToTeam(t *testing.T) { // Should work as team admin. th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) th.App.InvalidateAllCaches() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -187,7 +187,7 @@ func TestAddUserToTeam(t *testing.T) { } // Change permission level to System Admin - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() // Should not work as team admin. @@ -565,12 +565,12 @@ func TestInviteMembers(t *testing.T) { t.Fatal("Should have errored out on no invites to send") } - restrictTeamInvite := *utils.Cfg.TeamSettings.RestrictTeamInvite + restrictTeamInvite := *th.App.Config().TeamSettings.RestrictTeamInvite defer func() { - *utils.Cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite }) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic2() @@ -605,7 +605,7 @@ func TestInviteMembers(t *testing.T) { t.Fatal(err) } - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.InviteMembers(invites); err == nil { diff --git a/api/user.go b/api/user.go index 1e77b8e2e..365e082ae 100644 --- a/api/user.go +++ b/api/user.go @@ -169,9 +169,9 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.ClearSessionCacheForUser(c.Session.UserId) - c.Session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthMobileInDays) + c.Session.SetExpireInDays(*c.App.Config().ServiceSettings.SessionLengthMobileInDays) - maxAge := *utils.Cfg.ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 + maxAge := *c.App.Config().ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 secure := false if app.GetProtocol(r) == "https" { @@ -249,11 +249,11 @@ func getMe(c *Context, w http.ResponseWriter, r *http.Request) { c.RemoveSessionCookie(w, r) l4g.Error(utils.T("api.user.get_me.getting.error"), c.Session.UserId) return - } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get Me", w, r) { + } else if c.HandleEtag(user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress), "Get Me", w, r) { return } else { user.Sanitize(map[string]bool{}) - w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress)) + w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress)) w.Write([]byte(user.ToJson())) return } @@ -321,7 +321,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + etag := user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress) if c.HandleEtag(etag, "Get User", w, r) { return @@ -343,12 +343,12 @@ func getByUsername(c *Context, w http.ResponseWriter, r *http.Request) { if user, err = c.App.GetUserByUsername(username); err != nil { c.Err = err return - } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Username", w, r) { + } else if c.HandleEtag(user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress), "Get By Username", w, r) { return } else { sanitizeProfile(c, user) - w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress)) + w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress)) w.Write([]byte(user.ToJson())) return } @@ -361,12 +361,12 @@ func getByEmail(c *Context, w http.ResponseWriter, r *http.Request) { if user, err := c.App.GetUserByEmail(email); err != nil { c.Err = err return - } else if c.HandleEtag(user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress), "Get By Email", w, r) { + } else if c.HandleEtag(user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress), "Get By Email", w, r) { return } else { sanitizeProfile(c, user) - w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress)) + w.Header().Set(model.HEADER_ETAG_SERVER, user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress)) w.Write([]byte(user.ToJson())) return } @@ -579,17 +579,17 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { } func uploadProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) return } - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.parse.app_error", nil, "", http.StatusBadRequest) return } @@ -830,7 +830,7 @@ func updateUserNotify(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(ruser.Id, "") - options := utils.Cfg.GetSanitizeOptions() + options := c.App.Config().GetSanitizeOptions() options["passwordupdate"] = false ruser.Sanitize(options) w.Write([]byte(ruser.ToJson())) @@ -1100,7 +1100,7 @@ func updateMfa(c *Context, w http.ResponseWriter, r *http.Request) { } func checkMfa(c *Context, w http.ResponseWriter, r *http.Request) { - if !utils.IsLicensed() || !*utils.License().Features.MFA || !*utils.Cfg.ServiceSettings.EnableMultifactorAuthentication { + if !utils.IsLicensed() || !*utils.License().Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication { rdata := map[string]string{} rdata["mfa_required"] = "false" w.Write([]byte(model.MapToJson(rdata))) @@ -1249,7 +1249,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { } func sanitizeProfile(c *Context, user *model.User) *model.User { - options := utils.Cfg.GetSanitizeOptions() + options := c.App.Config().GetSanitizeOptions() if app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { options["email"] = true @@ -1288,8 +1288,8 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { searchOptions[store.USER_SEARCH_OPTION_ALLOW_INACTIVE] = props.AllowInactive if !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName - hideEmail := !utils.Cfg.PrivacySettings.ShowEmailAddress + hideFullName := !c.App.Config().PrivacySettings.ShowFullName + hideEmail := !c.App.Config().PrivacySettings.ShowEmailAddress if hideFullName && hideEmail { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true @@ -1348,7 +1348,7 @@ func autocompleteUsersInChannel(c *Context, w http.ResponseWriter, r *http.Reque searchOptions := map[string]bool{} - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName + hideFullName := !c.App.Config().PrivacySettings.ShowFullName if hideFullName && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true } else { @@ -1378,7 +1378,7 @@ func autocompleteUsersInTeam(c *Context, w http.ResponseWriter, r *http.Request) searchOptions := map[string]bool{} - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName + hideFullName := !c.App.Config().PrivacySettings.ShowFullName if hideFullName && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true } else { @@ -1399,7 +1399,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { searchOptions := map[string]bool{} - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName + hideFullName := !c.App.Config().PrivacySettings.ShowFullName if hideFullName && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true } else { diff --git a/api/user_test.go b/api/user_test.go index 52120d5f2..c339d3346 100644 --- a/api/user_test.go +++ b/api/user_test.go @@ -89,18 +89,18 @@ func TestLogin(t *testing.T) { Client := th.BasicClient - enableSignInWithEmail := *utils.Cfg.EmailSettings.EnableSignInWithEmail - enableSignInWithUsername := *utils.Cfg.EmailSettings.EnableSignInWithUsername - enableLdap := *utils.Cfg.LdapSettings.Enable + enableSignInWithEmail := *th.App.Config().EmailSettings.EnableSignInWithEmail + enableSignInWithUsername := *th.App.Config().EmailSettings.EnableSignInWithUsername + enableLdap := *th.App.Config().LdapSettings.Enable defer func() { - *utils.Cfg.EmailSettings.EnableSignInWithEmail = enableSignInWithEmail - *utils.Cfg.EmailSettings.EnableSignInWithUsername = enableSignInWithUsername - *utils.Cfg.LdapSettings.Enable = enableLdap + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithEmail = enableSignInWithEmail }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithUsername = enableSignInWithUsername }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LdapSettings.Enable = enableLdap }) }() - *utils.Cfg.EmailSettings.EnableSignInWithEmail = false - *utils.Cfg.EmailSettings.EnableSignInWithUsername = false - *utils.Cfg.LdapSettings.Enable = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithEmail = false }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithUsername = false }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LdapSettings.Enable = false }) team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN} rteam, _ := Client.CreateTeam(&team) @@ -127,7 +127,7 @@ func TestLogin(t *testing.T) { t.Fatal("shouldn't be able to log in by email when disabled") } - *utils.Cfg.EmailSettings.EnableSignInWithEmail = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithEmail = true }) if result, err := Client.Login(user.Email, user.Password); err != nil { t.Fatal(err) } else { @@ -140,7 +140,7 @@ func TestLogin(t *testing.T) { t.Fatal("shouldn't be able to log in by username when disabled") } - *utils.Cfg.EmailSettings.EnableSignInWithUsername = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithUsername = true }) if result, err := Client.Login(user.Username, user.Password); err != nil { t.Fatal(err) } else { @@ -186,7 +186,7 @@ func TestLogin(t *testing.T) { props["display_name"] = rteam2.Data.(*model.Team).DisplayName props["time"] = fmt.Sprintf("%v", model.GetMillis()) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) ruser2, err := Client.CreateUserFromSignup(&user2, data, hash) if err != nil { @@ -272,14 +272,14 @@ func TestPasswordGuessLockout(t *testing.T) { user := th.BasicUser Client.Must(Client.Logout()) - enableSignInWithEmail := *utils.Cfg.EmailSettings.EnableSignInWithEmail - passwordAttempts := *utils.Cfg.ServiceSettings.MaximumLoginAttempts + enableSignInWithEmail := *th.App.Config().EmailSettings.EnableSignInWithEmail + passwordAttempts := *th.App.Config().ServiceSettings.MaximumLoginAttempts defer func() { - *utils.Cfg.EmailSettings.EnableSignInWithEmail = enableSignInWithEmail - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithEmail = enableSignInWithEmail }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts }) }() - *utils.Cfg.EmailSettings.EnableSignInWithEmail = true - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = 2 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.EmailSettings.EnableSignInWithEmail = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 }) // OK to log in if _, err := Client.Login(user.Username, user.Password); err != nil { @@ -410,14 +410,14 @@ func TestGetUser(t *testing.T) { t.Fatal("shouldn't exist") } - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) if result, err := Client.GetUser(ruser2.Data.(*model.User).Id, ""); err != nil { t.Fatal(err) @@ -440,8 +440,8 @@ func TestGetUser(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = true - utils.Cfg.PrivacySettings.ShowFullName = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = true }) if result, err := Client.GetUser(ruser2.Data.(*model.User).Id, ""); err != nil { t.Fatal(err) @@ -517,12 +517,12 @@ func TestGetProfiles(t *testing.T) { th.BasicClient.Must(th.BasicClient.CreateDirectChannel(th.BasicUser2.Id)) - prevShowEmail := utils.Cfg.PrivacySettings.ShowEmailAddress + prevShowEmail := th.App.Config().PrivacySettings.ShowEmailAddress defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = prevShowEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = prevShowEmail }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := th.BasicClient.GetProfiles(0, 100, ""); err != nil { t.Fatal(err) @@ -549,7 +549,7 @@ func TestGetProfiles(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) if result, err := th.BasicClient.GetProfiles(0, 100, ""); err != nil { t.Fatal(err) @@ -572,12 +572,12 @@ func TestGetProfilesByIds(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - prevShowEmail := utils.Cfg.PrivacySettings.ShowEmailAddress + prevShowEmail := th.App.Config().PrivacySettings.ShowEmailAddress defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = prevShowEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = prevShowEmail }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := th.BasicClient.GetProfilesByIds([]string{th.BasicUser.Id}); err != nil { t.Fatal(err) @@ -595,7 +595,7 @@ func TestGetProfilesByIds(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) if result, err := th.BasicClient.GetProfilesByIds([]string{th.BasicUser.Id}); err != nil { t.Fatal(err) @@ -709,23 +709,23 @@ func TestUserCreateImage(t *testing.T) { } } - if *utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 { - endpoint := utils.Cfg.FileSettings.AmazonS3Endpoint - accessKey := utils.Cfg.FileSettings.AmazonS3AccessKeyId - secretKey := utils.Cfg.FileSettings.AmazonS3SecretAccessKey - secure := *utils.Cfg.FileSettings.AmazonS3SSL - signV2 := *utils.Cfg.FileSettings.AmazonS3SignV2 - region := utils.Cfg.FileSettings.AmazonS3Region + if *th.App.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 { + endpoint := th.App.Config().FileSettings.AmazonS3Endpoint + accessKey := th.App.Config().FileSettings.AmazonS3AccessKeyId + secretKey := th.App.Config().FileSettings.AmazonS3SecretAccessKey + secure := *th.App.Config().FileSettings.AmazonS3SSL + signV2 := *th.App.Config().FileSettings.AmazonS3SignV2 + region := th.App.Config().FileSettings.AmazonS3Region s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region) if err != nil { t.Fatal(err) } - bucket := utils.Cfg.FileSettings.AmazonS3Bucket + bucket := th.App.Config().FileSettings.AmazonS3Bucket if err = s3Clnt.RemoveObject(bucket, "/users/"+user.Id+"/profile.png"); err != nil { t.Fatal(err) } } else { - path := utils.Cfg.FileSettings.Directory + "/users/" + user.Id + "/profile.png" + path := th.App.Config().FileSettings.Directory + "/users/" + user.Id + "/profile.png" if err := os.Remove(path); err != nil { t.Fatal("Couldn't remove file at " + path) } @@ -748,7 +748,7 @@ func TestUserUploadProfileImage(t *testing.T) { th.LinkUserToTeam(user, team) store.Must(th.App.Srv.Store.User().VerifyEmail(user.Id)) - if *utils.Cfg.FileSettings.DriverName != "" { + if *th.App.Config().FileSettings.DriverName != "" { body := &bytes.Buffer{} writer := multipart.NewWriter(body) @@ -817,23 +817,23 @@ func TestUserUploadProfileImage(t *testing.T) { Client.DoApiGet("/users/"+user.Id+"/image", "", "") - if *utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 { - endpoint := utils.Cfg.FileSettings.AmazonS3Endpoint - accessKey := utils.Cfg.FileSettings.AmazonS3AccessKeyId - secretKey := utils.Cfg.FileSettings.AmazonS3SecretAccessKey - secure := *utils.Cfg.FileSettings.AmazonS3SSL - signV2 := *utils.Cfg.FileSettings.AmazonS3SignV2 - region := utils.Cfg.FileSettings.AmazonS3Region + if *th.App.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 { + endpoint := th.App.Config().FileSettings.AmazonS3Endpoint + accessKey := th.App.Config().FileSettings.AmazonS3AccessKeyId + secretKey := th.App.Config().FileSettings.AmazonS3SecretAccessKey + secure := *th.App.Config().FileSettings.AmazonS3SSL + signV2 := *th.App.Config().FileSettings.AmazonS3SignV2 + region := th.App.Config().FileSettings.AmazonS3Region s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region) if err != nil { t.Fatal(err) } - bucket := utils.Cfg.FileSettings.AmazonS3Bucket + bucket := th.App.Config().FileSettings.AmazonS3Bucket if err = s3Clnt.RemoveObject(bucket, "/users/"+user.Id+"/profile.png"); err != nil { t.Fatal(err) } } else { - path := utils.Cfg.FileSettings.Directory + "users/" + user.Id + "/profile.png" + path := th.App.Config().FileSettings.Directory + "users/" + user.Id + "/profile.png" if err := os.Remove(path); err != nil { t.Fatal("Couldn't remove file at " + path) } @@ -960,11 +960,11 @@ func TestUserUpdatePassword(t *testing.T) { } // Test lockout - passwordAttempts := *utils.Cfg.ServiceSettings.MaximumLoginAttempts + passwordAttempts := *th.App.Config().ServiceSettings.MaximumLoginAttempts defer func() { - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts }) }() - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = 2 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 }) // Fail twice if _, err := Client.UpdateUserPassword(user.Id, "badpwd", "newpwd"); err == nil { @@ -1887,11 +1887,11 @@ func TestUpdateMfa(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - enableMfa := *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication + enableMfa := *th.App.Config().ServiceSettings.EnableMultifactorAuthentication defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa }) }() utils.SetIsLicensed(false) utils.SetLicense(&model.License{Features: &model.Features{}}) @@ -1925,7 +1925,7 @@ func TestUpdateMfa(t *testing.T) { utils.SetIsLicensed(true) *utils.License().Features.MFA = true - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) if _, err := Client.UpdateMfa(true, "123456"); err == nil { t.Fatal("should have failed - bad token") @@ -2059,12 +2059,12 @@ func TestGetProfilesInChannel(t *testing.T) { Client := th.BasicClient - prevShowEmail := utils.Cfg.PrivacySettings.ShowEmailAddress + prevShowEmail := th.App.Config().PrivacySettings.ShowEmailAddress defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = prevShowEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = prevShowEmail }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := Client.GetProfilesInChannel(th.BasicChannel.Id, 0, 100, ""); err != nil { t.Fatal(err) @@ -2090,7 +2090,7 @@ func TestGetProfilesInChannel(t *testing.T) { Client.Must(Client.JoinChannel(th.BasicChannel.Id)) - utils.Cfg.PrivacySettings.ShowEmailAddress = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) if result, err := Client.GetProfilesInChannel(th.BasicChannel.Id, 0, 100, ""); err != nil { t.Fatal(err) @@ -2133,12 +2133,12 @@ func TestGetProfilesNotInChannel(t *testing.T) { Client := th.BasicClient - prevShowEmail := utils.Cfg.PrivacySettings.ShowEmailAddress + prevShowEmail := th.App.Config().PrivacySettings.ShowEmailAddress defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = prevShowEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = prevShowEmail }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := Client.GetProfilesNotInChannel(th.BasicChannel.Id, 0, 100, ""); err != nil { t.Fatal(err) @@ -2176,7 +2176,7 @@ func TestGetProfilesNotInChannel(t *testing.T) { Client.Must(Client.JoinChannel(th.BasicChannel.Id)) - utils.Cfg.PrivacySettings.ShowEmailAddress = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) if result, err := Client.GetProfilesNotInChannel(th.BasicChannel.Id, 0, 100, ""); err != nil { t.Fatal(err) @@ -2359,14 +2359,14 @@ func TestSearchUsers(t *testing.T) { } } - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) privacyEmailPrefix := strings.ToLower(model.NewId()) privacyUser := &model.User{Email: privacyEmailPrefix + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", FirstName: model.NewId(), LastName: "Jimmers"} @@ -2390,7 +2390,7 @@ func TestSearchUsers(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := Client.SearchUsers(model.UserSearch{Term: privacyUser.FirstName}); err != nil { t.Fatal(err) @@ -2409,8 +2409,8 @@ func TestSearchUsers(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = true }) if result, err := Client.SearchUsers(model.UserSearch{Term: privacyUser.FirstName}); err != nil { t.Fatal(err) @@ -2446,7 +2446,7 @@ func TestSearchUsers(t *testing.T) { } } - utils.Cfg.PrivacySettings.ShowEmailAddress = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = true }) if result, err := Client.SearchUsers(model.UserSearch{Term: privacyEmailPrefix}); err != nil { t.Fatal(err) @@ -2653,11 +2653,11 @@ func TestAutocompleteUsers(t *testing.T) { } } - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) privacyUser := &model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", FirstName: model.NewId(), LastName: "Jimmers"} privacyUser = Client.Must(Client.CreateUser(privacyUser, "")).Data.(*model.User) @@ -2712,15 +2712,15 @@ func TestGetByUsername(t *testing.T) { } } - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) if result, err := Client.GetByUsername(th.BasicUser2.Username, ""); err != nil { t.Fatal(err) @@ -2749,15 +2749,15 @@ func TestGetByEmail(t *testing.T) { t.Fatal("Failed to get user by email") } - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) if user, respMetdata := Client.GetByEmail(th.BasicUser2.Email, ""); respMetdata.Error != nil { t.Fatal(respMetdata.Error) diff --git a/api/webhook_test.go b/api/webhook_test.go index cb58fde76..6aa857af8 100644 --- a/api/webhook_test.go +++ b/api/webhook_test.go @@ -25,15 +25,15 @@ func TestCreateIncomingHook(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.IncomingWebhook{ChannelId: channel1.Id} @@ -100,7 +100,7 @@ func TestCreateIncomingHook(t *testing.T) { t.Fatal(err) } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.CreateIncomingWebhook(hook); err != nil { @@ -113,7 +113,7 @@ func TestCreateIncomingHook(t *testing.T) { t.Fatal("should have failed - channel is private and not a member") } - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) if _, err := Client.CreateIncomingWebhook(hook); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -139,16 +139,16 @@ func TestUpdateIncomingHook(t *testing.T) { th.LinkUserToTeam(user3, team2) th.UpdateUserToTeamAdmin(user3, team2) - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := createIncomingWebhook(channel1.Id, Client, t) @@ -229,10 +229,10 @@ func TestUpdateIncomingHook(t *testing.T) { } }) - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) t.Run("OnlyAdminIntegrationsDisabled", func(t *testing.T) { - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() t.Run("UpdateHookOfSameUser", func(t *testing.T) { @@ -255,7 +255,7 @@ func TestUpdateIncomingHook(t *testing.T) { }) }) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() Client.Logout() @@ -275,7 +275,7 @@ func TestUpdateIncomingHook(t *testing.T) { }) t.Run("IncomingHooksDisabled", func(t *testing.T) { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) if _, err := Client.UpdateIncomingWebhook(hook); err == nil { t.Fatal("should have failed - incoming hooks are disabled") } @@ -338,15 +338,15 @@ func TestListIncomingHooks(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook1 := &model.IncomingWebhook{ChannelId: channel1.Id} @@ -373,14 +373,14 @@ func TestListIncomingHooks(t *testing.T) { t.Fatal("should have errored - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.ListIncomingWebhooks(); err != nil { t.Fatal(err) } - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) if _, err := Client.ListIncomingWebhooks(); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -397,15 +397,15 @@ func TestDeleteIncomingHook(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.IncomingWebhook{ChannelId: channel1.Id} @@ -439,7 +439,7 @@ func TestDeleteIncomingHook(t *testing.T) { t.Fatal("should have failed - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.DeleteIncomingWebhook(hook.Id); err == nil { @@ -453,7 +453,7 @@ func TestDeleteIncomingHook(t *testing.T) { t.Fatal(err) } - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) if _, err := Client.DeleteIncomingWebhook(hook.Id); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -475,15 +475,15 @@ func TestCreateOutgoingHook(t *testing.T) { user3 := th.CreateUser(Client) th.LinkUserToTeam(user3, team2) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: channel1.Id, CallbackURLs: []string{"http://nowhere.com"}} @@ -554,7 +554,7 @@ func TestCreateOutgoingHook(t *testing.T) { t.Fatal("should have failed - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.CreateOutgoingWebhook(hook); err != nil { @@ -569,7 +569,7 @@ func TestCreateOutgoingHook(t *testing.T) { t.Fatal("should have failed - wrong team") } - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) if _, err := Client.CreateOutgoingWebhook(hook); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -586,15 +586,15 @@ func TestListOutgoingHooks(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook1 := &model.OutgoingWebhook{ChannelId: channel1.Id, CallbackURLs: []string{"http://nowhere.com"}} @@ -621,14 +621,14 @@ func TestListOutgoingHooks(t *testing.T) { t.Fatal("should have failed - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.ListOutgoingWebhooks(); err != nil { t.Fatal(err) } - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) if _, err := Client.ListOutgoingWebhooks(); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -651,16 +651,16 @@ func TestUpdateOutgoingHook(t *testing.T) { user3 := th.CreateUser(Client) th.LinkUserToTeam(user3, team2) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := createOutgoingWebhook(channel1.Id, []string{"http://nowhere.com"}, []string{"cats"}, Client, t) @@ -669,13 +669,13 @@ func TestUpdateOutgoingHook(t *testing.T) { hook.DisplayName = "Cats" hook.Description = "Get me some cats" t.Run("OutgoingHooksDisabled", func(t *testing.T) { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) if _, err := Client.UpdateOutgoingWebhook(hook); err == nil { t.Fatal("should have failed - outgoing webhooks disabled") } }) - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) t.Run("UpdateOutgoingWebhook", func(t *testing.T) { if result, err := Client.UpdateOutgoingWebhook(hook); err != nil { t.Fatal("failed to update outgoing web hook") @@ -734,7 +734,7 @@ func TestUpdateOutgoingHook(t *testing.T) { t.Fatal("should have failed - user does not have permissions to manage webhooks") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() hook2 := createOutgoingWebhook(channel1.Id, []string{"http://nowhereelse.com"}, []string{"dogs"}, Client, t) @@ -742,7 +742,7 @@ func TestUpdateOutgoingHook(t *testing.T) { t.Fatal("update webhook failed when admin only integrations is turned off") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() Client.Logout() @@ -829,15 +829,15 @@ func TestDeleteOutgoingHook(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: channel1.Id, CallbackURLs: []string{"http://nowhere.com"}} @@ -871,7 +871,7 @@ func TestDeleteOutgoingHook(t *testing.T) { t.Fatal("should have failed - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() if _, err := Client.DeleteOutgoingWebhook(hook.Id); err == nil { @@ -885,7 +885,7 @@ func TestDeleteOutgoingHook(t *testing.T) { t.Fatal(err) } - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) if _, err := Client.DeleteOutgoingWebhook(hook.Id); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -905,15 +905,15 @@ func TestRegenOutgoingHookToken(t *testing.T) { user3 := th.CreateUser(Client) th.LinkUserToTeam(user3, team2) - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: channel1.Id, CallbackURLs: []string{"http://nowhere.com"}} @@ -948,7 +948,7 @@ func TestRegenOutgoingHookToken(t *testing.T) { t.Fatal("should have failed - not system/team admin") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() hook = &model.OutgoingWebhook{ChannelId: channel1.Id, CallbackURLs: []string{"http://nowhere.com"}} @@ -966,7 +966,7 @@ func TestRegenOutgoingHookToken(t *testing.T) { t.Fatal("should have failed - wrong team") } - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) if _, err := Client.RegenOutgoingWebhookToken(hook.Id); err == nil { t.Fatal("should have errored - webhooks turned off") @@ -983,11 +983,11 @@ func TestIncomingWebhooks(t *testing.T) { user2 := th.CreateUser(Client) th.LinkUserToTeam(user2, team) - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) hook := &model.IncomingWebhook{ChannelId: channel1.Id} hook = Client.Must(Client.CreateIncomingWebhook(hook)).Data.(*model.IncomingWebhook) @@ -1030,14 +1030,14 @@ func TestIncomingWebhooks(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - disableTownSquareReadOnly := utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly + disableTownSquareReadOnly := th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly defer func() { - utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = disableTownSquareReadOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = disableTownSquareReadOnly }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) utils.SetDefaultRolesBasedOnConfig() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) @@ -1134,7 +1134,7 @@ func TestIncomingWebhooks(t *testing.T) { t.Fatal("should have failed with bad request - attachment too long") } - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) if _, err := Client.DoPost(url, "{\"text\":\"this is a test\"}", "application/json"); err == nil { t.Fatal("should have failed - webhooks turned off") diff --git a/api/websocket_test.go b/api/websocket_test.go index 42604124b..0a39a012f 100644 --- a/api/websocket_test.go +++ b/api/websocket_test.go @@ -13,7 +13,6 @@ import ( "github.com/gorilla/websocket" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) /*func TestWebSocketAuthentication(t *testing.T) { @@ -343,7 +342,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { } // Should succeed now because open CORS - *utils.Cfg.ServiceSettings.AllowCorsFrom = "*" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "*" }) _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX_V3+"/users/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) @@ -352,7 +351,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { } // Should succeed now because matching CORS - *utils.Cfg.ServiceSettings.AllowCorsFrom = "http://www.evil.com" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.evil.com" }) _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX_V3+"/users/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) @@ -361,7 +360,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { } // Should fail because non-matching CORS - *utils.Cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX_V3+"/users/websocket", http.Header{ "Origin": []string{"http://www.evil.com"}, }) @@ -370,7 +369,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { } // Should fail because non-matching CORS - *utils.Cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" }) _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX_V3+"/users/websocket", http.Header{ "Origin": []string{"http://www.good.co"}, }) @@ -378,5 +377,5 @@ func TestWebsocketOriginSecurity(t *testing.T) { t.Fatal("Should have errored because Origin does not match host! SECURITY ISSUE!") } - *utils.Cfg.ServiceSettings.AllowCorsFrom = "" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "" }) } diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 4bd8276d5..3e093df56 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -81,27 +81,28 @@ func setupTestHelper(enterprise bool) *TestHelper { var options []app.Option if testStore != nil { options = append(options, app.StoreOverride(testStore)) - options = append(options, app.ConfigOverride(func(cfg *model.Config) { - cfg.ServiceSettings.ListenAddress = new(string) - *cfg.ServiceSettings.ListenAddress = ":0" - })) } th := &TestHelper{ App: app.New(options...), } - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.Cfg.EmailSettings.SendEmailNotifications = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = true }) utils.DisableDebugLogForTest() + prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress + if testStore != nil { + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) + } th.App.StartServer() + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) Init(th.App, th.App.Srv.Router, true) wsapi.Init(th.App, th.App.Srv.WebSocketRouter) utils.EnableDebugLogForTest() th.App.Srv.Store.MarkSystemRanUnitTests() - *utils.Cfg.TeamSettings.EnableOpenServer = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) utils.SetIsLicensed(enterprise) if enterprise { diff --git a/api4/brand.go b/api4/brand.go index 23bfc557d..ce9f32b6d 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -32,12 +32,12 @@ func getBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { } func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadBrandImage", "api.admin.upload_brand_image.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { c.Err = model.NewAppError("uploadBrandImage", "api.admin.upload_brand_image.parse.app_error", nil, "", http.StatusBadRequest) return } diff --git a/api4/channel_test.go b/api4/channel_test.go index 44f3a4ad7..af47aca95 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -83,17 +83,17 @@ func TestCreateChannel(t *testing.T) { // Check permissions with policy config changes isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelCreation - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelCreation + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelCreation defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelCreation = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelCreation = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -107,8 +107,12 @@ func TestCreateChannel(t *testing.T) { _, resp = Client.CreateChannel(private) CheckNoError(t, resp) - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.CreateChannel(channel) @@ -135,8 +139,12 @@ func TestCreateChannel(t *testing.T) { _, resp = th.SystemAdminClient.CreateChannel(private) CheckNoError(t, resp) - *utils.Cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelCreation = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -880,17 +888,17 @@ func TestDeleteChannel(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - restrictPublicChannel := *utils.Cfg.TeamSettings.RestrictPublicChannelManagement - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement + restrictPublicChannel := *th.App.Config().TeamSettings.RestrictPublicChannelManagement + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManagement defer func() { - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = restrictPublicChannel }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = restrictPrivateChannel }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL - *utils.Cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPublicChannelManagement = model.PERMISSIONS_ALL }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManagement = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -915,8 +923,12 @@ func TestDeleteChannel(t *testing.T) { _, resp = Client.DeleteChannel(privateChannel7.Id) CheckNoError(t, resp) - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() // channels created by SystemAdmin @@ -964,8 +976,12 @@ func TestDeleteChannel(t *testing.T) { _, resp = Client.DeleteChannel(privateChannel7.Id) CheckNoError(t, resp) - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_TEAM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() th.UpdateUserToNonTeamAdmin(user, team) th.App.InvalidateAllCaches() @@ -1011,8 +1027,12 @@ func TestDeleteChannel(t *testing.T) { _, resp = Client.DeleteChannel(privateChannel7.Id) CheckNoError(t, resp) - *utils.Cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN - *utils.Cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPublicChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelDeletion = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() // channels created by SystemAdmin @@ -1781,11 +1801,15 @@ func TestAddChannelMember(t *testing.T) { CheckNoError(t, resp) // Test policy does not apply to TE. - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManageMembers defer func() { - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + }) }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() Client.Login(user2.Username, user2.Password) @@ -1807,7 +1831,7 @@ func TestAddChannelMember(t *testing.T) { utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1826,7 +1850,9 @@ func TestAddChannelMember(t *testing.T) { Client.Logout() // Test with CHANNEL_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1856,7 +1882,9 @@ func TestAddChannelMember(t *testing.T) { Client.Logout() // Test with TEAM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1886,7 +1914,9 @@ func TestAddChannelMember(t *testing.T) { Client.Logout() // Test with SYSTEM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1967,11 +1997,15 @@ func TestRemoveChannelMember(t *testing.T) { th.App.InvalidateAllCaches() // Test policy does not apply to TE. - restrictPrivateChannel := *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers + restrictPrivateChannel := *th.App.Config().TeamSettings.RestrictPrivateChannelManageMembers defer func() { - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = restrictPrivateChannel + }) }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetDefaultRolesBasedOnConfig() privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) @@ -1991,7 +2025,7 @@ func TestRemoveChannelMember(t *testing.T) { utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -2008,7 +2042,9 @@ func TestRemoveChannelMember(t *testing.T) { CheckNoError(t, resp) // Test with CHANNEL_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_CHANNEL_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -2033,7 +2069,9 @@ func TestRemoveChannelMember(t *testing.T) { CheckNoError(t, resp) // Test with TEAM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_TEAM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -2058,7 +2096,9 @@ func TestRemoveChannelMember(t *testing.T) { CheckNoError(t, resp) // Test with SYSTEM_ADMIN level permission. - *utils.Cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.TeamSettings.RestrictPrivateChannelManageMembers = model.PERMISSIONS_SYSTEM_ADMIN + }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() diff --git a/api4/command_help_test.go b/api4/command_help_test.go index 68a098636..c5ff819b3 100644 --- a/api4/command_help_test.go +++ b/api4/command_help_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestHelpCommand(t *testing.T) { @@ -17,18 +16,20 @@ func TestHelpCommand(t *testing.T) { Client := th.Client channel := th.BasicChannel - HelpLink := *utils.Cfg.SupportSettings.HelpLink + HelpLink := *th.App.Config().SupportSettings.HelpLink defer func() { - *utils.Cfg.SupportSettings.HelpLink = HelpLink + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = HelpLink }) }() - *utils.Cfg.SupportSettings.HelpLink = "" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" }) rs1, _ := Client.ExecuteCommand(channel.Id, "/help ") if rs1.GotoLocation != model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK { t.Fatal("failed to default help link") } - *utils.Cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" + }) rs2, _ := Client.ExecuteCommand(channel.Id, "/help ") if rs2.GotoLocation != "https://docs.mattermost.com/guides/user.html" { t.Fatal("failed to help link") diff --git a/api4/command_test.go b/api4/command_test.go index 716b3e414..3be1af061 100644 --- a/api4/command_test.go +++ b/api4/command_test.go @@ -9,7 +9,6 @@ import ( "testing" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestCreateCommand(t *testing.T) { @@ -17,11 +16,11 @@ func TestCreateCommand(t *testing.T) { defer th.TearDown() Client := th.Client - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) newCmd := &model.Command{ CreatorId: th.BasicUser.Id, @@ -53,7 +52,7 @@ func TestCreateCommand(t *testing.T) { CheckBadRequestStatus(t, resp) CheckErrorMessage(t, resp, "model.command.is_valid.method.app_error") - *utils.Cfg.ServiceSettings.EnableCommands = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = false }) newCmd.Method = "P" newCmd.Trigger = "testcommand" _, resp = th.SystemAdminClient.CreateCommand(newCmd) @@ -68,11 +67,11 @@ func TestUpdateCommand(t *testing.T) { user := th.SystemAdminUser team := th.BasicTeam - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd1 := &model.Command{ CreatorId: user.Id, @@ -154,11 +153,11 @@ func TestDeleteCommand(t *testing.T) { user := th.SystemAdminUser team := th.BasicTeam - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) cmd1 := &model.Command{ CreatorId: user.Id, @@ -352,11 +351,11 @@ func TestRegenToken(t *testing.T) { defer th.TearDown() Client := th.Client - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands + enableCommands := *th.App.Config().ServiceSettings.EnableCommands defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) newCmd := &model.Command{ CreatorId: th.BasicUser.Id, @@ -388,14 +387,16 @@ func TestExecuteCommand(t *testing.T) { Client := th.Client channel := th.BasicChannel - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) postCmd := &model.Command{ CreatorId: th.BasicUser.Id, @@ -498,14 +499,16 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) { Client := th.Client channel := th.BasicChannel - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) // create a slash command on some other team where we have permission to do so team2 := th.CreateTeam() @@ -531,14 +534,16 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) { defer th.TearDown() client := th.Client - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) // create a slash command on some other team where we have permission to do so team2 := th.CreateTeam() @@ -569,14 +574,16 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) { defer th.TearDown() client := th.Client - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) // create a slash command on some other team where we have permission to do so team2 := th.CreateTeam() @@ -609,14 +616,16 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) { defer th.TearDown() client := th.Client - enableCommands := *utils.Cfg.ServiceSettings.EnableCommands - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableCommands := *th.App.Config().ServiceSettings.EnableCommands + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableCommands = &enableCommands - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableCommands = &enableCommands }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableCommands = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost" }) // create a team that the user isn't a part of team2 := th.CreateTeam() diff --git a/api4/context.go b/api4/context.go index c526f38bb..44334aabf 100644 --- a/api4/context.go +++ b/api4/context.go @@ -182,7 +182,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Err.Where = r.URL.Path // Block out detailed error when not in developer mode - if !*utils.Cfg.ServiceSettings.EnableDeveloper { + if !*c.App.Config().ServiceSettings.EnableDeveloper { c.Err.DetailedError = "" } @@ -244,7 +244,7 @@ func (c *Context) IsSystemAdmin() bool { } func (c *Context) SessionRequired() { - if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens && c.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN { + if !*c.App.Config().ServiceSettings.EnableUserAccessTokens && c.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized) return } @@ -257,7 +257,7 @@ func (c *Context) SessionRequired() { func (c *Context) MfaRequired() { // Must be licensed for MFA and have it configured for enforcement - if !utils.IsLicensed() || !*utils.License().Features.MFA || !*utils.Cfg.ServiceSettings.EnableMultifactorAuthentication || !*utils.Cfg.ServiceSettings.EnforceMultifactorAuthentication { + if !utils.IsLicensed() || !*utils.License().Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication { return } diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index 2a378f54e..eb5a09876 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -22,7 +22,7 @@ func (api *API) InitElasticsearch() { func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { cfg := model.ConfigFromJson(r.Body) if cfg == nil { - cfg = utils.Cfg + cfg = c.App.Config() } if !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { diff --git a/api4/emoji.go b/api4/emoji.go index d014250d6..f2335b067 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -26,7 +26,7 @@ func (api *API) InitEmoji() { } func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("createEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -37,7 +37,7 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("createEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return } @@ -76,7 +76,7 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } func getEmojiList(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("getEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -122,7 +122,7 @@ func getEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("getEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -142,12 +142,12 @@ func getEmojiImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*c.App.Config().ServiceSettings.EnableCustomEmoji { c.Err = model.NewAppError("getEmojiImage", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("getEmojiImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/emoji_test.go b/api4/emoji_test.go index fe746f304..e35abdf08 100644 --- a/api4/emoji_test.go +++ b/api4/emoji_test.go @@ -18,11 +18,11 @@ func TestCreateEmoji(t *testing.T) { defer th.TearDown() Client := th.Client - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false }) emoji := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -33,7 +33,7 @@ func TestCreateEmoji(t *testing.T) { _, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNotImplementedStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) // try to create a valid gif emoji when they're enabled newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) @@ -146,11 +146,11 @@ func TestGetEmojiList(t *testing.T) { defer th.TearDown() Client := th.Client - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) emojis := []*model.Emoji{ { @@ -216,11 +216,11 @@ func TestDeleteEmoji(t *testing.T) { defer th.TearDown() Client := th.Client - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) emoji := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -283,11 +283,11 @@ func TestGetEmoji(t *testing.T) { defer th.TearDown() Client := th.Client - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) emoji := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -312,13 +312,13 @@ func TestGetEmojiImage(t *testing.T) { defer th.TearDown() Client := th.Client - EnableCustomEmoji := *utils.Cfg.ServiceSettings.EnableCustomEmoji - DriverName := *utils.Cfg.FileSettings.DriverName + EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji + DriverName := *th.App.Config().FileSettings.DriverName defer func() { - *utils.Cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji - *utils.Cfg.FileSettings.DriverName = DriverName + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = EnableCustomEmoji }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.DriverName = DriverName }) }() - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) emoji1 := &model.Emoji{ CreatorId: th.BasicUser.Id, @@ -328,20 +328,20 @@ func TestGetEmojiImage(t *testing.T) { emoji1, resp := Client.CreateEmoji(emoji1, utils.CreateTestGif(t, 10, 10), "image.gif") CheckNoError(t, resp) - *utils.Cfg.ServiceSettings.EnableCustomEmoji = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false }) _, resp = Client.GetEmojiImage(emoji1.Id) CheckNotImplementedStatus(t, resp) CheckErrorMessage(t, resp, "api.emoji.disabled.app_error") - *utils.Cfg.FileSettings.DriverName = "" - *utils.Cfg.ServiceSettings.EnableCustomEmoji = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.DriverName = "" }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true }) _, resp = Client.GetEmojiImage(emoji1.Id) CheckNotImplementedStatus(t, resp) CheckErrorMessage(t, resp, "api.emoji.storage.app_error") - *utils.Cfg.FileSettings.DriverName = DriverName + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.DriverName = DriverName }) emojiImage, resp := Client.GetEmojiImage(emoji1.Id) CheckNoError(t, resp) diff --git a/api4/file.go b/api4/file.go index 2c0b85ce7..933640c44 100644 --- a/api4/file.go +++ b/api4/file.go @@ -58,17 +58,17 @@ func (api *API) InitFile() { } func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.FileSettings.EnableFileAttachments { + if !*c.App.Config().FileSettings.EnableFileAttachments { c.Err = model.NewAppError("uploadFile", "api.file.attachments.disabled.app_error", nil, "", http.StatusNotImplemented) return } - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadFile", "api.file.upload_file.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -179,7 +179,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !utils.Cfg.FileSettings.EnablePublicLink { + if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -269,7 +269,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !utils.Cfg.FileSettings.EnablePublicLink { + if !c.App.Config().FileSettings.EnablePublicLink { c.Err = model.NewAppError("getPublicFile", "api.file.get_public_link.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -288,7 +288,7 @@ func getPublicFile(c *Context, w http.ResponseWriter, r *http.Request) { return } - if hash != app.GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) { + if hash != app.GeneratePublicLinkHash(info.Id, *c.App.Config().FileSettings.PublicLinkSalt) { c.Err = model.NewAppError("getPublicFile", "api.file.get_file.public_invalid.app_error", nil, "", http.StatusBadRequest) http.Redirect(w, r, c.GetSiteURLHeader()+"/error?message="+utils.T(c.Err.Message), http.StatusTemporaryRedirect) return diff --git a/api4/file_test.go b/api4/file_test.go index 615e601dc..0d44f2c86 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -13,7 +13,6 @@ import ( "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/store" - "github.com/mattermost/mattermost-server/utils" ) func TestUploadFile(t *testing.T) { @@ -114,11 +113,11 @@ func TestUploadFile(t *testing.T) { _, resp = th.SystemAdminClient.UploadFile(data, channel.Id, "test.png") CheckNoError(t, resp) - enableFileAttachments := *utils.Cfg.FileSettings.EnableFileAttachments + enableFileAttachments := *th.App.Config().FileSettings.EnableFileAttachments defer func() { - *utils.Cfg.FileSettings.EnableFileAttachments = enableFileAttachments + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = enableFileAttachments }) }() - *utils.Cfg.FileSettings.EnableFileAttachments = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = false }) _, resp = th.SystemAdminClient.UploadFile(data, channel.Id, "test.png") if resp.StatusCode != http.StatusNotImplemented && resp.StatusCode != 0 { @@ -133,7 +132,7 @@ func TestGetFile(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -183,7 +182,7 @@ func TestGetFileHeaders(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -247,7 +246,7 @@ func TestGetFileThumbnail(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -299,18 +298,18 @@ func TestGetFileLink(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } - enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink - publicLinkSalt := *utils.Cfg.FileSettings.PublicLinkSalt + enablePublicLink := th.App.Config().FileSettings.EnablePublicLink + publicLinkSalt := *th.App.Config().FileSettings.PublicLinkSalt defer func() { - utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink - *utils.Cfg.FileSettings.PublicLinkSalt = publicLinkSalt + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = enablePublicLink }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = publicLinkSalt }) }() - utils.Cfg.FileSettings.EnablePublicLink = true - *utils.Cfg.FileSettings.PublicLinkSalt = model.NewId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewId() }) fileId := "" if data, err := readTestFile("test.png"); err != nil { @@ -328,14 +327,14 @@ func TestGetFileLink(t *testing.T) { // Hacky way to assign file to a post (usually would be done by CreatePost call) store.Must(th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id)) - utils.Cfg.FileSettings.EnablePublicLink = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = false }) _, resp = Client.GetFileLink(fileId) CheckNotImplementedStatus(t, resp) // Wait a bit for files to ready time.Sleep(2 * time.Second) - utils.Cfg.FileSettings.EnablePublicLink = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) link, resp = Client.GetFileLink(fileId) CheckNoError(t, resp) if link == "" { @@ -374,7 +373,7 @@ func TestGetFilePreview(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -427,7 +426,7 @@ func TestGetFileInfo(t *testing.T) { user := th.BasicUser channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } @@ -493,18 +492,18 @@ func TestGetPublicFile(t *testing.T) { Client := th.Client channel := th.BasicChannel - if *utils.Cfg.FileSettings.DriverName == "" { + if *th.App.Config().FileSettings.DriverName == "" { t.Skip("skipping because no file driver is enabled") } - enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink - publicLinkSalt := *utils.Cfg.FileSettings.PublicLinkSalt + enablePublicLink := th.App.Config().FileSettings.EnablePublicLink + publicLinkSalt := *th.App.Config().FileSettings.PublicLinkSalt defer func() { - utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink - *utils.Cfg.FileSettings.PublicLinkSalt = publicLinkSalt + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = enablePublicLink }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = publicLinkSalt }) }() - utils.Cfg.FileSettings.EnablePublicLink = true - *utils.Cfg.FileSettings.PublicLinkSalt = GenerateTestId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = GenerateTestId() }) fileId := "" if data, err := readTestFile("test.png"); err != nil { @@ -535,14 +534,14 @@ func TestGetPublicFile(t *testing.T) { t.Fatal("should've failed to get image with public link without hash", resp.Status) } - utils.Cfg.FileSettings.EnablePublicLink = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = false }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusNotImplemented { t.Fatal("should've failed to get image with disabled public link") } // test after the salt has changed - utils.Cfg.FileSettings.EnablePublicLink = true - *utils.Cfg.FileSettings.PublicLinkSalt = GenerateTestId() + th.App.UpdateConfig(func(cfg *model.Config) { cfg.FileSettings.EnablePublicLink = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = GenerateTestId() }) if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusBadRequest { t.Fatal("should've failed to get image with public link after salt changed") diff --git a/api4/oauth.go b/api4/oauth.go index c60f240f6..8933f0863 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -313,7 +313,7 @@ func deauthorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !c.App.Config().ServiceSettings.EnableOAuthServiceProvider { err := model.NewAppError("authorizeOAuth", "api.oauth.authorize_oauth.disabled.app_error", nil, "", http.StatusNotImplemented) utils.RenderWebError(err, w, r) return @@ -560,7 +560,7 @@ func signupWithOAuth(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !utils.Cfg.TeamSettings.EnableUserCreation { + if !c.App.Config().TeamSettings.EnableUserCreation { c.Err = model.NewAppError("signupWithOAuth", "api.oauth.singup_with_oauth.disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/oauth_test.go b/api4/oauth_test.go index 9fa794e27..fbe5f11e5 100644 --- a/api4/oauth_test.go +++ b/api4/oauth_test.go @@ -19,13 +19,13 @@ func TestCreateOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}, IsTrusted: true} @@ -42,12 +42,12 @@ func TestCreateOAuthApp(t *testing.T) { t.Fatal("trusted did no match") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.CreateOAuthApp(oapp) CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() rapp, resp = Client.CreateOAuthApp(oapp) CheckNoError(t, resp) @@ -75,7 +75,7 @@ func TestCreateOAuthApp(t *testing.T) { _, resp = Client.CreateOAuthApp(oapp) CheckUnauthorizedStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) oapp.Name = GenerateTestAppName() _, resp = AdminClient.CreateOAuthApp(oapp) CheckNotImplementedStatus(t, resp) @@ -87,13 +87,13 @@ func TestUpdateOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{ @@ -101,7 +101,7 @@ func TestUpdateOAuthApp(t *testing.T) { IsTrusted: false, IconURL: "https://nowhere.com/img", Homepage: "https://nowhere.com", - Description: "test", + Description: "test", CallbackUrls: []string{"https://callback.com"}, } @@ -112,7 +112,7 @@ func TestUpdateOAuthApp(t *testing.T) { oapp.IconURL = "https://nowhere.com/img_update" oapp.Homepage = "https://nowhere_update.com" oapp.Description = "test_update" - oapp.CallbackUrls = []string{"https://callback_update.com","https://another_callback.com"} + oapp.CallbackUrls = []string{"https://callback_update.com", "https://another_callback.com"} updatedApp, resp := AdminClient.UpdateOAuthApp(oapp) CheckNoError(t, resp) @@ -153,7 +153,7 @@ func TestUpdateOAuthApp(t *testing.T) { for i, callbackUrl := range updatedApp.CallbackUrls { if callbackUrl != oapp.CallbackUrls[i] { t.Fatal("Description should have updated") - } + } } } @@ -165,7 +165,7 @@ func TestUpdateOAuthApp(t *testing.T) { t.Fatal("IsTrusted should have updated") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.UpdateOAuthApp(oapp) CheckForbiddenStatus(t, resp) @@ -174,7 +174,7 @@ func TestUpdateOAuthApp(t *testing.T) { _, resp = AdminClient.UpdateOAuthApp(oapp) CheckNotFoundStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.UpdateOAuthApp(oapp) CheckNotImplementedStatus(t, resp) @@ -193,14 +193,14 @@ func TestGetOAuthApps(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -244,7 +244,7 @@ func TestGetOAuthApps(t *testing.T) { t.Fatal("wrong apps returned") } - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.GetOAuthApps(0, 1000) @@ -255,7 +255,7 @@ func TestGetOAuthApps(t *testing.T) { _, resp = Client.GetOAuthApps(0, 1000) CheckUnauthorizedStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.GetOAuthApps(0, 1000) CheckNotImplementedStatus(t, resp) } @@ -266,14 +266,14 @@ func TestGetOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -313,7 +313,7 @@ func TestGetOAuthApp(t *testing.T) { _, resp = Client.GetOAuthApp(rapp.Id) CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.GetOAuthApp(rapp2.Id) @@ -330,7 +330,7 @@ func TestGetOAuthApp(t *testing.T) { _, resp = AdminClient.GetOAuthApp(model.NewId()) CheckNotFoundStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.GetOAuthApp(rapp.Id) CheckNotImplementedStatus(t, resp) } @@ -341,14 +341,14 @@ func TestGetOAuthAppInfo(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -388,7 +388,7 @@ func TestGetOAuthAppInfo(t *testing.T) { _, resp = Client.GetOAuthAppInfo(rapp.Id) CheckNoError(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.GetOAuthAppInfo(rapp2.Id) @@ -405,7 +405,7 @@ func TestGetOAuthAppInfo(t *testing.T) { _, resp = AdminClient.GetOAuthAppInfo(model.NewId()) CheckNotFoundStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.GetOAuthAppInfo(rapp.Id) CheckNotImplementedStatus(t, resp) } @@ -416,14 +416,14 @@ func TestDeleteOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -458,7 +458,7 @@ func TestDeleteOAuthApp(t *testing.T) { _, resp = Client.DeleteOAuthApp(rapp2.Id) CheckNoError(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.DeleteOAuthApp(rapp.Id) CheckForbiddenStatus(t, resp) @@ -473,7 +473,7 @@ func TestDeleteOAuthApp(t *testing.T) { _, resp = AdminClient.DeleteOAuthApp(model.NewId()) CheckNotFoundStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.DeleteOAuthApp(rapp.Id) CheckNotImplementedStatus(t, resp) } @@ -484,14 +484,14 @@ func TestRegenerateOAuthAppSecret(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - adminOnly := *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + adminOnly := *th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = adminOnly }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -530,7 +530,7 @@ func TestRegenerateOAuthAppSecret(t *testing.T) { _, resp = Client.RegenerateOAuthAppSecret(rapp2.Id) CheckNoError(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.RegenerateOAuthAppSecret(rapp.Id) CheckForbiddenStatus(t, resp) @@ -545,7 +545,7 @@ func TestRegenerateOAuthAppSecret(t *testing.T) { _, resp = AdminClient.RegenerateOAuthAppSecret(model.NewId()) CheckNotFoundStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = false }) _, resp = AdminClient.RegenerateOAuthAppSecret(rapp.Id) CheckNotImplementedStatus(t, resp) } @@ -556,11 +556,11 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + 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"}} @@ -616,11 +616,11 @@ func TestAuthorizeOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = true }) utils.SetDefaultRolesBasedOnConfig() oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}} @@ -684,11 +684,11 @@ func TestDeauthorizeOAuthApp(t *testing.T) { Client := th.Client AdminClient := th.SystemAdminClient - enableOAuth := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider + enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOAuthServiceProvider = enableOAuth }) }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + 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"}} diff --git a/api4/openGraph.go b/api4/openGraph.go index e03ecd219..6ddd0d79c 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -23,7 +23,7 @@ func (api *API) InitOpenGraph() { } func getOpenGraphMetadata(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableLinkPreviews { + if !*c.App.Config().ServiceSettings.EnableLinkPreviews { c.Err = model.NewAppError("getOpenGraphMetadata", "api.post.link_preview_disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/openGraph_test.go b/api4/openGraph_test.go index 04f207f55..6a14ad943 100644 --- a/api4/openGraph_test.go +++ b/api4/openGraph_test.go @@ -9,9 +9,8 @@ import ( "net/http/httptest" "strings" + "github.com/mattermost/mattermost-server/model" "testing" - - "github.com/mattermost/mattermost-server/utils" ) func TestGetOpenGraphMetadata(t *testing.T) { @@ -20,14 +19,18 @@ func TestGetOpenGraphMetadata(t *testing.T) { Client := th.Client - enableLinkPreviews := *utils.Cfg.ServiceSettings.EnableLinkPreviews - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - *utils.Cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews }) + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - *utils.Cfg.ServiceSettings.EnableLinkPreviews = true - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = true }) + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + }) ogDataCacheMissCount := 0 @@ -72,7 +75,7 @@ func TestGetOpenGraphMetadata(t *testing.T) { } } - *utils.Cfg.ServiceSettings.EnableLinkPreviews = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = false }) _, resp := Client.OpenGraph(ts.URL + "/og-data/") CheckNotImplementedStatus(t, resp) } diff --git a/api4/plugin.go b/api4/plugin.go index 08dea6301..2045a35a8 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -11,7 +11,6 @@ import ( l4g "github.com/alecthomas/log4go" "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) const ( @@ -30,7 +29,7 @@ func (api *API) InitPlugin() { } func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.PluginSettings.Enable { + if !*c.App.Config().PluginSettings.Enable { c.Err = model.NewAppError("uploadPlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -77,7 +76,7 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { } func getPlugins(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.PluginSettings.Enable { + if !*c.App.Config().PluginSettings.Enable { c.Err = model.NewAppError("getPlugins", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -102,7 +101,7 @@ func removePlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !*utils.Cfg.PluginSettings.Enable { + if !*c.App.Config().PluginSettings.Enable { c.Err = model.NewAppError("getPlugins", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return } @@ -122,7 +121,7 @@ func removePlugin(c *Context, w http.ResponseWriter, r *http.Request) { } func getWebappPlugins(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.PluginSettings.Enable { + if !*c.App.Config().PluginSettings.Enable { c.Err = model.NewAppError("getWebappPlugins", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/plugin_test.go b/api4/plugin_test.go index 5051ab434..1feb1b06a 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -9,6 +9,7 @@ import ( "os" "testing" + "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -26,11 +27,11 @@ func TestPlugin(t *testing.T) { th := SetupEnterprise().InitBasic().InitSystemAdmin() defer th.TearDown() - enablePlugins := *utils.Cfg.PluginSettings.Enable + enablePlugins := *th.App.Config().PluginSettings.Enable defer func() { - *utils.Cfg.PluginSettings.Enable = enablePlugins + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = enablePlugins }) }() - *utils.Cfg.PluginSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) th.App.InitPlugins(pluginDir, webappDir) defer func() { @@ -56,11 +57,11 @@ func TestPlugin(t *testing.T) { _, resp = th.SystemAdminClient.UploadPlugin(bytes.NewReader([]byte("badfile"))) CheckBadRequestStatus(t, resp) - *utils.Cfg.PluginSettings.Enable = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = false }) _, resp = th.SystemAdminClient.UploadPlugin(file) CheckNotImplementedStatus(t, resp) - *utils.Cfg.PluginSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) _, resp = th.Client.UploadPlugin(file) CheckForbiddenStatus(t, resp) @@ -78,11 +79,11 @@ func TestPlugin(t *testing.T) { assert.True(t, found) // Get error cases - *utils.Cfg.PluginSettings.Enable = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = false }) _, resp = th.SystemAdminClient.GetPlugins() CheckNotImplementedStatus(t, resp) - *utils.Cfg.PluginSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) _, resp = th.Client.GetPlugins() CheckForbiddenStatus(t, resp) @@ -111,11 +112,11 @@ func TestPlugin(t *testing.T) { assert.False(t, ok) - *utils.Cfg.PluginSettings.Enable = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = false }) _, resp = th.SystemAdminClient.RemovePlugin(manifest.Id) CheckNotImplementedStatus(t, resp) - *utils.Cfg.PluginSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) _, resp = th.Client.RemovePlugin(manifest.Id) CheckForbiddenStatus(t, resp) diff --git a/api4/post_test.go b/api4/post_test.go index 27e6d6458..3a410f2b4 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -124,19 +124,23 @@ func testCreatePostWithOutgoingHook( team := th.BasicTeam channel := th.BasicChannel - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations - allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations + allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() - utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.AllowedUntrustedInternalConnections = &allowedInternalConnections + }) }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() - *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + th.App.UpdateConfig(func(cfg *model.Config) { + *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost 127.0.0.1" + }) var hook *model.OutgoingWebhook var post *model.Post @@ -375,18 +379,18 @@ func TestUpdatePost(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - allowEditPost := *utils.Cfg.ServiceSettings.AllowEditPost + allowEditPost := *th.App.Config().ServiceSettings.AllowEditPost defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.AllowEditPost = allowEditPost + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = allowEditPost }) utils.SetDefaultRolesBasedOnConfig() }() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS }) utils.SetDefaultRolesBasedOnConfig() post := &model.Post{ChannelId: channel.Id, Message: "zz" + model.NewId() + "a"} @@ -455,18 +459,18 @@ func TestPatchPost(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - allowEditPost := *utils.Cfg.ServiceSettings.AllowEditPost + allowEditPost := *th.App.Config().ServiceSettings.AllowEditPost defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.AllowEditPost = allowEditPost + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = allowEditPost }) utils.SetDefaultRolesBasedOnConfig() }() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() - *utils.Cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowEditPost = model.ALLOW_EDIT_POST_ALWAYS }) utils.SetDefaultRolesBasedOnConfig() post := &model.Post{ diff --git a/api4/system.go b/api4/system.go index b8c927630..920e9a63d 100644 --- a/api4/system.go +++ b/api4/system.go @@ -44,11 +44,11 @@ func (api *API) InitSystem() { func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { actualGoroutines := runtime.NumGoroutine() - if *utils.Cfg.ServiceSettings.GoroutineHealthThreshold <= 0 || actualGoroutines <= *utils.Cfg.ServiceSettings.GoroutineHealthThreshold { + if *c.App.Config().ServiceSettings.GoroutineHealthThreshold <= 0 || actualGoroutines <= *c.App.Config().ServiceSettings.GoroutineHealthThreshold { m := make(map[string]string) m[model.STATUS] = model.STATUS_OK - reqs := utils.Cfg.ClientRequirements + reqs := c.App.Config().ClientRequirements m["AndroidLatestVersion"] = reqs.AndroidLatestVersion m["AndroidMinVersion"] = reqs.AndroidMinVersion m["DesktopLatestVersion"] = reqs.DesktopLatestVersion @@ -61,7 +61,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { rdata := map[string]string{} rdata["status"] = "unhealthy" - l4g.Warn(utils.T("api.system.go_routines"), actualGoroutines, *utils.Cfg.ServiceSettings.GoroutineHealthThreshold) + l4g.Warn(utils.T("api.system.go_routines"), actualGoroutines, *c.App.Config().ServiceSettings.GoroutineHealthThreshold) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(model.MapToJson(rdata))) @@ -71,7 +71,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { cfg := model.ConfigFromJson(r.Body) if cfg == nil { - cfg = utils.Cfg + cfg = c.App.Config() } if !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { @@ -198,7 +198,7 @@ func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { } func postLog(c *Context, w http.ResponseWriter, r *http.Request) { - if !*utils.Cfg.ServiceSettings.EnableDeveloper && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !*c.App.Config().ServiceSettings.EnableDeveloper && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -286,7 +286,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { return } - err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize) + err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return diff --git a/api4/system_test.go b/api4/system_test.go index 2855e5840..14165acb4 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -7,7 +7,6 @@ import ( l4g "github.com/alecthomas/log4go" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestGetPing(t *testing.T) { @@ -15,9 +14,9 @@ func TestGetPing(t *testing.T) { defer th.TearDown() Client := th.Client - goRoutineHealthThreshold := *utils.Cfg.ServiceSettings.GoroutineHealthThreshold + goRoutineHealthThreshold := *th.App.Config().ServiceSettings.GoroutineHealthThreshold defer func() { - *utils.Cfg.ServiceSettings.GoroutineHealthThreshold = goRoutineHealthThreshold + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = goRoutineHealthThreshold }) }() status, resp := Client.GetPing() @@ -26,7 +25,7 @@ func TestGetPing(t *testing.T) { t.Fatal("should return OK") } - *utils.Cfg.ServiceSettings.GoroutineHealthThreshold = 10 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = 10 }) status, resp = th.SystemAdminClient.GetPing() CheckInternalErrorStatus(t, resp) if status != "unhealthy" { @@ -98,8 +97,8 @@ func TestReloadConfig(t *testing.T) { t.Fatal("should Reload the config") } - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.TeamSettings.EnableOpenServer = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) } func TestUpdateConfig(t *testing.T) { @@ -112,7 +111,7 @@ func TestUpdateConfig(t *testing.T) { _, resp := Client.UpdateConfig(cfg) CheckForbiddenStatus(t, resp) - SiteName := utils.Cfg.TeamSettings.SiteName + SiteName := th.App.Config().TeamSettings.SiteName cfg.TeamSettings.SiteName = "MyFancyName" cfg, resp = th.SystemAdminClient.UpdateConfig(cfg) @@ -243,21 +242,21 @@ func TestEmailTest(t *testing.T) { defer th.TearDown() Client := th.Client - SendEmailNotifications := utils.Cfg.EmailSettings.SendEmailNotifications - SMTPServer := utils.Cfg.EmailSettings.SMTPServer - SMTPPort := utils.Cfg.EmailSettings.SMTPPort - FeedbackEmail := utils.Cfg.EmailSettings.FeedbackEmail + SendEmailNotifications := th.App.Config().EmailSettings.SendEmailNotifications + SMTPServer := th.App.Config().EmailSettings.SMTPServer + SMTPPort := th.App.Config().EmailSettings.SMTPPort + FeedbackEmail := th.App.Config().EmailSettings.FeedbackEmail defer func() { - utils.Cfg.EmailSettings.SendEmailNotifications = SendEmailNotifications - utils.Cfg.EmailSettings.SMTPServer = SMTPServer - utils.Cfg.EmailSettings.SMTPPort = SMTPPort - utils.Cfg.EmailSettings.FeedbackEmail = FeedbackEmail + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = SendEmailNotifications }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPServer = SMTPServer }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPPort = SMTPPort }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.FeedbackEmail = FeedbackEmail }) }() - utils.Cfg.EmailSettings.SendEmailNotifications = false - utils.Cfg.EmailSettings.SMTPServer = "" - utils.Cfg.EmailSettings.SMTPPort = "" - utils.Cfg.EmailSettings.FeedbackEmail = "" + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SendEmailNotifications = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPServer = "" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.SMTPPort = "" }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.EmailSettings.FeedbackEmail = "" }) _, resp := Client.TestEmail() CheckForbiddenStatus(t, resp) diff --git a/api4/team_test.go b/api4/team_test.go index 45484e2a1..f0668d9ac 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -68,12 +68,12 @@ func TestCreateTeam(t *testing.T) { CheckUnauthorizedStatus(t, resp) // Update permission - enableTeamCreation := utils.Cfg.TeamSettings.EnableTeamCreation + enableTeamCreation := th.App.Config().TeamSettings.EnableTeamCreation defer func() { - utils.Cfg.TeamSettings.EnableTeamCreation = enableTeamCreation + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableTeamCreation = enableTeamCreation }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.TeamSettings.EnableTeamCreation = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableTeamCreation = false }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -1295,18 +1295,18 @@ func TestAddTeamMember(t *testing.T) { Client.Logout() // Check effects of config and license changes. - restrictTeamInvite := *utils.Cfg.TeamSettings.RestrictTeamInvite + restrictTeamInvite := *th.App.Config().TeamSettings.RestrictTeamInvite isLicensed := utils.IsLicensed() license := utils.License() defer func() { - *utils.Cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() // Set the config so that only team admins can add a user to a team. - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -1328,7 +1328,7 @@ func TestAddTeamMember(t *testing.T) { // Update user to team admin th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) th.App.InvalidateAllCaches() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1340,7 +1340,7 @@ func TestAddTeamMember(t *testing.T) { CheckNoError(t, resp) // Change permission level to System Admin - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() // Should not work as team admin. @@ -1354,7 +1354,7 @@ func TestAddTeamMember(t *testing.T) { // Change permission level to All th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.App.InvalidateAllCaches() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1366,7 +1366,7 @@ func TestAddTeamMember(t *testing.T) { CheckNoError(t, resp) // Reset config and license. - *utils.Cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() @@ -1380,7 +1380,7 @@ func TestAddTeamMember(t *testing.T) { dataObject["id"] = team.Id data := model.MapToJson(dataObject) - hashed := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hashed := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) tm, resp = Client.AddTeamMemberFromInvite(hashed, data, "") CheckNoError(t, resp) @@ -1410,7 +1410,7 @@ func TestAddTeamMember(t *testing.T) { // expired data of more than 50 hours dataObject["time"] = fmt.Sprintf("%v", model.GetMillis()-1000*60*60*50) data = model.MapToJson(dataObject) - hashed = utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hashed = utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) tm, resp = Client.AddTeamMemberFromInvite(hashed, data, "") CheckBadRequestStatus(t, resp) @@ -1418,7 +1418,7 @@ func TestAddTeamMember(t *testing.T) { // invalid team id dataObject["id"] = GenerateTestId() data = model.MapToJson(dataObject) - hashed = utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hashed = utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) tm, resp = Client.AddTeamMemberFromInvite(hashed, data, "") CheckBadRequestStatus(t, resp) @@ -1509,18 +1509,18 @@ func TestAddTeamMembers(t *testing.T) { Client.Logout() // Check effects of config and license changes. - restrictTeamInvite := *utils.Cfg.TeamSettings.RestrictTeamInvite + restrictTeamInvite := *th.App.Config().TeamSettings.RestrictTeamInvite isLicensed := utils.IsLicensed() license := utils.License() defer func() { - *utils.Cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = restrictTeamInvite }) utils.SetIsLicensed(isLicensed) utils.SetLicense(license) utils.SetDefaultRolesBasedOnConfig() }() // Set the config so that only team admins can add a user to a team. - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() th.LoginBasic() @@ -1542,7 +1542,7 @@ func TestAddTeamMembers(t *testing.T) { // Update user to team admin th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) th.App.InvalidateAllCaches() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_TEAM_ADMIN }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1554,7 +1554,7 @@ func TestAddTeamMembers(t *testing.T) { CheckNoError(t, resp) // Change permission level to System Admin - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_SYSTEM_ADMIN }) utils.SetDefaultRolesBasedOnConfig() // Should not work as team admin. @@ -1568,7 +1568,7 @@ func TestAddTeamMembers(t *testing.T) { // Change permission level to All th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.App.InvalidateAllCaches() - *utils.Cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_ALL + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictTeamInvite = model.PERMISSIONS_ALL }) utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() @@ -1898,7 +1898,7 @@ func TestInviteUsersToTeam(t *testing.T) { t.Fatal("should return true") } - nameFormat := *utils.Cfg.TeamSettings.TeammateNameDisplay + nameFormat := *th.App.Config().TeamSettings.TeammateNameDisplay expectedSubject := "[Mattermost] " + th.SystemAdminUser.GetDisplayName(nameFormat) + " invited you to join " + th.BasicTeam.DisplayName + " Team" //Check if the email was send to the rigth email address for _, email := range emailList { @@ -1927,11 +1927,11 @@ func TestInviteUsersToTeam(t *testing.T) { } } - restrictCreationToDomains := utils.Cfg.TeamSettings.RestrictCreationToDomains + restrictCreationToDomains := th.App.Config().TeamSettings.RestrictCreationToDomains defer func() { - utils.Cfg.TeamSettings.RestrictCreationToDomains = restrictCreationToDomains + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.RestrictCreationToDomains = restrictCreationToDomains }) }() - utils.Cfg.TeamSettings.RestrictCreationToDomains = "@example.com" + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.RestrictCreationToDomains = "@example.com" }) err := th.App.InviteNewUsersToTeam(emailList, th.BasicTeam.Id, th.BasicUser.Id) diff --git a/api4/user.go b/api4/user.go index 07f223bd6..d17591afa 100644 --- a/api4/user.go +++ b/api4/user.go @@ -112,7 +112,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + etag := user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress) if c.HandleEtag(etag, "Get User", w, r) { return @@ -145,7 +145,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } - etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + etag := user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress) if c.HandleEtag(etag, "Get User", w, r) { return @@ -173,7 +173,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { return } - etag := user.Etag(utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + etag := user.Etag(c.App.Config().PrivacySettings.ShowFullName, c.App.Config().PrivacySettings.ShowEmailAddress) if c.HandleEtag(etag, "Get User", w, r) { return @@ -235,17 +235,17 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*c.App.Config().FileSettings.DriverName) == 0 { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.storage.app_error", nil, "", http.StatusNotImplemented) return } - if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { + if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge) return } - if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { + if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil { c.Err = model.NewAppError("uploadProfileImage", "api.user.upload_profile_user.parse.app_error", nil, err.Error(), http.StatusInternalServerError) return } @@ -453,8 +453,8 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { searchOptions[store.USER_SEARCH_OPTION_ALLOW_INACTIVE] = props.AllowInactive if !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName - hideEmail := !utils.Cfg.PrivacySettings.ShowEmailAddress + hideFullName := !c.App.Config().PrivacySettings.ShowFullName + hideEmail := !c.App.Config().PrivacySettings.ShowEmailAddress if hideFullName && hideEmail { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true @@ -483,7 +483,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { searchOptions := map[string]bool{} - hideFullName := !utils.Cfg.PrivacySettings.ShowFullName + hideFullName := !c.App.Config().PrivacySettings.ShowFullName if hideFullName && !app.SessionHasPermissionTo(c.Session, model.PERMISSION_MANAGE_SYSTEM) { searchOptions[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true } else { @@ -701,7 +701,7 @@ func checkUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { resp := map[string]interface{}{} resp["mfa_required"] = false - if !utils.IsLicensed() || !*utils.License().Features.MFA || !*utils.Cfg.ServiceSettings.EnableMultifactorAuthentication { + if !utils.IsLicensed() || !*utils.License().Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication { w.Write([]byte(model.StringInterfaceToJson(resp))) return } @@ -1022,9 +1022,9 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.ClearSessionCacheForUser(c.Session.UserId) - c.Session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthMobileInDays) + c.Session.SetExpireInDays(*c.App.Config().ServiceSettings.SessionLengthMobileInDays) - maxAge := *utils.Cfg.ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 + maxAge := *c.App.Config().ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 secure := false if app.GetProtocol(r) == "https" { diff --git a/api4/user_test.go b/api4/user_test.go index 3a1579e14..ceaf3f038 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -63,14 +63,14 @@ func TestCreateUser(t *testing.T) { CheckErrorMessage(t, resp, "model.user.is_valid.email.app_error") CheckBadRequestStatus(t, resp) - openServer := *utils.Cfg.TeamSettings.EnableOpenServer - canCreateAccount := utils.Cfg.TeamSettings.EnableUserCreation + openServer := *th.App.Config().TeamSettings.EnableOpenServer + canCreateAccount := th.App.Config().TeamSettings.EnableUserCreation defer func() { - *utils.Cfg.TeamSettings.EnableOpenServer = openServer - utils.Cfg.TeamSettings.EnableUserCreation = canCreateAccount + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = openServer }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = canCreateAccount }) }() - *utils.Cfg.TeamSettings.EnableOpenServer = false - utils.Cfg.TeamSettings.EnableUserCreation = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) user2 := &model.User{Email: GenerateTestEmail(), Password: "Password1", Username: GenerateTestUsername()} _, resp = AdminClient.CreateUser(user2) @@ -101,7 +101,7 @@ func TestCreateUserWithHash(t *testing.T) { props["name"] = th.BasicTeam.Name props["time"] = fmt.Sprintf("%v", model.GetMillis()) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) ruser, resp := Client.CreateUserWithHash(&user, hash, data) CheckNoError(t, resp) @@ -127,7 +127,7 @@ func TestCreateUserWithHash(t *testing.T) { props["name"] = th.BasicTeam.Name props["time"] = fmt.Sprintf("%v", model.GetMillis()) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) _, resp := Client.CreateUserWithHash(&user, "", data) CheckBadRequestStatus(t, resp) @@ -150,7 +150,7 @@ func TestCreateUserWithHash(t *testing.T) { props["name"] = th.BasicTeam.Name props["time"] = fmt.Sprintf("%v", past49Hours) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) _, resp := Client.CreateUserWithHash(&user, hash, data) CheckInternalErrorStatus(t, resp) @@ -183,13 +183,13 @@ func TestCreateUserWithHash(t *testing.T) { props["name"] = th.BasicTeam.Name props["time"] = fmt.Sprintf("%v", model.GetMillis()) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) - canCreateAccount := utils.Cfg.TeamSettings.EnableUserCreation + canCreateAccount := th.App.Config().TeamSettings.EnableUserCreation defer func() { - utils.Cfg.TeamSettings.EnableUserCreation = canCreateAccount + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = canCreateAccount }) }() - utils.Cfg.TeamSettings.EnableUserCreation = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) _, resp := Client.CreateUserWithHash(&user, hash, data) CheckNotImplementedStatus(t, resp) @@ -206,13 +206,13 @@ func TestCreateUserWithHash(t *testing.T) { props["name"] = th.BasicTeam.Name props["time"] = fmt.Sprintf("%v", model.GetMillis()) data := model.MapToJson(props) - hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) + hash := utils.HashSha256(fmt.Sprintf("%v:%v", data, th.App.Config().EmailSettings.InviteSalt)) - openServer := *utils.Cfg.TeamSettings.EnableOpenServer + openServer := *th.App.Config().TeamSettings.EnableOpenServer defer func() { - *utils.Cfg.TeamSettings.EnableOpenServer = openServer + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = openServer }) }() - *utils.Cfg.TeamSettings.EnableOpenServer = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) ruser, resp := Client.CreateUserWithHash(&user, hash, data) CheckNoError(t, resp) @@ -291,11 +291,11 @@ func TestCreateUserWithInviteId(t *testing.T) { t.Run("EnableUserCreationDisable", func(t *testing.T) { user := model.User{Email: GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.ROLE_SYSTEM_ADMIN.Id + " " + model.ROLE_SYSTEM_USER.Id} - canCreateAccount := utils.Cfg.TeamSettings.EnableUserCreation + canCreateAccount := th.App.Config().TeamSettings.EnableUserCreation defer func() { - utils.Cfg.TeamSettings.EnableUserCreation = canCreateAccount + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = canCreateAccount }) }() - utils.Cfg.TeamSettings.EnableUserCreation = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) inviteId := th.BasicTeam.InviteId @@ -307,11 +307,11 @@ func TestCreateUserWithInviteId(t *testing.T) { t.Run("EnableOpenServerDisable", func(t *testing.T) { user := model.User{Email: GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.ROLE_SYSTEM_ADMIN.Id + " " + model.ROLE_SYSTEM_USER.Id} - openServer := *utils.Cfg.TeamSettings.EnableOpenServer + openServer := *th.App.Config().TeamSettings.EnableOpenServer defer func() { - *utils.Cfg.TeamSettings.EnableOpenServer = openServer + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = openServer }) }() - *utils.Cfg.TeamSettings.EnableOpenServer = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) inviteId := th.BasicTeam.InviteId @@ -374,14 +374,14 @@ func TestGetUser(t *testing.T) { CheckNotFoundStatus(t, resp) // Check against privacy config settings - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) ruser, resp = Client.GetUser(user.Id, "") CheckNoError(t, resp) @@ -435,14 +435,14 @@ func TestGetUserByUsername(t *testing.T) { CheckNotFoundStatus(t, resp) // Check against privacy config settings - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) ruser, resp = Client.GetUserByUsername(user.Username, "") CheckNoError(t, resp) @@ -499,14 +499,14 @@ func TestGetUserByEmail(t *testing.T) { CheckNotFoundStatus(t, resp) // Check against privacy config settings - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) ruser, resp = Client.GetUserByEmail(user.Email, "") CheckNoError(t, resp) @@ -666,14 +666,14 @@ func TestSearchUsers(t *testing.T) { search.Term = th.BasicUser.Username - emailPrivacy := utils.Cfg.PrivacySettings.ShowEmailAddress - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + emailPrivacy := th.App.Config().PrivacySettings.ShowEmailAddress + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowEmailAddress = emailPrivacy - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = emailPrivacy }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowEmailAddress = false - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) _, err = th.App.UpdateActiveNoLdap(th.BasicUser2.Id, true) if err != nil { @@ -824,11 +824,11 @@ func TestAutocompleteUsers(t *testing.T) { CheckNoError(t, resp) // Check against privacy config settings - namePrivacy := utils.Cfg.PrivacySettings.ShowFullName + namePrivacy := th.App.Config().PrivacySettings.ShowFullName defer func() { - utils.Cfg.PrivacySettings.ShowFullName = namePrivacy + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = namePrivacy }) }() - utils.Cfg.PrivacySettings.ShowFullName = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) th.LoginBasic() @@ -1544,17 +1544,17 @@ func TestUpdateUserMfa(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - enableMfa := *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication + enableMfa := *th.App.Config().ServiceSettings.EnableMultifactorAuthentication defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa }) }() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() *utils.License().Features.MFA = true - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true @@ -1616,17 +1616,17 @@ func TestCheckUserMfa(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - enableMfa := *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication + enableMfa := *th.App.Config().ServiceSettings.EnableMultifactorAuthentication defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa }) }() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() *utils.License().Features.MFA = true - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) th.LoginBasic() @@ -1663,17 +1663,17 @@ func TestGenerateMfaSecret(t *testing.T) { isLicensed := utils.IsLicensed() license := utils.License() - enableMfa := *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication + enableMfa := *th.App.Config().ServiceSettings.EnableMultifactorAuthentication defer func() { utils.SetIsLicensed(isLicensed) utils.SetLicense(license) - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = enableMfa }) }() utils.SetIsLicensed(true) utils.SetLicense(&model.License{Features: &model.Features{}}) utils.License().Features.SetDefaults() *utils.License().Features.MFA = true - *utils.Cfg.ServiceSettings.EnableMultifactorAuthentication = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) _, resp = Client.GenerateMfaSecret(model.NewId()) CheckForbiddenStatus(t, resp) @@ -1733,11 +1733,11 @@ func TestUpdateUserPassword(t *testing.T) { th.LoginBasic() // Test lockout - passwordAttempts := *utils.Cfg.ServiceSettings.MaximumLoginAttempts + passwordAttempts := *th.App.Config().ServiceSettings.MaximumLoginAttempts defer func() { - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = passwordAttempts }) }() - *utils.Cfg.ServiceSettings.MaximumLoginAttempts = 2 + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 }) // Fail twice _, resp = Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd") @@ -2175,11 +2175,11 @@ func TestSwitchAccount(t *testing.T) { defer th.TearDown() Client := th.Client - enableGitLab := utils.Cfg.GitLabSettings.Enable + enableGitLab := th.App.Config().GitLabSettings.Enable defer func() { - utils.Cfg.GitLabSettings.Enable = enableGitLab + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = enableGitLab }) }() - utils.Cfg.GitLabSettings.Enable = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = true }) Client.Logout() @@ -2269,11 +2269,11 @@ func TestCreateUserAccessToken(t *testing.T) { testDescription := "test token" - enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens + enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens defer func() { - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens }) }() - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) _, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckForbiddenStatus(t, resp) @@ -2286,10 +2286,10 @@ func TestCreateUserAccessToken(t *testing.T) { th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id) - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false }) _, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckNotImplementedStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) rtoken, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckNoError(t, resp) @@ -2352,11 +2352,11 @@ func TestGetUserAccessToken(t *testing.T) { testDescription := "test token" - enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens + enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens defer func() { - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens }) }() - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) _, resp := Client.GetUserAccessToken("123") CheckBadRequestStatus(t, resp) @@ -2423,11 +2423,11 @@ func TestRevokeUserAccessToken(t *testing.T) { testDescription := "test token" - enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens + enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens defer func() { - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens }) }() - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id) token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) @@ -2470,11 +2470,11 @@ func TestUserAccessTokenInactiveUser(t *testing.T) { testDescription := "test token" - enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens + enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens defer func() { - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens }) }() - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id) token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) @@ -2497,11 +2497,11 @@ func TestUserAccessTokenDisableConfig(t *testing.T) { testDescription := "test token" - enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens + enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens defer func() { - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens }) }() - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id) token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) @@ -2512,7 +2512,7 @@ func TestUserAccessTokenDisableConfig(t *testing.T) { _, resp = Client.GetMe("") CheckNoError(t, resp) - *utils.Cfg.ServiceSettings.EnableUserAccessTokens = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false }) _, resp = Client.GetMe("") CheckUnauthorizedStatus(t, resp) diff --git a/api4/webhook.go b/api4/webhook.go index 39d0cbff4..1921659ce 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -459,7 +459,7 @@ func incomingWebhook(c *Context, w http.ResponseWriter, r *http.Request) { payload = r.Body } - if utils.Cfg.LogSettings.EnableWebhookDebugging { + if c.App.Config().LogSettings.EnableWebhookDebugging { var err error payload, err = utils.InfoReader( payload, diff --git a/api4/webhook_test.go b/api4/webhook_test.go index f8d33e984..6740ee097 100644 --- a/api4/webhook_test.go +++ b/api4/webhook_test.go @@ -19,15 +19,15 @@ func TestCreateIncomingWebhook(t *testing.T) { defer th.TearDown() Client := th.Client - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -60,13 +60,13 @@ func TestCreateIncomingWebhook(t *testing.T) { _, resp = Client.CreateIncomingWebhook(hook) CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.CreateIncomingWebhook(hook) CheckNoError(t, resp) - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) _, resp = Client.CreateIncomingWebhook(hook) CheckNotImplementedStatus(t, resp) } @@ -76,15 +76,15 @@ func TestGetIncomingWebhooks(t *testing.T) { defer th.TearDown() Client := th.Client - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -136,7 +136,7 @@ func TestGetIncomingWebhooks(t *testing.T) { _, resp = Client.GetIncomingWebhooks(0, 1000, "") CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.GetIncomingWebhooksForTeam(th.BasicTeam.Id, 0, 1000, "") @@ -158,15 +158,15 @@ func TestGetIncomingWebhook(t *testing.T) { defer th.TearDown() Client := th.SystemAdminClient - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() var resp *model.Response @@ -206,15 +206,15 @@ func TestDeleteIncomingWebhook(t *testing.T) { defer th.TearDown() Client := th.SystemAdminClient - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() var resp *model.Response @@ -266,15 +266,15 @@ func TestCreateOutgoingWebhook(t *testing.T) { defer th.TearDown() Client := th.Client - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -303,13 +303,13 @@ func TestCreateOutgoingWebhook(t *testing.T) { _, resp = Client.CreateOutgoingWebhook(hook) CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.CreateOutgoingWebhook(hook) CheckNoError(t, resp) - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) _, resp = Client.CreateOutgoingWebhook(hook) CheckNotImplementedStatus(t, resp) } @@ -319,15 +319,15 @@ func TestGetOutgoingWebhooks(t *testing.T) { defer th.TearDown() Client := th.Client - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -396,7 +396,7 @@ func TestGetOutgoingWebhooks(t *testing.T) { _, resp = Client.GetOutgoingWebhooks(0, 1000, "") CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() _, resp = Client.GetOutgoingWebhooksForTeam(th.BasicTeam.Id, 0, 1000, "") @@ -424,15 +424,15 @@ func TestGetOutgoingWebhook(t *testing.T) { defer th.TearDown() Client := th.Client - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -463,15 +463,15 @@ func TestUpdateIncomingHook(t *testing.T) { defer th.TearDown() Client := th.Client - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook1 := &model.IncomingWebhook{ChannelId: th.BasicChannel.Id} @@ -555,10 +555,10 @@ func TestUpdateIncomingHook(t *testing.T) { CheckForbiddenStatus(t, resp) }) - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) t.Run("OnlyAdminIntegrationsDisabled", func(t *testing.T) { - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() t.Run("UpdateHookOfSameUser", func(t *testing.T) { @@ -577,7 +577,7 @@ func TestUpdateIncomingHook(t *testing.T) { }) }) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() Client.Logout() @@ -592,13 +592,13 @@ func TestUpdateIncomingHook(t *testing.T) { }) t.Run("IncomingHooksDisabled", func(t *testing.T) { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = false }) _, resp := Client.UpdateIncomingWebhook(createdHook) CheckNotImplementedStatus(t, resp) CheckErrorMessage(t, resp, "api.incoming_webhook.disabled.app_error") }) - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) t.Run("PrivateChannel", func(t *testing.T) { privateChannel := th.CreatePrivateChannel() @@ -632,15 +632,15 @@ func TestRegenOutgoingHookToken(t *testing.T) { defer th.TearDown() Client := th.Client - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() hook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}} @@ -663,7 +663,7 @@ func TestRegenOutgoingHookToken(t *testing.T) { _, resp = Client.RegenOutgoingHookToken(rhook.Id) CheckForbiddenStatus(t, resp) - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) _, resp = th.SystemAdminClient.RegenOutgoingHookToken(rhook.Id) CheckNotImplementedStatus(t, resp) } @@ -673,15 +673,15 @@ func TestUpdateOutgoingHook(t *testing.T) { defer th.TearDown() Client := th.Client - enableOutgoingHooks := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableOutgoingHooks := th.App.Config().ServiceSettings.EnableOutgoingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() createdHook := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, @@ -705,12 +705,12 @@ func TestUpdateOutgoingHook(t *testing.T) { }) t.Run("OutgoingHooksDisabled", func(t *testing.T) { - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = false + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = false }) _, resp := th.SystemAdminClient.UpdateOutgoingWebhook(createdHook) CheckNotImplementedStatus(t, resp) }) - utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOutgoingWebhooks = true }) t.Run("RetainCreateAt", func(t *testing.T) { hook2 := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, TriggerWords: []string{"rats"}} @@ -755,7 +755,7 @@ func TestUpdateOutgoingHook(t *testing.T) { CheckForbiddenStatus(t, resp) }) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = false }) utils.SetDefaultRolesBasedOnConfig() hook2 := &model.OutgoingWebhook{ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, TriggerWords: []string{"rats2"}} @@ -766,7 +766,7 @@ func TestUpdateOutgoingHook(t *testing.T) { _, resp = Client.UpdateOutgoingWebhook(createdHook2) CheckForbiddenStatus(t, resp) - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() Client.Logout() @@ -840,15 +840,15 @@ func TestDeleteOutgoingHook(t *testing.T) { defer th.TearDown() Client := th.SystemAdminClient - enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks - enableAdminOnlyHooks := utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations + enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks + enableAdminOnlyHooks := th.App.Config().ServiceSettings.EnableOnlyAdminIntegrations defer func() { - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks - utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks }) + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableOnlyAdminIntegrations = enableAdminOnlyHooks }) utils.SetDefaultRolesBasedOnConfig() }() - utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true - *utils.Cfg.ServiceSettings.EnableOnlyAdminIntegrations = true + th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true }) + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOnlyAdminIntegrations = true }) utils.SetDefaultRolesBasedOnConfig() var resp *model.Response diff --git a/api4/webrtc_test.go b/api4/webrtc_test.go index 4e2f28fb5..660bb6f62 100644 --- a/api4/webrtc_test.go +++ b/api4/webrtc_test.go @@ -4,9 +4,8 @@ package api4 import ( + "github.com/mattermost/mattermost-server/model" "testing" - - "github.com/mattermost/mattermost-server/utils" ) func TestGetWebrtcToken(t *testing.T) { @@ -18,11 +17,11 @@ func TestGetWebrtcToken(t *testing.T) { defer th.TearDown() Client := th.Client - enableWebrtc := *utils.Cfg.WebrtcSettings.Enable + enableWebrtc := *th.App.Config().WebrtcSettings.Enable defer func() { - *utils.Cfg.WebrtcSettings.Enable = enableWebrtc + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.WebrtcSettings.Enable = enableWebrtc }) }() - *utils.Cfg.WebrtcSettings.Enable = false + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.WebrtcSettings.Enable = false }) _, resp := Client.GetWebrtcToken() CheckNotImplementedStatus(t, resp) diff --git a/app/admin.go b/app/admin.go index 5994fc826..fc792a3f0 100644 --- a/app/admin.go +++ b/app/admin.go @@ -24,7 +24,7 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { perPage = 10000 var lines []string - if a.Cluster != nil && *utils.Cfg.ClusterSettings.Enable { + if a.Cluster != nil && *a.Config().ClusterSettings.Enable { lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, a.Cluster.GetMyClusterInfo().Hostname) @@ -39,7 +39,7 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { lines = append(lines, melines...) - if a.Cluster != nil && *utils.Cfg.ClusterSettings.Enable { + if a.Cluster != nil && *a.Config().ClusterSettings.Enable { clines, err := a.Cluster.GetLogs(page, perPage) if err != nil { return nil, err @@ -54,8 +54,8 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { var lines []string - if utils.Cfg.LogSettings.EnableFile { - file, err := os.Open(utils.GetLogFileLocation(utils.Cfg.LogSettings.FileLocation)) + if a.Config().LogSettings.EnableFile { + file, err := os.Open(utils.GetLogFileLocation(a.Config().LogSettings.FileLocation)) if err != nil { return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, err.Error(), http.StatusInternalServerError) } @@ -124,7 +124,7 @@ func (a *App) InvalidateAllCachesSkipSend() { } func (a *App) GetConfig() *model.Config { - json := utils.Cfg.ToJson() + json := a.Config().ToJson() cfg := model.ConfigFromJson(strings.NewReader(json)) cfg.Sanitize() @@ -140,7 +140,7 @@ func (a *App) ReloadConfig() { } func (a *App) SaveConfig(cfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { - oldCfg := utils.Cfg + oldCfg := a.Config() cfg.SetDefaults() utils.Desanitize(cfg) @@ -152,7 +152,7 @@ func (a *App) SaveConfig(cfg *model.Config, sendConfigChangeClusterMessage bool) return err } - if *utils.Cfg.ClusterSettings.Enable && *utils.Cfg.ClusterSettings.ReadOnlyConfig { + if *a.Config().ClusterSettings.Enable && *a.Config().ClusterSettings.ReadOnlyConfig { return model.NewAppError("saveConfig", "ent.cluster.save_config.error", nil, "", http.StatusForbidden) } @@ -162,7 +162,7 @@ func (a *App) SaveConfig(cfg *model.Config, sendConfigChangeClusterMessage bool) utils.EnableConfigWatch() if a.Metrics != nil { - if *utils.Cfg.MetricsSettings.Enable { + if *a.Config().MetricsSettings.Enable { a.Metrics.StartServer() } else { a.Metrics.StopServer() @@ -205,10 +205,10 @@ 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.SMTPServer == utils.Cfg.EmailSettings.SMTPServer && - cfg.EmailSettings.SMTPPort == utils.Cfg.EmailSettings.SMTPPort && - cfg.EmailSettings.SMTPUsername == utils.Cfg.EmailSettings.SMTPUsername { - cfg.EmailSettings.SMTPPassword = utils.Cfg.EmailSettings.SMTPPassword + if cfg.EmailSettings.SMTPServer == a.Config().EmailSettings.SMTPServer && + cfg.EmailSettings.SMTPPort == a.Config().EmailSettings.SMTPPort && + cfg.EmailSettings.SMTPUsername == a.Config().EmailSettings.SMTPUsername { + cfg.EmailSettings.SMTPPassword = a.Config().EmailSettings.SMTPPassword } else { return model.NewAppError("testEmail", "api.admin.test_email.reenter_password", nil, "", http.StatusBadRequest) } diff --git a/app/analytics.go b/app/analytics.go index 65a9e4129..5d30ad426 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -7,7 +7,6 @@ import ( l4g "github.com/alecthomas/log4go" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/store" - "github.com/mattermost/mattermost-server/utils" ) const ( @@ -22,8 +21,8 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo return nil, r.Err } else { systemUserCount = r.Data.(int64) - if systemUserCount > int64(*utils.Cfg.AnalyticsSettings.MaxUsersForStatistics) { - l4g.Debug("More than %v users on the system, intensive queries skipped", *utils.Cfg.AnalyticsSettings.MaxUsersForStatistics) + if systemUserCount > int64(*a.Config().AnalyticsSettings.MaxUsersForStatistics) { + l4g.Debug("More than %v users on the system, intensive queries skipped", *a.Config().AnalyticsSettings.MaxUsersForStatistics) skipIntensiveQueries = true } } @@ -97,7 +96,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo } // If in HA mode then aggregrate all the stats - if a.Cluster != nil && *utils.Cfg.ClusterSettings.Enable { + if a.Cluster != nil && *a.Config().ClusterSettings.Enable { stats, err := a.Cluster.GetClusterStats() if err != nil { return nil, err diff --git a/app/app.go b/app/app.go index 34c0721a0..c82520cd9 100644 --- a/app/app.go +++ b/app/app.go @@ -47,8 +47,7 @@ type App struct { Mfa einterfaces.MfaInterface Saml einterfaces.SamlInterface - newStore func() store.Store - configOverride func(*model.Config) *model.Config + newStore func() store.Store } var appCount = 0 @@ -234,12 +233,13 @@ func (a *App) initEnterprise() { } func (a *App) Config() *model.Config { - if a.configOverride != nil { - return a.configOverride(utils.Cfg) - } return utils.Cfg } +func (a *App) UpdateConfig(f func(*model.Config)) { + f(utils.Cfg) +} + // Go creates a goroutine, but maintains a record of it to ensure that execution completes before // the app is destroyed. func (a *App) Go(f func()) { diff --git a/app/apptestlib.go b/app/apptestlib.go index 9c26e0bbb..3557a8727 100644 --- a/app/apptestlib.go +++ b/app/apptestlib.go @@ -57,10 +57,6 @@ func setupTestHelper(enterprise bool) *TestHelper { var options []Option if testStore != nil { options = append(options, StoreOverride(testStore)) - options = append(options, ConfigOverride(func(cfg *model.Config) { - cfg.ServiceSettings.ListenAddress = new(string) - *cfg.ServiceSettings.ListenAddress = ":0" - })) } th := &TestHelper{ @@ -70,7 +66,12 @@ func setupTestHelper(enterprise bool) *TestHelper { *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 *utils.Cfg.RateLimitSettings.Enable = false utils.DisableDebugLogForTest() + prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress + if testStore != nil { + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) + } th.App.StartServer() + th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) utils.InitHTML() utils.EnableDebugLogForTest() th.App.Srv.Store.MarkSystemRanUnitTests() diff --git a/app/authentication.go b/app/authentication.go index 01e1e0a48..7aae48b97 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -99,7 +99,7 @@ func (a *App) CheckUserAdditionalAuthenticationCriteria(user *model.User, mfaTok } func (a *App) CheckUserMfa(user *model.User, token string) *model.AppError { - if !user.MfaActive || !utils.IsLicensed() || !*utils.License().Features.MFA || !*utils.Cfg.ServiceSettings.EnableMultifactorAuthentication { + if !user.MfaActive || !utils.IsLicensed() || !*utils.License().Features.MFA || !*a.Config().ServiceSettings.EnableMultifactorAuthentication { return nil } @@ -139,7 +139,7 @@ func checkUserNotDisabled(user *model.User) *model.AppError { } func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) { - ldapAvailable := *utils.Cfg.LdapSettings.Enable && a.Ldap != nil && utils.IsLicensed() && *utils.License().Features.LDAP + ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap != nil && utils.IsLicensed() && *utils.License().Features.LDAP if user.AuthService == model.USER_AUTH_SERVICE_LDAP { if !ldapAvailable { diff --git a/app/brand.go b/app/brand.go index b108a7b32..ea04a59be 100644 --- a/app/brand.go +++ b/app/brand.go @@ -8,11 +8,10 @@ import ( "net/http" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*a.Config().FileSettings.DriverName) == 0 { return model.NewAppError("SaveBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -28,7 +27,7 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { } func (a *App) GetBrandImage() ([]byte, *model.AppError) { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*a.Config().FileSettings.DriverName) == 0 { return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/channel.go b/app/channel.go index 2ab591c42..29e2309cf 100644 --- a/app/channel.go +++ b/app/channel.go @@ -114,8 +114,8 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userId string) (*mod if count, err := a.GetNumberOfChannelsOnTeam(channel.TeamId); err != nil { return nil, err } else { - if int64(count+1) > *utils.Cfg.TeamSettings.MaxChannelsPerTeam { - return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.max_channel_limit.app_error", map[string]interface{}{"MaxChannelsPerTeam": *utils.Cfg.TeamSettings.MaxChannelsPerTeam}, "", http.StatusBadRequest) + if int64(count+1) > *a.Config().TeamSettings.MaxChannelsPerTeam { + return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.max_channel_limit.app_error", map[string]interface{}{"MaxChannelsPerTeam": *a.Config().TeamSettings.MaxChannelsPerTeam}, "", http.StatusBadRequest) } } @@ -212,7 +212,7 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha } func (a *App) WaitForChannelMembership(channelId string, userId string) { - if len(utils.Cfg.SqlSettings.DataSourceReplicas) > 0 { + if len(a.Config().SqlSettings.DataSourceReplicas) > 0 { now := model.GetMillis() for model.GetMillis()-now < 12000 { @@ -1119,7 +1119,7 @@ func (a *App) UpdateChannelLastViewedAt(channelIds []string, userId string) *mod return result.Err } - if *utils.Cfg.ServiceSettings.EnableChannelViewedMessages { + if *a.Config().ServiceSettings.EnableChannelViewedMessages { for _, channelId := range channelIds { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userId, nil) message.Add("channel_id", channelId) @@ -1163,7 +1163,7 @@ func (a *App) ViewChannel(view *model.ChannelView, userId string, clearPushNotif if len(view.PrevChannelId) > 0 { channelIds = append(channelIds, view.PrevChannelId) - if *utils.Cfg.EmailSettings.SendPushNotifications && clearPushNotifications && len(view.ChannelId) > 0 { + if *a.Config().EmailSettings.SendPushNotifications && clearPushNotifications && len(view.ChannelId) > 0 { pchan = a.Srv.Store.User().GetUnreadCountForChannel(userId, view.ChannelId) } } @@ -1191,7 +1191,7 @@ func (a *App) ViewChannel(view *model.ChannelView, userId string, clearPushNotif times = result.Data.(map[string]int64) } - if *utils.Cfg.ServiceSettings.EnableChannelViewedMessages && model.IsValidId(view.ChannelId) { + if *a.Config().ServiceSettings.EnableChannelViewedMessages && model.IsValidId(view.ChannelId) { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userId, nil) message.Add("channel_id", view.ChannelId) a.Go(func() { diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index 5278b339d..6418ab2be 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -80,7 +80,7 @@ func (me *ClusterDiscoveryService) Stop() { } func (a *App) IsLeader() bool { - if utils.IsLicensed() && *utils.Cfg.ClusterSettings.Enable && a.Cluster != nil { + if utils.IsLicensed() && *a.Config().ClusterSettings.Enable && a.Cluster != nil { return a.Cluster.IsLeader() } else { return true diff --git a/app/command.go b/app/command.go index 811294b6d..2d1a8ef71 100644 --- a/app/command.go +++ b/app/command.go @@ -73,7 +73,7 @@ func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([ } } - if *utils.Cfg.ServiceSettings.EnableCommands { + if *a.Config().ServiceSettings.EnableCommands { if result := <-a.Srv.Store.Command().GetByTeam(teamId); result.Err != nil { return nil, result.Err } else { @@ -92,7 +92,7 @@ func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([ } func (a *App) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -115,7 +115,7 @@ func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.C } } - if *utils.Cfg.ServiceSettings.EnableCommands { + if *a.Config().ServiceSettings.EnableCommands { if result := <-a.Srv.Store.Command().GetByTeam(teamId); result.Err != nil { return nil, result.Err } else { @@ -144,7 +144,7 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, * response := provider.DoCommand(a, args, message) return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true) } else { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -251,7 +251,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA post.AddProp("from_webhook", "true") } - if utils.Cfg.ServiceSettings.EnablePostUsernameOverride { + if a.Config().ServiceSettings.EnablePostUsernameOverride { if len(command.Username) != 0 { post.AddProp("override_username", command.Username) } else if len(response.Username) != 0 { @@ -259,7 +259,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA } } - if utils.Cfg.ServiceSettings.EnablePostIconOverride { + if a.Config().ServiceSettings.EnablePostIconOverride { if len(command.IconURL) != 0 { post.AddProp("override_icon_url", command.IconURL) } else if len(response.IconURL) != 0 { @@ -277,7 +277,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA } func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("CreateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -308,7 +308,7 @@ func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError } func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -321,7 +321,7 @@ func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) { } func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("UpdateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -352,7 +352,7 @@ func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppEr } func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return nil, model.NewAppError("RegenCommandToken", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -366,7 +366,7 @@ func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppE } func (a *App) DeleteCommand(commandId string) *model.AppError { - if !*utils.Cfg.ServiceSettings.EnableCommands { + if !*a.Config().ServiceSettings.EnableCommands { return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/command_channel_rename_test.go b/app/command_channel_rename_test.go index 372e366b9..00b9eab0a 100644 --- a/app/command_channel_rename_test.go +++ b/app/command_channel_rename_test.go @@ -15,7 +15,7 @@ func TestRenameProviderDoCommand(t *testing.T) { args := &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, ChannelId: th.BasicChannel.Id, - Session: model.Session{UserId: th.BasicUser.Id, TeamMembers: []*model.TeamMember{&model.TeamMember{TeamId: th.BasicTeam.Id, Roles: model.ROLE_TEAM_USER.Id}}}, + Session: model.Session{UserId: th.BasicUser.Id, TeamMembers: []*model.TeamMember{{TeamId: th.BasicTeam.Id, Roles: model.ROLE_TEAM_USER.Id}}}, } // Blank text is a success diff --git a/app/command_help.go b/app/command_help.go index 41f3a3cb4..d3b803d8b 100644 --- a/app/command_help.go +++ b/app/command_help.go @@ -5,7 +5,6 @@ package app import ( "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" goi18n "github.com/nicksnyder/go-i18n/i18n" ) @@ -34,7 +33,7 @@ func (h *HelpProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (h *HelpProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { - helpLink := *utils.Cfg.SupportSettings.HelpLink + helpLink := *a.Config().SupportSettings.HelpLink if helpLink == "" { helpLink = model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK diff --git a/app/command_invite_people.go b/app/command_invite_people.go index d81eaa34a..03a4d0e36 100644 --- a/app/command_invite_people.go +++ b/app/command_invite_people.go @@ -42,11 +42,11 @@ func (me *InvitePeopleProvider) GetCommand(T goi18n.TranslateFunc) *model.Comman } func (me *InvitePeopleProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { - if !utils.Cfg.EmailSettings.SendEmailNotifications { + if !a.Config().EmailSettings.SendEmailNotifications { return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")} } - if !utils.Cfg.TeamSettings.EnableUserCreation { + if !a.Config().TeamSettings.EnableUserCreation { return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.invite_off")} } diff --git a/app/command_loadtest.go b/app/command_loadtest.go index 4bc371bdc..946f70919 100644 --- a/app/command_loadtest.go +++ b/app/command_loadtest.go @@ -87,7 +87,7 @@ func (me *LoadTestProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *LoadTestProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { //This command is only available when EnableTesting is true - if !utils.Cfg.ServiceSettings.EnableTesting { + if !a.Config().ServiceSettings.EnableTesting { return &model.CommandResponse{} } diff --git a/app/compliance.go b/app/compliance.go index 77590af6c..44e0039d8 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -13,7 +13,7 @@ import ( ) func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) { - if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance { + if !*a.Config().ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance { return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } @@ -25,7 +25,7 @@ func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model } func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { - if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || a.Compliance == nil { + if !*a.Config().ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || a.Compliance == nil { return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } @@ -44,7 +44,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m } func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { - if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || a.Compliance == nil { + if !*a.Config().ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || a.Compliance == nil { return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/diagnostics.go b/app/diagnostics.go index 5f5ef35b2..dda86eb35 100644 --- a/app/diagnostics.go +++ b/app/diagnostics.go @@ -52,7 +52,7 @@ const ( var client *analytics.Client func (a *App) SendDailyDiagnostics() { - if *utils.Cfg.LogSettings.EnableDiagnostics && a.IsLeader() { + if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() { initDiagnostics("") a.trackActivity() trackConfig() @@ -483,7 +483,7 @@ func (a *App) trackServer() { data := map[string]interface{}{ "edition": model.BuildEnterpriseReady, "version": model.CurrentVersion, - "database_type": *utils.Cfg.SqlSettings.DriverName, + "database_type": *a.Config().SqlSettings.DriverName, "operating_system": runtime.GOOS, } diff --git a/app/elasticsearch.go b/app/elasticsearch.go index 71fe6cedb..c3b558bce 100644 --- a/app/elasticsearch.go +++ b/app/elasticsearch.go @@ -7,13 +7,12 @@ import ( "net/http" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { if *cfg.ElasticsearchSettings.Password == model.FAKE_SETTING { - if *cfg.ElasticsearchSettings.ConnectionUrl == *utils.Cfg.ElasticsearchSettings.ConnectionUrl && *cfg.ElasticsearchSettings.Username == *utils.Cfg.ElasticsearchSettings.Username { - *cfg.ElasticsearchSettings.Password = *utils.Cfg.ElasticsearchSettings.Password + if *cfg.ElasticsearchSettings.ConnectionUrl == *a.Config().ElasticsearchSettings.ConnectionUrl && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username { + *cfg.ElasticsearchSettings.Password = *a.Config().ElasticsearchSettings.Password } else { return model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.reenter_password", nil, "", http.StatusBadRequest) } diff --git a/app/email.go b/app/email.go index 76597dea0..a96c7005c 100644 --- a/app/email.go +++ b/app/email.go @@ -139,9 +139,9 @@ func (a *App) SendWelcomeEmail(userId string, email string, verified bool, local bodyPage.Props["Info3"] = T("api.templates.welcome_body.info3") bodyPage.Props["SiteURL"] = siteURL - if *utils.Cfg.NativeAppSettings.AppDownloadLink != "" { + if *a.Config().NativeAppSettings.AppDownloadLink != "" { bodyPage.Props["AppDownloadInfo"] = T("api.templates.welcome_body.app_download_info") - bodyPage.Props["AppDownloadLink"] = *utils.Cfg.NativeAppSettings.AppDownloadLink + bodyPage.Props["AppDownloadLink"] = *a.Config().NativeAppSettings.AppDownloadLink } if !verified { diff --git a/app/email_batching.go b/app/email_batching.go index 4c546531f..75e09dd17 100644 --- a/app/email_batching.go +++ b/app/email_batching.go @@ -23,9 +23,9 @@ const ( ) func (a *App) InitEmailBatching() { - if *utils.Cfg.EmailSettings.EnableEmailBatching { + if *a.Config().EmailSettings.EnableEmailBatching { if a.EmailBatching == nil { - a.EmailBatching = NewEmailBatchingJob(a, *utils.Cfg.EmailSettings.EmailBatchingBufferSize) + a.EmailBatching = NewEmailBatchingJob(a, *a.Config().EmailSettings.EmailBatchingBufferSize) } // note that we don't support changing EmailBatchingBufferSize without restarting the server @@ -35,7 +35,7 @@ func (a *App) InitEmailBatching() { } func (a *App) AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError { - if !*utils.Cfg.EmailSettings.EnableEmailBatching { + if !*a.Config().EmailSettings.EnableEmailBatching { return model.NewAppError("AddNotificationEmailToBatch", "api.email_batching.add_notification_email_to_batch.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -197,7 +197,7 @@ func (a *App) sendBatchedEmailNotification(userId string, notifications []*batch } translateFunc := utils.GetUserTranslations(user.Locale) - displayNameFormat := *utils.Cfg.TeamSettings.TeammateNameDisplay + displayNameFormat := *a.Config().TeamSettings.TeammateNameDisplay var contents string for _, notification := range notifications { @@ -221,23 +221,23 @@ func (a *App) sendBatchedEmailNotification(userId string, notifications []*batch emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL if utils.IsLicensed() && *utils.License().Features.EmailNotificationContents { - emailNotificationContentsType = *utils.Cfg.EmailSettings.EmailNotificationContentsType + emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType } - contents += a.renderBatchedPost(notification, channel, sender, *utils.Cfg.ServiceSettings.SiteURL, displayNameFormat, translateFunc, user.Locale, emailNotificationContentsType) + contents += a.renderBatchedPost(notification, channel, sender, *a.Config().ServiceSettings.SiteURL, displayNameFormat, translateFunc, user.Locale, emailNotificationContentsType) } tm := time.Unix(notifications[0].post.CreateAt/1000, 0) subject := translateFunc("api.email_batching.send_batched_email_notification.subject", len(notifications), map[string]interface{}{ - "SiteName": utils.Cfg.TeamSettings.SiteName, + "SiteName": a.Config().TeamSettings.SiteName, "Year": tm.Year(), "Month": translateFunc(tm.Month().String()), "Day": tm.Day(), }) body := utils.NewHTMLTemplate("post_batched_body", user.Locale) - body.Props["SiteURL"] = *utils.Cfg.ServiceSettings.SiteURL + body.Props["SiteURL"] = *a.Config().ServiceSettings.SiteURL body.Props["Posts"] = template.HTML(contents) body.Props["BodyText"] = translateFunc("api.email_batching.send_batched_email_notification.body_text", len(notifications)) diff --git a/app/emoji.go b/app/emoji.go index 308791aed..ba2bb4494 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -137,11 +137,11 @@ func (a *App) DeleteEmoji(emoji *model.Emoji) *model.AppError { } func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { + if !*a.Config().ServiceSettings.EnableCustomEmoji { return nil, model.NewAppError("deleteEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*a.Config().FileSettings.DriverName) == 0 { return nil, model.NewAppError("deleteImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/file.go b/app/file.go index 2beb7231a..11e503c40 100644 --- a/app/file.go +++ b/app/file.go @@ -244,7 +244,7 @@ func GeneratePublicLinkHash(fileId, salt string) string { } func (a *App) UploadFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string) (*model.FileUploadResponse, *model.AppError) { - if len(*utils.Cfg.FileSettings.DriverName) == 0 { + if len(*a.Config().FileSettings.DriverName) == 0 { return nil, model.NewAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/import.go b/app/import.go index f7f9cf144..217e924b4 100644 --- a/app/import.go +++ b/app/import.go @@ -558,8 +558,8 @@ func (a *App) ImportUser(data *UserImportData, dryRun bool) *model.AppError { hasUserChanged = true } } else { - if user.Locale != *utils.Cfg.LocalizationSettings.DefaultClientLocale { - user.Locale = *utils.Cfg.LocalizationSettings.DefaultClientLocale + if user.Locale != *a.Config().LocalizationSettings.DefaultClientLocale { + user.Locale = *a.Config().LocalizationSettings.DefaultClientLocale hasUserChanged = true } } diff --git a/app/ldap.go b/app/ldap.go index 119587866..f1d46f824 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -13,7 +13,7 @@ import ( func (a *App) SyncLdap() { a.Go(func() { - if utils.IsLicensed() && *utils.License().Features.LDAP && *utils.Cfg.LdapSettings.Enable { + if utils.IsLicensed() && *utils.License().Features.LDAP && *a.Config().LdapSettings.Enable { if ldapI := a.Ldap; ldapI != nil { ldapI.StartSynchronizeJob(false) } else { @@ -24,7 +24,7 @@ func (a *App) SyncLdap() { } func (a *App) TestLdap() *model.AppError { - if ldapI := a.Ldap; ldapI != nil && utils.IsLicensed() && *utils.License().Features.LDAP && *utils.Cfg.LdapSettings.Enable { + if ldapI := a.Ldap; ldapI != nil && utils.IsLicensed() && *utils.License().Features.LDAP && *a.Config().LdapSettings.Enable { if err := ldapI.RunTest(); err != nil { err.StatusCode = 500 return err diff --git a/app/login.go b/app/login.go index 18b26c55c..ecc0f0163 100644 --- a/app/login.go +++ b/app/login.go @@ -10,7 +10,6 @@ import ( "time" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" "github.com/mssola/user_agent" ) @@ -58,10 +57,10 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) (*model.Session, *model.AppError) { session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceId, IsOAuth: false} - maxAge := *utils.Cfg.ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24 + maxAge := *a.Config().ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24 if len(deviceId) > 0 { - session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthMobileInDays) + session.SetExpireInDays(*a.Config().ServiceSettings.SessionLengthMobileInDays) // A special case where we logout of all other sessions with the same Id if err := a.RevokeSessionsForDeviceId(user.Id, deviceId, ""); err != nil { @@ -69,7 +68,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, return nil, err } } else { - session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthWebInDays) + session.SetExpireInDays(*a.Config().ServiceSettings.SessionLengthWebInDays) } ua := user_agent.New(r.UserAgent()) diff --git a/app/notification.go b/app/notification.go index 2a8f9ff2e..e11218faa 100644 --- a/app/notification.go +++ b/app/notification.go @@ -149,7 +149,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod senderUsername = sender.Username } - if utils.Cfg.EmailSettings.SendEmailNotifications { + if a.Config().EmailSettings.SendEmailNotifications { for _, id := range mentionedUsersList { userAllowsEmails := profileMap[id].NotifyProps[model.EMAIL_NOTIFY_PROP] != "false" if channelEmail, ok := channelMemberNotifyPropsMap[id][model.EMAIL_NOTIFY_PROP]; ok { @@ -159,7 +159,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } //If email verification is required and user email is not verified don't send email. - if utils.Cfg.EmailSettings.RequireEmailVerification && !profileMap[id].EmailVerified { + if a.Config().EmailSettings.RequireEmailVerification && !profileMap[id].EmailVerified { l4g.Error("Skipped sending notification email to %v, address not verified. [details: user_id=%v]", profileMap[id].Email, id) continue } @@ -185,37 +185,37 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod T := utils.GetUserTranslations(sender.Locale) // If the channel has more than 1K users then @here is disabled - if hereNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel { + if hereNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { hereNotification = false a.SendEphemeralPost( post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_here", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_here", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) } // If the channel has more than 1K users then @channel is disabled - if channelNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel { + if channelNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { a.SendEphemeralPost( post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_channel", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_channel", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) } // If the channel has more than 1K users then @all is disabled - if allNotification && int64(len(profileMap)) > *utils.Cfg.TeamSettings.MaxNotificationsPerChannel { + if allNotification && int64(len(profileMap)) > *a.Config().TeamSettings.MaxNotificationsPerChannel { a.SendEphemeralPost( post.UserId, &model.Post{ ChannelId: post.ChannelId, - Message: T("api.post.disabled_all", map[string]interface{}{"Users": *utils.Cfg.TeamSettings.MaxNotificationsPerChannel}), + Message: T("api.post.disabled_all", map[string]interface{}{"Users": *a.Config().TeamSettings.MaxNotificationsPerChannel}), CreateAt: post.CreateAt + 1, }, ) @@ -231,8 +231,8 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } sendPushNotifications := false - if *utils.Cfg.EmailSettings.SendPushNotifications { - pushServer := *utils.Cfg.EmailSettings.PushNotificationServer + if *a.Config().EmailSettings.SendPushNotifications { + pushServer := *a.Config().EmailSettings.PushNotificationServer if pushServer == model.MHPNS && (!utils.IsLicensed() || !*utils.License().Features.MHPNS) { l4g.Warn(utils.T("api.post.send_notifications_and_forget.push_notification.mhpnsWarn")) sendPushNotifications = false @@ -323,11 +323,11 @@ func (a *App) sendNotificationEmail(post *model.Post, user *model.User, channel team = teams[0] } else { // in case the user hasn't joined any teams we send them to the select_team page - team = &model.Team{Name: "select_team", DisplayName: utils.Cfg.TeamSettings.SiteName} + team = &model.Team{Name: "select_team", DisplayName: a.Config().TeamSettings.SiteName} } } } - if *utils.Cfg.EmailSettings.EnableEmailBatching { + if *a.Config().EmailSettings.EnableEmailBatching { var sendBatched bool if result := <-a.Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); result.Err != nil { // if the call fails, assume that the interval has not been explicitly set and batch the notifications @@ -350,14 +350,14 @@ func (a *App) sendNotificationEmail(post *model.Post, user *model.User, channel var subjectText string if channel.Type == model.CHANNEL_DIRECT { - subjectText = getDirectMessageNotificationEmailSubject(post, translateFunc, utils.Cfg.TeamSettings.SiteName, senderName) + subjectText = getDirectMessageNotificationEmailSubject(post, translateFunc, a.Config().TeamSettings.SiteName, senderName) } else { - subjectText = getNotificationEmailSubject(post, translateFunc, utils.Cfg.TeamSettings.SiteName, team.DisplayName) + subjectText = getNotificationEmailSubject(post, translateFunc, a.Config().TeamSettings.SiteName, team.DisplayName) } emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL if utils.IsLicensed() && *utils.License().Features.EmailNotificationContents { - emailNotificationContentsType = *utils.Cfg.EmailSettings.EmailNotificationContentsType + emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType } teamURL := utils.GetSiteURL() + "/" + team.Name @@ -594,14 +594,14 @@ func (a *App) sendPushNotification(post *model.Post, user *model.User, channel * msg.FromWebhook = fw.(string) } - if *utils.Cfg.EmailSettings.PushNotificationContents == model.FULL_NOTIFICATION { + if *a.Config().EmailSettings.PushNotificationContents == model.FULL_NOTIFICATION { msg.Category = model.CATEGORY_CAN_REPLY if channel.Type == model.CHANNEL_DIRECT { msg.Message = senderName + ": " + model.ClearMentionTags(post.Message) } else { msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_in") + channelName + ": " + model.ClearMentionTags(post.Message) } - } else if *utils.Cfg.EmailSettings.PushNotificationContents == model.GENERIC_NO_CHANNEL_NOTIFICATION { + } else if *a.Config().EmailSettings.PushNotificationContents == model.GENERIC_NO_CHANNEL_NOTIFICATION { if channel.Type == model.CHANNEL_DIRECT { msg.Category = model.CATEGORY_CAN_REPLY msg.Message = senderName + userLocale("api.post.send_notifications_and_forget.push_message") @@ -693,7 +693,7 @@ func (a *App) ClearPushNotification(userId string, channelId string) { func (a *App) sendToPushProxy(msg model.PushNotification, session *model.Session) { msg.ServerId = utils.CfgDiagnosticId - request, _ := http.NewRequest("POST", *utils.Cfg.EmailSettings.PushNotificationServer+model.API_URL_SUFFIX_V1+"/send_push", strings.NewReader(msg.ToJson())) + request, _ := http.NewRequest("POST", *a.Config().EmailSettings.PushNotificationServer+model.API_URL_SUFFIX_V1+"/send_push", strings.NewReader(msg.ToJson())) if resp, err := utils.HttpClient(true).Do(request); err != nil { l4g.Error("Device push reported as error for UserId=%v SessionId=%v message=%v", session.UserId, session.Id, err.Error()) diff --git a/app/oauth.go b/app/oauth.go index 5a02f6238..83e9390c5 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -25,7 +25,7 @@ const ( ) func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("CreateOAuthApp", "api.oauth.register_oauth_app.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -40,7 +40,7 @@ func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppEr } func (a *App) GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -52,7 +52,7 @@ func (a *App) GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) { } func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("UpdateOauthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -69,7 +69,7 @@ func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthAp } func (a *App) DeleteOAuthApp(appId string) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return model.NewAppError("DeleteOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -83,7 +83,7 @@ func (a *App) DeleteOAuthApp(appId string) *model.AppError { } func (a *App) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthApps", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -95,7 +95,7 @@ func (a *App) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppErro } func (a *App) GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthAppsByUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -107,7 +107,7 @@ func (a *App) GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model. } func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -153,7 +153,7 @@ func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.Author } func (a *App) GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -234,7 +234,7 @@ func (a *App) GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret AccessToken: session.Token, TokenType: model.ACCESS_TOKEN_TYPE, RefreshToken: accessData.RefreshToken, - ExpiresIn: int32(*utils.Cfg.ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), + ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), } } @@ -266,7 +266,7 @@ func (a *App) GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret func (a *App) newSession(appName string, user *model.User) (*model.Session, *model.AppError) { // set new token an session session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true} - session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthSSOInDays) + session.SetExpireInDays(*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") @@ -302,7 +302,7 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData AccessToken: session.Token, RefreshToken: accessData.RefreshToken, TokenType: model.ACCESS_TOKEN_TYPE, - ExpiresIn: int32(*utils.Cfg.ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), + ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24), } return accessRsp, nil @@ -341,7 +341,7 @@ func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, ser } func (a *App) GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetAuthorizedAppsForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -359,7 +359,7 @@ func (a *App) GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*mod } func (a *App) DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return model.NewAppError("DeauthorizeOAuthAppForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -389,7 +389,7 @@ func (a *App) DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { } func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { + if !a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("RegenerateOAuthAppSecret", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -563,7 +563,7 @@ func generateOAuthStateTokenExtra(email, action, cookie string) string { } func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { - sso := utils.Cfg.GetSSOService(service) + sso := a.Config().GetSSOService(service) if sso != nil && !sso.Enable { return "", model.NewAppError("GetAuthorizationCode", "api.user.get_authorization_code.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented) } @@ -616,7 +616,7 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi } func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.AppError) { - sso := utils.Cfg.GetSSOService(service) + sso := a.Config().GetSSOService(service) if sso == nil || !sso.Enable { return nil, "", nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented) } diff --git a/app/options.go b/app/options.go index 121bbbf80..34fa92d93 100644 --- a/app/options.go +++ b/app/options.go @@ -4,39 +4,11 @@ package app import ( - "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/store" ) type Option func(a *App) -// By default, the app will use a global configuration file. This allows you to override all or part -// of that configuration. -// -// The override parameter must be a *model.Config, func(*model.Config), or func(*model.Config) *model.Config. -// -// XXX: Most code will not respect this at the moment. (We need to eliminate utils.Cfg first.) -func ConfigOverride(override interface{}) Option { - return func(a *App) { - switch o := override.(type) { - case *model.Config: - a.configOverride = func(*model.Config) *model.Config { - return o - } - case func(*model.Config): - a.configOverride = func(cfg *model.Config) *model.Config { - ret := *cfg - o(&ret) - return &ret - } - case func(*model.Config) *model.Config: - a.configOverride = o - default: - panic("invalid ConfigOverride") - } - } -} - // By default, the app will use the store specified by the configuration. This allows you to // construct an app with a different store. // diff --git a/app/plugins.go b/app/plugins.go index 9826674f1..ca3fe610c 100644 --- a/app/plugins.go +++ b/app/plugins.go @@ -295,7 +295,7 @@ func (a *App) ActivatePlugins() { } func (a *App) UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *model.AppError) { - if a.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { + if a.PluginEnv == nil || !*a.Config().PluginSettings.Enable { return nil, model.NewAppError("UnpackAndActivatePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -346,7 +346,7 @@ func (a *App) UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *m } func (a *App) GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { - if a.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { + if a.PluginEnv == nil || !*a.Config().PluginSettings.Enable { return nil, model.NewAppError("GetActivePluginManifests", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -361,7 +361,7 @@ func (a *App) GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { } func (a *App) RemovePlugin(id string) *model.AppError { - if a.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { + if a.PluginEnv == nil || !*a.Config().PluginSettings.Enable { return model.NewAppError("RemovePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -394,7 +394,7 @@ func (a *App) RemovePlugin(id string) *model.AppError { } func (a *App) InitPlugins(pluginPath, webappPath string) { - if !utils.IsLicensed() || !*utils.License().Features.FutureFeatures || !*utils.Cfg.PluginSettings.Enable { + if !utils.IsLicensed() || !*utils.License().Features.FutureFeatures || !*a.Config().PluginSettings.Enable { return } diff --git a/app/post.go b/app/post.go index da5661ae2..f12866217 100644 --- a/app/post.go +++ b/app/post.go @@ -77,7 +77,7 @@ func (a *App) CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) l4g.Error(utils.T("api.post.create_post.last_viewed.error"), post.ChannelId, post.UserId, result.Err) } - if *utils.Cfg.ServiceSettings.EnableChannelViewedMessages { + if *a.Config().ServiceSettings.EnableChannelViewedMessages { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", post.UserId, nil) message.Add("channel_id", post.ChannelId) a.Go(func() { @@ -117,7 +117,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo user = result.Data.(*model.User) } - if utils.IsLicensed() && *utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly && + if utils.IsLicensed() && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && !post.IsSystemMessage() && channel.Name == model.DEFAULT_CHANNEL && !CheckIfRolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { @@ -158,7 +158,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo } esInterface := a.Elasticsearch - if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if esInterface != nil && *a.Config().ElasticsearchSettings.EnableIndexing { a.Go(func() { esInterface.IndexPost(rpost, channel.TeamId) }) @@ -280,7 +280,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model oldPost = result.Data.(*model.PostList).Posts[post.Id] if utils.IsLicensed() { - if *utils.Cfg.ServiceSettings.AllowEditPost == model.ALLOW_EDIT_POST_NEVER && post.Message != oldPost.Message { + if *a.Config().ServiceSettings.AllowEditPost == model.ALLOW_EDIT_POST_NEVER && post.Message != oldPost.Message { err := model.NewAppError("UpdatePost", "api.post.update_post.permissions_denied.app_error", nil, "", http.StatusForbidden) return nil, err } @@ -302,8 +302,8 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model } if utils.IsLicensed() { - if *utils.Cfg.ServiceSettings.AllowEditPost == model.ALLOW_EDIT_POST_TIME_LIMIT && model.GetMillis() > oldPost.CreateAt+int64(*utils.Cfg.ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message { - err := model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *utils.Cfg.ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) + if *a.Config().ServiceSettings.AllowEditPost == model.ALLOW_EDIT_POST_TIME_LIMIT && model.GetMillis() > oldPost.CreateAt+int64(*a.Config().ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message { + err := model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) return nil, err } } @@ -331,7 +331,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model rpost := result.Data.(*model.Post) esInterface := a.Elasticsearch - if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if esInterface != nil && *a.Config().ElasticsearchSettings.EnableIndexing { a.Go(func() { if rchannel := <-a.Srv.Store.Channel().GetForPost(rpost.Id); rchannel.Err != nil { l4g.Error("Couldn't get channel %v for post %v for Elasticsearch indexing.", rpost.ChannelId, rpost.Id) @@ -523,7 +523,7 @@ func (a *App) DeletePost(postId string) (*model.Post, *model.AppError) { }) esInterface := a.Elasticsearch - if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if esInterface != nil && *a.Config().ElasticsearchSettings.EnableIndexing { a.Go(func() { esInterface.DeletePost(post) }) @@ -556,7 +556,7 @@ func (a *App) SearchPostsInTeam(terms string, userId string, teamId string, isOr paramsList := model.ParseSearchParams(terms) esInterface := a.Elasticsearch - if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableSearching && utils.IsLicensed() && *utils.License().Features.Elasticsearch { + if esInterface != nil && *a.Config().ElasticsearchSettings.EnableSearching && utils.IsLicensed() && *utils.License().Features.Elasticsearch { finalParamsList := []*model.SearchParams{} for _, params := range paramsList { @@ -617,7 +617,7 @@ func (a *App) SearchPostsInTeam(terms string, userId string, teamId string, isOr return postList, nil } else { - if !*utils.Cfg.ServiceSettings.EnablePostSearch { + if !*a.Config().ServiceSettings.EnablePostSearch { return nil, model.NewAppError("SearchPostsInTeam", "store.sql_post.search.disabled", nil, fmt.Sprintf("teamId=%v userId=%v", teamId, userId), http.StatusNotImplemented) } diff --git a/app/post_test.go b/app/post_test.go index 5fa3d50d6..24910f964 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -106,10 +106,10 @@ func TestPostAction(t *testing.T) { UserId: th.BasicUser.Id, Props: model.StringInterface{ "attachments": []*model.SlackAttachment{ - &model.SlackAttachment{ + { Text: "hello", Actions: []*model.PostAction{ - &model.PostAction{ + { Integration: &model.PostActionIntegration{ Context: model.StringInterface{ "s": "foo", diff --git a/app/security_update_check.go b/app/security_update_check.go index 32d1f4d31..bac558c8c 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -31,7 +31,7 @@ const ( ) func (a *App) DoSecurityUpdateCheck() { - if *utils.Cfg.ServiceSettings.EnableSecurityFixAlert { + if *a.Config().ServiceSettings.EnableSecurityFixAlert { if result := <-a.Srv.Store.System().Get(); result.Err == nil { props := result.Data.(model.StringMap) lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0) @@ -45,7 +45,7 @@ func (a *App) DoSecurityUpdateCheck() { v.Set(PROP_SECURITY_ID, utils.CfgDiagnosticId) v.Set(PROP_SECURITY_BUILD, model.CurrentVersion+"."+model.BuildNumber) v.Set(PROP_SECURITY_ENTERPRISE_READY, model.BuildEnterpriseReady) - v.Set(PROP_SECURITY_DATABASE, *utils.Cfg.SqlSettings.DriverName) + v.Set(PROP_SECURITY_DATABASE, *a.Config().SqlSettings.DriverName) v.Set(PROP_SECURITY_OS, runtime.GOOS) if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 { diff --git a/app/server.go b/app/server.go index d686c1f24..f8dca6a4c 100644 --- a/app/server.go +++ b/app/server.go @@ -123,18 +123,18 @@ func (a *App) StartServer() { var handler http.Handler = &CorsWrapper{a.Srv.Router} - if *utils.Cfg.RateLimitSettings.Enable { + if *a.Config().RateLimitSettings.Enable { l4g.Info(utils.T("api.server.start_server.rate.info")) - store, err := memstore.New(*utils.Cfg.RateLimitSettings.MemoryStoreSize) + store, err := memstore.New(*a.Config().RateLimitSettings.MemoryStoreSize) if err != nil { l4g.Critical(utils.T("api.server.start_server.rate_limiting_memory_store")) return } quota := throttled.RateQuota{ - MaxRate: throttled.PerSec(*utils.Cfg.RateLimitSettings.PerSec), - MaxBurst: *utils.Cfg.RateLimitSettings.MaxBurst, + MaxRate: throttled.PerSec(*a.Config().RateLimitSettings.PerSec), + MaxBurst: *a.Config().RateLimitSettings.MaxBurst, } rateLimiter, err := throttled.NewGCRARateLimiter(store, quota) @@ -157,13 +157,13 @@ func (a *App) StartServer() { a.Srv.Server = &http.Server{ Handler: handlers.RecoveryHandler(handlers.RecoveryLogger(&RecoveryLogger{}), handlers.PrintRecoveryStack(true))(handler), - ReadTimeout: time.Duration(*utils.Cfg.ServiceSettings.ReadTimeout) * time.Second, - WriteTimeout: time.Duration(*utils.Cfg.ServiceSettings.WriteTimeout) * time.Second, + ReadTimeout: time.Duration(*a.Config().ServiceSettings.ReadTimeout) * time.Second, + WriteTimeout: time.Duration(*a.Config().ServiceSettings.WriteTimeout) * time.Second, } addr := *a.Config().ServiceSettings.ListenAddress if addr == "" { - if *utils.Cfg.ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { + if *a.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { addr = ":https" } else { addr = ":http" @@ -179,7 +179,7 @@ func (a *App) StartServer() { l4g.Info(utils.T("api.server.start_server.listening.info"), listener.Addr().String()) - if *utils.Cfg.ServiceSettings.Forward80To443 { + if *a.Config().ServiceSettings.Forward80To443 { go func() { redirectListener, err := net.Listen("tcp", ":80") if err != nil { @@ -196,10 +196,10 @@ func (a *App) StartServer() { a.Srv.didFinishListen = make(chan struct{}) go func() { var err error - if *utils.Cfg.ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { - if *utils.Cfg.ServiceSettings.UseLetsEncrypt { + if *a.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { + if *a.Config().ServiceSettings.UseLetsEncrypt { var m letsencrypt.Manager - m.CacheFile(*utils.Cfg.ServiceSettings.LetsEncryptCertificateCacheFile) + m.CacheFile(*a.Config().ServiceSettings.LetsEncryptCertificateCacheFile) tlsConfig := &tls.Config{ GetCertificate: m.GetCertificate, @@ -210,7 +210,7 @@ func (a *App) StartServer() { a.Srv.Server.TLSConfig = tlsConfig err = a.Srv.Server.ServeTLS(listener, "", "") } else { - err = a.Srv.Server.ServeTLS(listener, *utils.Cfg.ServiceSettings.TLSCertFile, *utils.Cfg.ServiceSettings.TLSKeyFile) + err = a.Srv.Server.ServeTLS(listener, *a.Config().ServiceSettings.TLSCertFile, *a.Config().ServiceSettings.TLSKeyFile) } } else { err = a.Srv.Server.Serve(listener) diff --git a/app/session.go b/app/session.go index be79b0266..f8b931043 100644 --- a/app/session.go +++ b/app/session.go @@ -71,12 +71,12 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, "", http.StatusUnauthorized) } - if *utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes > 0 && + if *a.Config().ServiceSettings.SessionIdleTimeoutInMinutes > 0 && utils.IsLicensed() && *utils.License().Features.Compliance && session != nil && !session.IsOAuth && !session.IsMobileApp() && session.Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_USER_ACCESS_TOKEN { - timeout := int64(*utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes) * 1000 * 60 + timeout := int64(*a.Config().ServiceSettings.SessionIdleTimeoutInMinutes) * 1000 * 60 if model.GetMillis()-session.LastActivityAt > timeout { a.RevokeSessionById(session.Id) return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, "idle timeout", http.StatusUnauthorized) @@ -231,7 +231,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { } func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens { + if !*a.Config().ServiceSettings.EnableUserAccessTokens { return nil, model.NewAppError("CreateUserAccessToken", "app.user_access_token.disabled", nil, "", http.StatusNotImplemented) } @@ -259,7 +259,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc } func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens { + if !*a.Config().ServiceSettings.EnableUserAccessTokens { return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "EnableUserAccessTokens=false", http.StatusUnauthorized) } diff --git a/app/status.go b/app/status.go index 3d4837cb0..56bad2105 100644 --- a/app/status.go +++ b/app/status.go @@ -57,7 +57,7 @@ func GetAllStatuses() map[string]*model.Status { } func (a *App) GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return map[string]interface{}{}, nil } @@ -104,7 +104,7 @@ func (a *App) GetStatusesByIds(userIds []string) (map[string]interface{}, *model //GetUserStatusesByIds used by apiV4 func (a *App) GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return []*model.Status{}, nil } @@ -161,7 +161,7 @@ func (a *App) GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.Ap } func (a *App) SetStatusOnline(userId string, sessionId string, manual bool) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return } @@ -227,7 +227,7 @@ func (a *App) BroadcastStatus(status *model.Status) { } func (a *App) SetStatusOffline(userId string, manual bool) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return } @@ -253,7 +253,7 @@ func (a *App) SetStatusOffline(userId string, manual bool) { } func (a *App) SetStatusAwayIfNeeded(userId string, manual bool) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return } @@ -307,7 +307,7 @@ func GetStatusFromCache(userId string) *model.Status { } func (a *App) GetStatus(userId string) (*model.Status, *model.AppError) { - if !*utils.Cfg.ServiceSettings.EnableUserStatuses { + if !*a.Config().ServiceSettings.EnableUserStatuses { return &model.Status{}, nil } diff --git a/app/team.go b/app/team.go index 1bc77c9f0..61d0f52b6 100644 --- a/app/team.go +++ b/app/team.go @@ -215,7 +215,7 @@ func (a *App) AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppE func (a *App) AddUserToTeamByHash(userId string, hash string, data string) (*model.Team, *model.AppError) { props := model.MapFromJson(strings.NewReader(data)) - if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) { + if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, a.Config().EmailSettings.InviteSalt)) { return nil, model.NewAppError("JoinUserToTeamByHash", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest) } @@ -674,7 +674,7 @@ func (a *App) InviteNewUsersToTeam(emailList []string, teamId, senderId string) user = result.Data.(*model.User) } - nameFormat := *utils.Cfg.TeamSettings.TeammateNameDisplay + nameFormat := *a.Config().TeamSettings.TeammateNameDisplay SendInviteEmails(team, user.GetDisplayName(nameFormat), emailList, utils.GetSiteURL()) return nil @@ -812,7 +812,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { data := query.Get("d") props := model.MapFromJson(strings.NewReader(data)) - if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) { + if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, a.Config().EmailSettings.InviteSalt)) { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) } diff --git a/app/user.go b/app/user.go index edb4961fc..f27e4e06f 100644 --- a/app/user.go +++ b/app/user.go @@ -45,7 +45,7 @@ func (a *App) CreateUserWithHash(user *model.User, hash string, data string) (*m props := model.MapFromJson(strings.NewReader(data)) - if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) { + if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, a.Config().EmailSettings.InviteSalt)) { return nil, model.NewAppError("CreateUserWithHash", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusInternalServerError) } @@ -131,7 +131,7 @@ func (a *App) CreateUserFromSignup(user *model.User) (*model.User, *model.AppErr return nil, err } - if !a.IsFirstUserAccount() && !*utils.Cfg.TeamSettings.EnableOpenServer { + if !a.IsFirstUserAccount() && !*a.Config().TeamSettings.EnableOpenServer { err := model.NewAppError("CreateUserFromSignup", "api.user.create_user.no_open_server", nil, "email="+user.Email, http.StatusForbidden) return nil, err } @@ -175,7 +175,7 @@ func (a *App) IsFirstUserAccount() bool { } func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { - if !user.IsLDAPUser() && !user.IsSAMLUser() && !CheckUserDomain(user, utils.Cfg.TeamSettings.RestrictCreationToDomains) { + if !user.IsLDAPUser() && !user.IsSAMLUser() && !CheckUserDomain(user, a.Config().TeamSettings.RestrictCreationToDomains) { return nil, model.NewAppError("CreateUser", "api.user.create_user.accepted_domain.app_error", nil, "", http.StatusBadRequest) } @@ -193,7 +193,7 @@ func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { } if _, ok := utils.GetSupportedLocales()[user.Locale]; !ok { - user.Locale = *utils.Cfg.LocalizationSettings.DefaultClientLocale + user.Locale = *a.Config().LocalizationSettings.DefaultClientLocale } if ruser, err := a.createUser(user); err != nil { @@ -241,7 +241,7 @@ func (a *App) createUser(user *model.User) (*model.User, *model.AppError) { } func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) { - if !utils.Cfg.TeamSettings.EnableUserCreation { + if !a.Config().TeamSettings.EnableUserCreation { return nil, model.NewAppError("CreateOAuthUser", "api.user.create_user.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -374,12 +374,12 @@ func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, } func (a *App) GetUserForLogin(loginId string, onlyLdap bool) (*model.User, *model.AppError) { - ldapAvailable := *utils.Cfg.LdapSettings.Enable && a.Ldap != nil && utils.IsLicensed() && *utils.License().Features.LDAP + ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap != nil && utils.IsLicensed() && *utils.License().Features.LDAP if result := <-a.Srv.Store.User().GetForLogin( loginId, - *utils.Cfg.EmailSettings.EnableSignInWithUsername && !onlyLdap, - *utils.Cfg.EmailSettings.EnableSignInWithEmail && !onlyLdap, + *a.Config().EmailSettings.EnableSignInWithUsername && !onlyLdap, + *a.Config().EmailSettings.EnableSignInWithEmail && !onlyLdap, ldapAvailable, ); result.Err != nil && result.Err.Id == "store.sql_user.get_for_login.multiple_users" { // don't fall back to LDAP in this case since we already know there's an LDAP user, but that it shouldn't work @@ -438,7 +438,7 @@ func (a *App) GetUsersPage(page int, perPage int, asAdmin bool) ([]*model.User, } func (a *App) GetUsersEtag() string { - return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForAllProfiles()).Data.(string), utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForAllProfiles()).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress) } func (a *App) GetUsersInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) { @@ -492,11 +492,11 @@ func (a *App) GetUsersNotInTeamPage(teamId string, page int, perPage int, asAdmi } func (a *App) GetUsersInTeamEtag(teamId string) string { - return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfiles(teamId)).Data.(string), utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfiles(teamId)).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress) } func (a *App) GetUsersNotInTeamEtag(teamId string) string { - return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfilesNotInTeam(teamId)).Data.(string), utils.Cfg.PrivacySettings.ShowFullName, utils.Cfg.PrivacySettings.ShowEmailAddress) + return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfilesNotInTeam(teamId)).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress) } func (a *App) GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) { @@ -823,7 +823,7 @@ func (a *App) SetProfileImage(userId string, imageData *multipart.FileHeader) *m if user, err := a.GetUser(userId); err != nil { l4g.Error(utils.T("api.user.get_me.getting.error"), userId) } else { - options := utils.Cfg.GetSanitizeOptions() + options := a.Config().GetSanitizeOptions() user.SanitizeProfile(options) omitUsers := make(map[string]bool, 1) @@ -908,7 +908,7 @@ func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.A } ruser := result.Data.([2]*model.User)[0] - options := utils.Cfg.GetSanitizeOptions() + options := a.Config().GetSanitizeOptions() options["passwordupdate"] = false ruser.Sanitize(options) @@ -1001,7 +1001,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, } }) - if utils.Cfg.EmailSettings.RequireEmailVerification { + if a.Config().EmailSettings.RequireEmailVerification { if err := a.SendEmailVerification(rusers[0]); err != nil { l4g.Error(err.Error()) } diff --git a/app/webhook.go b/app/webhook.go index 231fe1529..e8f9936f8 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -22,7 +22,7 @@ const ( ) func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil } @@ -140,7 +140,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove metrics.IncrementWebhookPost() } - if utils.Cfg.ServiceSettings.EnablePostUsernameOverride { + if a.Config().ServiceSettings.EnablePostUsernameOverride { if len(overrideUsername) != 0 { post.AddProp("override_username", overrideUsername) } else { @@ -148,7 +148,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove } } - if utils.Cfg.ServiceSettings.EnablePostIconOverride { + if a.Config().ServiceSettings.EnablePostIconOverride { if len(overrideIconUrl) != 0 { post.AddProp("override_icon_url", overrideIconUrl) } @@ -200,7 +200,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove } func (a *App) CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, hook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("CreateIncomingWebhookForChannel", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -215,7 +215,7 @@ func (a *App) CreateIncomingWebhookForChannel(creatorId string, channel *model.C } func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("UpdateIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -235,7 +235,7 @@ func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) } func (a *App) DeleteIncomingWebhook(hookId string) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return model.NewAppError("DeleteIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -249,7 +249,7 @@ func (a *App) DeleteIncomingWebhook(hookId string) *model.AppError { } func (a *App) GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -261,7 +261,7 @@ func (a *App) GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model. } func (a *App) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhooksForTeamPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -273,7 +273,7 @@ func (a *App) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ( } func (a *App) GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhooksPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -285,7 +285,7 @@ func (a *App) GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebho } func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("CreateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -333,7 +333,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -384,7 +384,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) } func (a *App) GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -396,7 +396,7 @@ func (a *App) GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model. } func (a *App) GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -408,7 +408,7 @@ func (a *App) GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebho } func (a *App) GetOutgoingWebhooksForChannelPage(channelId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksForChannelPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -420,7 +420,7 @@ func (a *App) GetOutgoingWebhooksForChannelPage(channelId string, page, perPage } func (a *App) GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksForTeamPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -432,7 +432,7 @@ func (a *App) GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ( } func (a *App) DeleteOutgoingWebhook(hookId string) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return model.NewAppError("DeleteOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -444,7 +444,7 @@ func (a *App) DeleteOutgoingWebhook(hookId string) *model.AppError { } func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { - if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { + if !a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("RegenOutgoingWebhookToken", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -458,7 +458,7 @@ func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.Out } func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *model.AppError { - if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { + if !a.Config().ServiceSettings.EnableIncomingWebhooks { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -531,7 +531,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq } } - if utils.IsLicensed() && *utils.Cfg.TeamSettings.ExperimentalTownSquareIsReadOnly && + if utils.IsLicensed() && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { return model.NewAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden) } diff --git a/app/webhook_test.go b/app/webhook_test.go index b9ba35f43..d6293e2b7 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -30,7 +30,7 @@ func TestCreateWebhookPost(t *testing.T) { post, err := th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", model.StringInterface{ "attachments": []*model.SlackAttachment{ - &model.SlackAttachment{ + { Text: "text", }, }, diff --git a/web/web_test.go b/web/web_test.go index 23b43ba93..fe2115f83 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -42,11 +42,11 @@ func Setup() *app.App { utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) - a := app.New(app.StoreOverride(testStore), app.ConfigOverride(func(cfg *model.Config) { - cfg.ServiceSettings.ListenAddress = new(string) - *cfg.ServiceSettings.ListenAddress = ":0" - })) + a := app.New(app.StoreOverride(testStore)) + prevListenAddress := *a.Config().ServiceSettings.ListenAddress + a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) a.StartServer() + a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) api4.Init(a, a.Srv.Router, false) api3 := api.Init(a, a.Srv.Router) Init(api3) -- cgit v1.2.3-1-g7c22