From 17523fa5d956d655ffde1e2e3642a1510cc54235 Mon Sep 17 00:00:00 2001 From: Eli Yukelzon Date: Thu, 13 Feb 2020 13:26:58 +0100 Subject: [PATCH] =?UTF-8?q?MM-21898=20-=20Part=201:=20Generate=20and=20use?= =?UTF-8?q?=20an=20interface=20instead=20of=20*A=E2=80=A6=20(#13840)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Generate and use an interface instead of *App --- .gitignore | 2 + Makefile | 4 + api4/apitestlib.go | 34 +- api4/bot.go | 30 +- api4/brand.go | 4 +- api4/channel.go | 166 +-- api4/channel_test.go | 2 +- api4/cluster.go | 2 +- api4/command.go | 44 +- api4/compliance.go | 10 +- api4/config.go | 12 +- api4/cors_test.go | 2 +- api4/elasticsearch.go | 4 +- api4/emoji.go | 20 +- api4/file.go | 22 +- api4/file_test.go | 12 +- api4/group.go | 22 +- api4/image.go | 2 +- api4/integration_action.go | 12 +- api4/job.go | 10 +- api4/job_test.go | 18 +- api4/ldap.go | 10 +- api4/license.go | 6 +- api4/oauth.go | 34 +- api4/plugin.go | 18 +- api4/post.go | 72 +- api4/post_test.go | 36 +- api4/preference.go | 12 +- api4/reaction.go | 12 +- api4/reaction_test.go | 4 +- api4/role.go | 2 +- api4/role_test.go | 28 +- api4/saml.go | 16 +- api4/scheme.go | 14 +- api4/scheme_test.go | 16 +- api4/status.go | 2 +- api4/system.go | 50 +- api4/system_test.go | 22 +- api4/team.go | 136 +- api4/team_test.go | 10 +- api4/terms_of_service.go | 4 +- api4/user.go | 176 +-- api4/user_test.go | 30 +- api4/webhook.go | 74 +- api4/websocket.go | 4 +- api4/websocket_test.go | 10 +- app/admin.go | 42 +- app/analytics.go | 54 +- app/app.go | 179 ++- app/app_iface.go | 834 ++++++++++++ app/audit.go | 4 +- app/authentication.go | 18 +- app/authorization.go | 12 +- app/auto_users.go | 8 +- app/bot.go | 42 +- app/channel.go | 260 ++-- app/channel_test.go | 32 +- app/cluster_discovery.go | 20 +- app/cluster_handlers.go | 24 +- app/command.go | 30 +- app/command_echo.go | 2 +- app/command_expand_collapse.go | 2 +- app/command_groupmsg.go | 2 +- app/command_invite.go | 2 +- app/command_join.go | 2 +- app/command_loadtest.go | 10 +- app/command_msg.go | 4 +- app/command_mute.go | 4 +- app/command_remove.go | 2 +- app/command_test.go | 4 +- app/compliance.go | 14 +- app/config.go | 76 +- app/config_test.go | 8 +- app/data_retention.go | 4 +- app/diagnostics.go | 64 +- app/download.go | 2 +- app/elasticsearch.go | 4 +- app/email.go | 30 +- app/email_batching.go | 2 +- app/email_batching_test.go | 20 +- app/emoji.go | 22 +- app/enterprise_test.go | 6 +- app/export.go | 24 +- app/export_test.go | 36 +- app/file.go | 68 +- app/file.go.orig | 1139 +++++++++++++++++ app/file_bench_test.go | 14 +- app/file_test.go | 14 +- app/group.go | 76 +- app/helper_test.go | 12 +- app/import.go | 4 +- app/import_functions.go | 76 +- app/import_functions_test.go | 168 +-- app/import_test.go | 10 +- app/integration_action.go | 20 +- app/integration_action_test.go | 2 +- app/job.go | 10 +- app/job_test.go | 8 +- app/layer_generators/app_iface.go.tmpl | 12 + app/ldap.go | 22 +- app/license.go | 42 +- app/login.go | 22 +- app/migrations.go | 46 +- app/notification.go | 16 +- app/notification_email.go | 14 +- app/notification_push.go | 44 +- app/oauth.go | 76 +- app/oauth_test.go | 6 +- app/opengraph.go | 2 +- app/options.go | 35 +- app/permissions.go | 16 +- app/permissions_migrations.go | 6 +- app/permissions_test.go | 6 +- app/plugin.go | 66 +- app/plugin_api.go | 6 +- app/plugin_api_test.go | 10 +- app/plugin_commands.go | 36 +- app/plugin_context.go | 10 +- app/plugin_event.go | 4 +- app/plugin_hooks_test.go | 28 +- app/plugin_key_value_store.go | 24 +- app/plugin_requests.go | 12 +- app/plugin_signature.go | 6 +- app/plugin_statuses.go | 4 +- app/plugin_test.go | 2 +- app/post.go | 128 +- app/post_metadata.go | 8 +- app/post_test.go | 20 +- app/preference.go | 10 +- app/reaction.go | 12 +- app/role.go | 14 +- app/saml.go | 20 +- app/scheme.go | 24 +- app/server.go | 2 +- app/server_app_adapters.go | 34 +- app/session.go | 90 +- app/session_test.go | 18 +- app/slack.go | 2 +- app/slackimport.go | 20 +- app/status.go | 32 +- app/syncables.go | 22 +- app/syncables_test.go | 4 +- app/team.go | 170 +-- app/team_test.go | 48 +- app/terms_of_service.go | 6 +- app/user.go | 228 ++-- app/user_terms_of_service.go | 6 +- app/user_test.go | 28 +- app/web_conn.go | 14 +- app/web_hub.go | 84 +- app/web_hub_test.go | 2 +- app/webhook.go | 64 +- app/webhook_test.go | 4 +- app/websocket_router.go | 2 +- cmd/mattermost/commands/channel.go | 12 +- cmd/mattermost/commands/channel_test.go | 4 +- cmd/mattermost/commands/channelargs.go | 4 +- cmd/mattermost/commands/command.go | 2 +- cmd/mattermost/commands/commandargs.go | 4 +- cmd/mattermost/commands/export.go | 6 +- cmd/mattermost/commands/integrity.go | 2 +- cmd/mattermost/commands/jobserver.go | 8 +- cmd/mattermost/commands/ldap.go | 4 +- cmd/mattermost/commands/reset.go | 2 +- cmd/mattermost/commands/roles_test.go | 4 +- cmd/mattermost/commands/team_test.go | 2 +- cmd/mattermost/commands/teamargs.go | 4 +- cmd/mattermost/commands/test.go | 12 +- cmd/mattermost/commands/user.go | 10 +- cmd/mattermost/commands/user_test.go | 26 +- cmd/mattermost/commands/userargs.go | 6 +- cmd/mattermost/commands/version.go | 2 +- cmd/mattermost/commands/webhook.go | 4 +- go.mod | 6 +- go.sum | 11 +- manualtesting/manual_testing.go | 10 +- migrations/advanced_permissions_phase_2.go | 4 +- migrations/helper_test.go | 6 +- migrations/migrations_test.go | 20 +- migrations/scheduler.go | 10 +- migrations/worker.go | 14 +- plugin/interface_generator/main.go | 2 +- plugin/scheduler/scheduler.go | 2 +- plugin/scheduler/worker.go | 6 +- vendor/golang.org/x/tools/go/analysis/doc.go | 2 +- .../go/internal/gcimporter/gcimporter.go | 8 +- .../golang.org/x/tools/go/packages/golist.go | 79 +- .../x/tools/go/packages/golist_overlay.go | 27 +- vendor/modules.txt | 2 +- web/context.go | 34 +- web/handlers.go | 50 +- web/handlers_test.go | 4 +- web/oauth.go | 12 +- web/oauth_test.go | 4 +- web/saml.go | 8 +- web/unsupported_browser.go | 14 +- web/web.go | 2 +- web/web_test.go | 8 +- web/webhook.go | 2 +- wsapi/user.go | 2 +- 200 files changed, 4553 insertions(+), 2361 deletions(-) create mode 100644 app/app_iface.go create mode 100644 app/file.go.orig create mode 100644 app/layer_generators/app_iface.go.tmpl diff --git a/.gitignore b/.gitignore index d41ca31b5d..76c5d46c1d 100644 --- a/.gitignore +++ b/.gitignore @@ -101,3 +101,5 @@ tags debug client +__debug_bin +report.xml diff --git a/Makefile b/Makefile index 25f0e8e23a..d897e5e6b3 100644 --- a/Makefile +++ b/Makefile @@ -202,6 +202,10 @@ ifneq ($(MM_NO_ENTERPRISE_LINT),true) endif endif +app-layers: ## Extract interface from App struct + env GO111MODULE=off $(GO) get -u github.com/reflog/struct2interface + $(GOBIN)/struct2interface -f "app" -o "app/app_iface.go" -p "app" -s "App" -i "AppIface" -t ./app/layer_generators/app_iface.go.tmpl + i18n-extract: ## Extract strings for translation from the source code env GO111MODULE=off $(GO) get -u github.com/mattermost/mattermost-utilities/mmgotool $(GOBIN)/mmgotool i18n extract diff --git a/api4/apitestlib.go b/api4/apitestlib.go index f37e4c8949..2d681c5515 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -114,10 +114,10 @@ func setupTestHelper(enterprise bool, updateConfig func(*model.Config)) *TestHel } th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) - Init(th.Server, th.Server.AppOptions, th.App.Srv.Router) - web.New(th.Server, th.Server.AppOptions, th.App.Srv.Router) - wsapi.Init(th.App, th.App.Srv.WebSocketRouter) - th.App.Srv.Store.MarkSystemRanUnitTests() + Init(th.Server, th.Server.AppOptions, th.App.Srv().Router) + web.New(th.Server, th.Server.AppOptions, th.App.Srv().Router) + wsapi.Init(th.App, th.App.Srv().WebSocketRouter) + th.App.Srv().Store.MarkSystemRanUnitTests() th.App.DoAppMigrations() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -227,7 +227,7 @@ func (me *TestHelper) InitBasic() *TestHelper { func (me *TestHelper) waitForConnectivity() { for i := 0; i < 1000; i++ { - conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", me.App.Srv.ListenAddr.Port)) + conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", me.App.Srv().ListenAddr.Port)) if err == nil { conn.Close() return @@ -238,19 +238,19 @@ func (me *TestHelper) waitForConnectivity() { } func (me *TestHelper) CreateClient() *model.Client4 { - return model.NewAPIv4Client(fmt.Sprintf("http://localhost:%v", me.App.Srv.ListenAddr.Port)) + return model.NewAPIv4Client(fmt.Sprintf("http://localhost:%v", me.App.Srv().ListenAddr.Port)) } func (me *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, *model.AppError) { - return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), me.Client.AuthToken) + return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv().ListenAddr.Port), me.Client.AuthToken) } func (me *TestHelper) CreateWebSocketSystemAdminClient() (*model.WebSocketClient, *model.AppError) { - return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), me.SystemAdminClient.AuthToken) + return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv().ListenAddr.Port), me.SystemAdminClient.AuthToken) } func (me *TestHelper) CreateWebSocketClientWithClient(client *model.Client4) (*model.WebSocketClient, *model.AppError) { - return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), client.AuthToken) + return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv().ListenAddr.Port), client.AuthToken) } func (me *TestHelper) CreateBotWithSystemAdminClient() *model.Bot { @@ -318,7 +318,7 @@ func (me *TestHelper) CreateUserWithClient(client *model.Client4) *model.User { } ruser.Password = "Pa$$word11" - _, err := me.App.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err := me.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return nil } @@ -420,7 +420,7 @@ func (me *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel } func (me *TestHelper) CreateMessagePostNoClient(channel *model.Channel, message string, createAtTime int64) *model.Post { - post, err := me.App.Srv.Store.Post().Save(&model.Post{ + post, err := me.App.Srv().Store.Post().Save(&model.Post{ UserId: me.BasicUser.Id, ChannelId: channel.Id, Message: message, @@ -751,9 +751,9 @@ func (me *TestHelper) cleanupTestFile(info *model.FileInfo) error { func (me *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Channel) { utils.DisableDebugLogForTest() - if cm, err := me.App.Srv.Store.Channel().GetMember(channel.Id, user.Id); err == nil { + if cm, err := me.App.Srv().Store.Channel().GetMember(channel.Id, user.Id); err == nil { cm.SchemeAdmin = true - if _, err = me.App.Srv.Store.Channel().UpdateMember(cm); err != nil { + if _, err = me.App.Srv().Store.Channel().UpdateMember(cm); err != nil { utils.EnableDebugLogForTest() panic(err) } @@ -768,9 +768,9 @@ func (me *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Chan func (me *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - if tm, err := me.App.Srv.Store.Team().GetMember(team.Id, user.Id); err == nil { + if tm, err := me.App.Srv().Store.Team().GetMember(team.Id, user.Id); err == nil { tm.SchemeAdmin = true - if _, err = me.App.Srv.Store.Team().UpdateMember(tm); err != nil { + if _, err = me.App.Srv().Store.Team().UpdateMember(tm); err != nil { utils.EnableDebugLogForTest() panic(err) } @@ -788,9 +788,9 @@ func (me *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) func (me *TestHelper) UpdateUserToNonTeamAdmin(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - if tm, err := me.App.Srv.Store.Team().GetMember(team.Id, user.Id); err == nil { + if tm, err := me.App.Srv().Store.Team().GetMember(team.Id, user.Id); err == nil { tm.SchemeAdmin = false - if _, err = me.App.Srv.Store.Team().UpdateMember(tm); err != nil { + if _, err = me.App.Srv().Store.Team().UpdateMember(tm); err != nil { utils.EnableDebugLogForTest() panic(err) } diff --git a/api4/bot.go b/api4/bot.go index 3d599ef1ba..2ccf17b6ee 100644 --- a/api4/bot.go +++ b/api4/bot.go @@ -35,16 +35,16 @@ func createBot(c *Context, w http.ResponseWriter, r *http.Request) { } bot := &model.Bot{ - OwnerId: c.App.Session.UserId, + OwnerId: c.App.Session().UserId, } bot.Patch(botPatch) - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_BOT) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_BOT) { c.SetPermissionError(model.PERMISSION_CREATE_BOT) return } - if user, err := c.App.GetUser(c.App.Session.UserId); err == nil { + if user, err := c.App.GetUser(c.App.Session().UserId); err == nil { if user.IsBot { c.SetPermissionError(model.PERMISSION_CREATE_BOT) return @@ -79,7 +79,7 @@ func patchBot(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { c.Err = err return } @@ -108,10 +108,10 @@ func getBot(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_OTHERS_BOTS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_OTHERS_BOTS) { // Allow access to any bot. - } else if bot.OwnerId == c.App.Session.UserId { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_BOTS) { + } else if bot.OwnerId == c.App.Session().UserId { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_BOTS) { // Pretend like the bot doesn't exist at all to avoid revealing that the // user is a bot. It's kind of silly in this case, sine we created the bot, // but we don't have read bot permissions. @@ -137,12 +137,12 @@ func getBots(c *Context, w http.ResponseWriter, r *http.Request) { onlyOrphaned := r.URL.Query().Get("only_orphaned") == "true" var OwnerId string - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_OTHERS_BOTS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_OTHERS_BOTS) { // Get bots created by any user. OwnerId = "" - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_BOTS) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_BOTS) { // Only get bots created by this user. - OwnerId = c.App.Session.UserId + OwnerId = c.App.Session().UserId } else { c.SetPermissionError(model.PERMISSION_READ_BOTS) return @@ -182,7 +182,7 @@ func updateBotActive(c *Context, w http.ResponseWriter, r *http.Request, active } botUserId := c.Params.BotUserId - if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { c.Err = err return } @@ -205,7 +205,7 @@ func assignBot(c *Context, w http.ResponseWriter, r *http.Request) { botUserId := c.Params.BotUserId userId := c.Params.UserId - if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { c.Err = err return } @@ -233,7 +233,7 @@ func getBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { } botUserId := c.Params.BotUserId - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, botUserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, botUserId) if err != nil { c.Err = err return @@ -276,7 +276,7 @@ func setBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { } botUserId := c.Params.BotUserId - if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { c.Err = err return } @@ -322,7 +322,7 @@ func deleteBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { } botUserId := c.Params.BotUserId - if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { c.Err = err return } diff --git a/api4/brand.go b/api4/brand.go index cd7ef48fba..f636d6a273 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -57,7 +57,7 @@ func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -74,7 +74,7 @@ func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { } func deleteBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/channel.go b/api4/channel.go index 1688753294..8e02fa9324 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -66,17 +66,17 @@ func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_CREATE_PUBLIC_CHANNEL) { + if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_CREATE_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_CREATE_PUBLIC_CHANNEL) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_CREATE_PRIVATE_CHANNEL) { + if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_CREATE_PRIVATE_CHANNEL) { c.SetPermissionError(model.PERMISSION_CREATE_PRIVATE_CHANNEL) return } - sc, err := c.App.CreateChannelWithUser(channel, c.App.Session.UserId) + sc, err := c.App.CreateChannelWithUser(channel, c.App.Session().UserId) if err != nil { c.Err = err return @@ -115,20 +115,20 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { switch oldChannel.Type { case model.CHANNEL_OPEN: - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) return } case model.CHANNEL_PRIVATE: - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) return } case model.CHANNEL_GROUP, model.CHANNEL_DIRECT: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. - if _, err := c.App.GetChannelMember(channel.Id, c.App.Session.UserId); err != nil { + if _, err := c.App.GetChannelMember(channel.Id, c.App.Session().UserId); err != nil { c.Err = model.NewAppError("updateChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -178,7 +178,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if oldChannelDisplayName != channel.DisplayName { - if err := c.App.PostUpdateChannelDisplayNameMessage(c.App.Session.UserId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { + if err := c.App.PostUpdateChannelDisplayNameMessage(c.App.Session().UserId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { mlog.Error(err.Error()) } } @@ -199,7 +199,7 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, oldPublicChannel.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), oldPublicChannel.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -214,7 +214,7 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) return } - user, err := c.App.GetUser(c.App.Session.UserId) + user, err := c.App.GetUser(c.App.Session().UserId) if err != nil { c.Err = err return @@ -251,7 +251,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -261,7 +261,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { return } - user, err := c.App.GetUser(c.App.Session.UserId) + user, err := c.App.GetUser(c.App.Session().UserId) if err != nil { c.Err = err return @@ -301,20 +301,20 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { switch oldChannel.Type { case model.CHANNEL_OPEN: - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) return } case model.CHANNEL_PRIVATE: - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) return } case model.CHANNEL_GROUP, model.CHANNEL_DIRECT: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. - if _, err = c.App.GetChannelMember(c.Params.ChannelId, c.App.Session.UserId); err != nil { + if _, err = c.App.GetChannelMember(c.Params.ChannelId, c.App.Session().UserId); err != nil { c.Err = model.NewAppError("patchChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -324,7 +324,7 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - rchannel, err := c.App.PatchChannel(oldChannel, patch, c.App.Session.UserId) + rchannel, err := c.App.PatchChannel(oldChannel, patch, c.App.Session().UserId) if err != nil { c.Err = err return @@ -353,12 +353,12 @@ func restoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { } teamId := channel.TeamId - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } - channel, err = c.App.RestoreChannel(channel, c.App.Session.UserId) + channel, err = c.App.RestoreChannel(channel, c.App.Session().UserId) if err != nil { c.Err = err return @@ -383,27 +383,27 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("user_id") return } - if id == c.App.Session.UserId { + if id == c.App.Session().UserId { allowed = true } } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_DIRECT_CHANNEL) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_DIRECT_CHANNEL) { c.SetPermissionError(model.PERMISSION_CREATE_DIRECT_CHANNEL) return } - if !allowed && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !allowed && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } otherUserId := userIds[0] - if c.App.Session.UserId == otherUserId { + if c.App.Session().UserId == otherUserId { otherUserId = userIds[1] } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, otherUserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, otherUserId) if err != nil { c.Err = err return @@ -431,7 +431,7 @@ func searchGroupChannels(c *Context, w http.ResponseWriter, r *http.Request) { return } - groupChannels, err := c.App.SearchGroupChannels(c.App.Session.UserId, props.Term) + groupChannels, err := c.App.SearchGroupChannels(c.App.Session().UserId, props.Term) if err != nil { c.Err = err return @@ -454,24 +454,24 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("user_id") return } - if id == c.App.Session.UserId { + if id == c.App.Session().UserId { found = true } } if !found { - userIds = append(userIds, c.App.Session.UserId) + userIds = append(userIds, c.App.Session().UserId) } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_GROUP_CHANNEL) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_GROUP_CHANNEL) { c.SetPermissionError(model.PERMISSION_CREATE_GROUP_CHANNEL) return } canSeeAll := true for _, id := range userIds { - if c.App.Session.UserId != id { - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, id) + if c.App.Session().UserId != id { + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, id) if err != nil { c.Err = err return @@ -487,7 +487,7 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - groupChannel, err := c.App.CreateGroupChannel(userIds, c.App.Session.UserId) + groupChannel, err := c.App.CreateGroupChannel(userIds, c.App.Session().UserId) if err != nil { c.Err = err return @@ -510,12 +510,12 @@ func getChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } } else { - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -536,12 +536,12 @@ func getChannelUnread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -561,7 +561,7 @@ func getChannelStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -594,7 +594,7 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -616,7 +616,7 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { } func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -657,7 +657,7 @@ func getPublicChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) return } @@ -683,7 +683,7 @@ func getDeletedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Reques return } - channels, err := c.App.GetDeletedChannels(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage, c.App.Session.UserId) + channels, err := c.App.GetDeletedChannels(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage, c.App.Session().UserId) if err != nil { c.Err = err return @@ -717,7 +717,7 @@ func getPublicChannelsByIdsForTeam(c *Context, w http.ResponseWriter, r *http.Re } } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -743,12 +743,12 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -779,7 +779,7 @@ func autocompleteChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Requ return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) return } @@ -803,14 +803,14 @@ func autocompleteChannelsForTeamForSearch(c *Context, w http.ResponseWriter, r * return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) return } name := r.URL.Query().Get("name") - channels, err := c.App.AutocompleteChannelsForSearch(c.Params.TeamId, c.App.Session.UserId, name) + channels, err := c.App.AutocompleteChannelsForSearch(c.Params.TeamId, c.App.Session().UserId, name) if err != nil { c.Err = err return @@ -835,16 +835,16 @@ func searchChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request) { var channels *model.ChannelList var err *model.AppError - if c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { channels, err = c.App.SearchChannels(c.Params.TeamId, props.Term) } else { // If the user is not a team member, return a 404 - if _, err = c.App.GetTeamMember(c.Params.TeamId, c.App.Session.UserId); err != nil { + if _, err = c.App.GetTeamMember(c.Params.TeamId, c.App.Session().UserId); err != nil { c.Err = err return } - channels, err = c.App.SearchChannelsForUser(c.App.Session.UserId, c.Params.TeamId, props.Term) + channels, err = c.App.SearchChannelsForUser(c.App.Session().UserId, c.Params.TeamId, props.Term) } if err != nil { @@ -871,16 +871,16 @@ func searchArchivedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Re var channels *model.ChannelList var err *model.AppError - if c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { - channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.App.Session.UserId) + if c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.App.Session().UserId) } else { // If the user is not a team member, return a 404 - if _, err = c.App.GetTeamMember(c.Params.TeamId, c.App.Session.UserId); err != nil { + if _, err = c.App.GetTeamMember(c.Params.TeamId, c.App.Session().UserId); err != nil { c.Err = err return } - channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.App.Session.UserId) + channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.App.Session().UserId) } if err != nil { @@ -900,7 +900,7 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -950,17 +950,17 @@ func deleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_DELETE_PUBLIC_CHANNEL) { + if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_DELETE_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_DELETE_PUBLIC_CHANNEL) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_DELETE_PRIVATE_CHANNEL) { + if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_DELETE_PRIVATE_CHANNEL) { c.SetPermissionError(model.PERMISSION_DELETE_PRIVATE_CHANNEL) return } - err = c.App.DeleteChannel(channel, c.App.Session.UserId) + err = c.App.DeleteChannel(channel, c.App.Session().UserId) if err != nil { c.Err = err return @@ -986,12 +986,12 @@ func getChannelByName(c *Context, w http.ResponseWriter, r *http.Request) { } if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } } else { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.Err = model.NewAppError("getChannelByName", store.MISSING_CHANNEL_ERROR, nil, "teamId="+channel.TeamId+", "+"name="+channel.Name+"", http.StatusNotFound) return } @@ -1020,7 +1020,7 @@ func getChannelByNameForTeamName(c *Context, w http.ResponseWriter, r *http.Requ return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.Err = model.NewAppError("getChannelByNameForTeamName", store.MISSING_CHANNEL_ERROR, nil, "teamId="+channel.TeamId+", "+"name="+channel.Name+"", http.StatusNotFound) return } @@ -1040,7 +1040,7 @@ func getChannelMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1060,7 +1060,7 @@ func getChannelMembersTimezones(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1086,7 +1086,7 @@ func getChannelMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1106,7 +1106,7 @@ func getChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1126,12 +1126,12 @@ func getChannelMembersForUser(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - if c.App.Session.UserId != c.Params.UserId && !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1151,7 +1151,7 @@ func viewChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1173,13 +1173,13 @@ func viewChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - times, err := c.App.ViewChannel(view, c.Params.UserId, c.App.Session.Id) + times, err := c.App.ViewChannel(view, c.Params.UserId, c.App.Session().Id) if err != nil { c.Err = err return } - c.App.UpdateLastActivityAtIfNeeded(c.App.Session) + c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) // Returning {"status": "OK", ...} for backwards compatibility resp := &model.ChannelViewResponse{ @@ -1204,7 +1204,7 @@ func updateChannelMemberRoles(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) return } @@ -1229,7 +1229,7 @@ func updateChannelMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.R return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) return } @@ -1254,7 +1254,7 @@ func updateChannelMemberNotifyProps(c *Context, w http.ResponseWriter, r *http.R return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1325,18 +1325,18 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - isSelfAdd := member.UserId == c.App.Session.UserId + isSelfAdd := member.UserId == c.App.Session().UserId if channel.Type == model.CHANNEL_OPEN { if isSelfAdd && isNewMembership { - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_JOIN_PUBLIC_CHANNELS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_JOIN_PUBLIC_CHANNELS) { c.SetPermissionError(model.PERMISSION_JOIN_PUBLIC_CHANNELS) return } } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) return } @@ -1345,14 +1345,14 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { if channel.Type == model.CHANNEL_PRIVATE { if isSelfAdd && isNewMembership { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) return } } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) return } @@ -1375,7 +1375,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - cm, err := c.App.AddChannelMember(member.UserId, channel, c.App.Session.UserId, postRootId) + cm, err := c.App.AddChannelMember(member.UserId, channel, c.App.Session().UserId, postRootId) if err != nil { c.Err = err return @@ -1409,24 +1409,24 @@ func removeChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.IsGroupConstrained() && (c.Params.UserId != c.App.Session.UserId) && !user.IsBot { + if channel.IsGroupConstrained() && (c.Params.UserId != c.App.Session().UserId) && !user.IsBot { c.Err = model.NewAppError("removeChannelMember", "api.channel.remove_member.group_constrained.app_error", nil, "", http.StatusBadRequest) return } - if c.Params.UserId != c.App.Session.UserId { - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { + if c.Params.UserId != c.App.Session().UserId { + if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) return } - if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { + if channel.Type == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) return } } - if err = c.App.RemoveUserFromChannel(c.Params.UserId, c.App.Session.UserId, channel); err != nil { + if err = c.App.RemoveUserFromChannel(c.Params.UserId, c.App.Session().UserId, channel); err != nil { c.Err = err return } @@ -1453,7 +1453,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1508,7 +1508,7 @@ func channelMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http. groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/channel_test.go b/api4/channel_test.go index 19e91d23fb..ea272ec52b 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -1298,7 +1298,7 @@ func TestDeleteChannel2(t *testing.T) { // successful delete by channel admin th.MakeUserChannelAdmin(user, publicChannel6) th.MakeUserChannelAdmin(user, privateChannel7) - th.App.Srv.Store.Channel().ClearCaches() + th.App.Srv().Store.Channel().ClearCaches() _, resp = Client.DeleteChannel(publicChannel6.Id) CheckNoError(t, resp) diff --git a/api4/cluster.go b/api4/cluster.go index e476e2d923..53c19f5345 100644 --- a/api4/cluster.go +++ b/api4/cluster.go @@ -14,7 +14,7 @@ func (api *API) InitCluster() { } func getClusterStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/command.go b/api4/command.go index e945d9c204..c85e48bf18 100644 --- a/api4/command.go +++ b/api4/command.go @@ -34,12 +34,12 @@ func createCommand(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) return } - cmd.CreatorId = c.App.Session.UserId + cmd.CreatorId = c.App.Session().UserId rcmd, err := c.App.CreateCommand(cmd) if err != nil { @@ -73,11 +73,11 @@ func updateCommand(c *Context, w http.ResponseWriter, r *http.Request) { } if cmd.TeamId != oldCmd.TeamId { - c.Err = model.NewAppError("updateCommand", "api.command.team_mismatch.app_error", nil, "user_id="+c.App.Session.UserId, http.StatusBadRequest) + c.Err = model.NewAppError("updateCommand", "api.command.team_mismatch.app_error", nil, "user_id="+c.App.Session().UserId, http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, oldCmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -85,7 +85,7 @@ func updateCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != oldCmd.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, oldCmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.App.Session().UserId != oldCmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) return @@ -122,7 +122,7 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, newTeam.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), newTeam.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) return @@ -134,7 +134,7 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -165,7 +165,7 @@ func deleteCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -173,7 +173,7 @@ func deleteCommand(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.App.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) return @@ -202,7 +202,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -210,7 +210,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { var commands []*model.Command var err *model.AppError if customOnly { - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) return } @@ -221,7 +221,7 @@ func listCommands(c *Context, w http.ResponseWriter, r *http.Request) { } } else { //User with no permission should see only system commands - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { commands, err = c.App.ListAutocompleteCommands(teamId, c.App.T) if err != nil { c.Err = err @@ -254,13 +254,13 @@ func getCommand(c *Context, w http.ResponseWriter, r *http.Request) { // check for permissions to view this command; must have perms to view team and // PERMISSION_MANAGE_SLASH_COMMANDS for the team the command belongs to. - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_VIEW_TEAM) { // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. c.SetCommandNotFoundError() return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { // again, return not_found to ensure id existence does not leak. c.SetCommandNotFoundError() return @@ -281,7 +281,7 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { } // checks that user is a member of the specified channel, and that they have permission to use slash commands in it - if !c.App.SessionHasPermissionToChannel(c.App.Session, commandArgs.ChannelId, model.PERMISSION_USE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), commandArgs.ChannelId, model.PERMISSION_USE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) return } @@ -299,17 +299,17 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { } else { // if the slash command was used in a DM or GM, ensure that the user is a member of the specified team, so that // they can't just execute slash commands against arbitrary teams - if c.App.Session.GetTeamByTeamId(commandArgs.TeamId) == nil { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_USE_SLASH_COMMANDS) { + if c.App.Session().GetTeamByTeamId(commandArgs.TeamId) == nil { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_USE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) return } } } - commandArgs.UserId = c.App.Session.UserId + commandArgs.UserId = c.App.Session().UserId commandArgs.T = c.App.T - commandArgs.Session = c.App.Session + commandArgs.Session = *c.App.Session() commandArgs.SiteURL = c.GetSiteURLHeader() response, err := c.App.ExecuteCommand(commandArgs) @@ -327,7 +327,7 @@ func listAutocompleteCommands(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -354,7 +354,7 @@ func regenCommandToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") // here we return Not_found instead of a permissions error so we don't leak the existence of // a command to someone without permissions for the team it belongs to. @@ -362,7 +362,7 @@ func regenCommandToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { + if c.App.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) return diff --git a/api4/compliance.go b/api4/compliance.go index 41d08bb27f..b94dc9bfdc 100644 --- a/api4/compliance.go +++ b/api4/compliance.go @@ -25,12 +25,12 @@ func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - job.UserId = c.App.Session.UserId + job.UserId = c.App.Session().UserId rjob, err := c.App.SaveComplianceReport(job) if err != nil { @@ -44,7 +44,7 @@ func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) } func getComplianceReports(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -64,7 +64,7 @@ func getComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -84,7 +84,7 @@ func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/config.go b/api4/config.go index 04ae19bea4..301870abbc 100644 --- a/api4/config.go +++ b/api4/config.go @@ -22,7 +22,7 @@ func (api *API) InitConfig() { } func getConfig(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -34,7 +34,7 @@ func getConfig(c *Context, w http.ResponseWriter, r *http.Request) { } func configReload(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -57,7 +57,7 @@ func updateConfig(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -121,7 +121,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { } var config map[string]string - if len(c.App.Session.UserId) == 0 { + if len(c.App.Session().UserId) == 0 { config = c.App.LimitedClientConfigWithComputed() } else { config = c.App.ClientConfigWithComputed() @@ -131,7 +131,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { } func getEnvironmentConfig(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -149,7 +149,7 @@ func patchConfig(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/cors_test.go b/api4/cors_test.go index c0de025af2..7f64714486 100644 --- a/api4/cors_test.go +++ b/api4/cors_test.go @@ -126,7 +126,7 @@ func TestCORSRequestHandling(t *testing.T) { }) defer th.TearDown() - port := th.App.Srv.ListenAddr.Port + port := th.App.Srv().ListenAddr.Port host := fmt.Sprintf("http://localhost:%v", port) url := fmt.Sprintf("%v/api/v4/system/ping", host) diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index 8c7703c013..94fed473e1 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -20,7 +20,7 @@ func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -39,7 +39,7 @@ func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { } func purgeElasticsearchIndexes(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/emoji.go b/api4/emoji.go index 8ae071c475..99bc2495a3 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -48,17 +48,17 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } // Allow any user with CREATE_EMOJIS permission at Team level to create emojis at system level - memberships, err := c.App.GetTeamMembersForUser(c.App.Session.UserId) + memberships, err := c.App.GetTeamMembersForUser(c.App.Session().UserId) if err != nil { c.Err = err return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_EMOJIS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_EMOJIS) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(c.App.Session, membership.TeamId, model.PERMISSION_CREATE_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), membership.TeamId, model.PERMISSION_CREATE_EMOJIS) { hasPermission = true break } @@ -83,7 +83,7 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { return } - newEmoji, err := c.App.CreateEmoji(c.App.Session.UserId, emoji, m) + newEmoji, err := c.App.CreateEmoji(c.App.Session().UserId, emoji, m) if err != nil { c.Err = err return @@ -126,17 +126,17 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } // Allow any user with DELETE_EMOJIS permission at Team level to delete emojis at system level - memberships, err := c.App.GetTeamMembersForUser(c.App.Session.UserId) + memberships, err := c.App.GetTeamMembersForUser(c.App.Session().UserId) if err != nil { c.Err = err return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_DELETE_EMOJIS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DELETE_EMOJIS) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(c.App.Session, membership.TeamId, model.PERMISSION_DELETE_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), membership.TeamId, model.PERMISSION_DELETE_EMOJIS) { hasPermission = true break } @@ -147,11 +147,11 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { } } - if c.App.Session.UserId != emoji.CreatorId { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_DELETE_OTHERS_EMOJIS) { + if c.App.Session().UserId != emoji.CreatorId { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DELETE_OTHERS_EMOJIS) { hasPermission := false for _, membership := range memberships { - if c.App.SessionHasPermissionToTeam(c.App.Session, membership.TeamId, model.PERMISSION_DELETE_OTHERS_EMOJIS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), membership.TeamId, model.PERMISSION_DELETE_OTHERS_EMOJIS) { hasPermission = true break } diff --git a/api4/file.go b/api4/file.go index 2a149e173d..0ecd8b0f31 100644 --- a/api4/file.go +++ b/api4/file.go @@ -153,7 +153,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F return nil } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -161,7 +161,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F clientId := r.Form.Get("client_id") info, appErr := c.App.UploadFileX(c.Params.ChannelId, c.Params.Filename, r.Body, app.UploadFileSetTeamId(FILE_TEAM_ID), - app.UploadFileSetUserId(c.App.Session.UserId), + app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(r.ContentLength), app.UploadFileSetClientId(clientId)) @@ -294,7 +294,7 @@ NEXT_PART: if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -318,7 +318,7 @@ NEXT_PART: info, appErr := c.App.UploadFileX(c.Params.ChannelId, filename, part, app.UploadFileSetTeamId(FILE_TEAM_ID), - app.UploadFileSetUserId(c.App.Session.UserId), + app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), app.UploadFileSetClientId(clientId)) @@ -374,7 +374,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_UPLOAD_FILE) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -411,7 +411,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, info, appErr := c.App.UploadFileX(c.Params.ChannelId, fileHeader.Filename, f, app.UploadFileSetTeamId(FILE_TEAM_ID), - app.UploadFileSetUserId(c.App.Session.UserId), + app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), app.UploadFileSetClientId(clientId)) @@ -447,7 +447,7 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.App.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -484,7 +484,7 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.App.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -526,7 +526,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.App.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -559,7 +559,7 @@ func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.App.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -596,7 +596,7 @@ func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) { return } - if info.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionToChannelByPost(c.App.Session, info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } diff --git a/api4/file_test.go b/api4/file_test.go index 8bc1a17064..70e32820c5 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -567,7 +567,7 @@ func TestUploadFiles(t *testing.T) { fmt.Sprintf("Wrong clientId returned, expected %v, got %v", tc.clientIds[i], fileResp.ClientIds[i])) } - dbInfo, err := th.App.Srv.Store.FileInfo().Get(ri.Id) + dbInfo, err := th.App.Srv().Store.FileInfo().Get(ri.Id) require.Nil(t, err) assert.Equal(t, dbInfo.Id, ri.Id, "File id from response should match one stored in database") assert.Equal(t, dbInfo.CreatorId, tc.expectedCreatorId, "F ile should be assigned to user") @@ -801,7 +801,7 @@ func TestGetFileLink(t *testing.T) { CheckBadRequestStatus(t, resp) // Hacky way to assign file to a post (usually would be done by CreatePost call) - err = th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) require.Nil(t, err) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = false }) @@ -835,7 +835,7 @@ func TestGetFileLink(t *testing.T) { _, resp = th.SystemAdminClient.GetFileLink(fileId) CheckNoError(t, resp) - fileInfo, err := th.App.Srv.Store.FileInfo().Get(fileId) + fileInfo, err := th.App.Srv().Store.FileInfo().Get(fileId) require.Nil(t, err) th.cleanupTestFile(fileInfo) } @@ -955,10 +955,10 @@ func TestGetPublicFile(t *testing.T) { fileId := fileResp.FileInfos[0].Id // Hacky way to assign file to a post (usually would be done by CreatePost call) - err = th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) require.Nil(t, err) - info, err := th.App.Srv.Store.FileInfo().Get(fileId) + info, err := th.App.Srv().Store.FileInfo().Get(fileId) require.Nil(t, err) link := th.App.GeneratePublicLink(Client.Url, info) @@ -991,7 +991,7 @@ func TestGetPublicFile(t *testing.T) { require.NoError(t, err) require.Equal(t, http.StatusBadRequest, resp.StatusCode, "should've failed to get image with public link after salt changed") - fileInfo, err := th.App.Srv.Store.FileInfo().Get(fileId) + fileInfo, err := th.App.Srv().Store.FileInfo().Get(fileId) require.Nil(t, err) require.Nil(t, th.cleanupTestFile(fileInfo)) th.cleanupTestFile(info) diff --git a/api4/group.go b/api4/group.go index 738cb8ea40..fe242c13b0 100644 --- a/api4/group.go +++ b/api4/group.go @@ -73,7 +73,7 @@ func getGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -110,7 +110,7 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -230,7 +230,7 @@ func getGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -267,7 +267,7 @@ func getGroupSyncables(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -402,7 +402,7 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType, syncableID string) *model.AppError { switch syncableType { case model.GroupSyncableTypeTeam: - if !c.App.SessionHasPermissionToTeam(c.App.Session, syncableID, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), syncableID, model.PERMISSION_MANAGE_TEAM) { return c.App.MakePermissionError(model.PERMISSION_MANAGE_TEAM) } case model.GroupSyncableTypeChannel: @@ -418,7 +418,7 @@ func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS } - if !c.App.SessionHasPermissionToChannel(c.App.Session, syncableID, permission) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), syncableID, permission) { return c.App.MakePermissionError(permission) } } @@ -437,7 +437,7 @@ func getGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -485,7 +485,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else { permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS } - if !c.App.SessionHasPermissionToChannel(c.App.Session, c.Params.ChannelId, permission) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, permission) { c.SetPermissionError(permission) return } @@ -531,7 +531,7 @@ func getGroupsByTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -597,7 +597,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = err return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamID, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamID, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -616,7 +616,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { } else { permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS } - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelID, permission) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelID, permission) { c.SetPermissionError(permission) return } diff --git a/api4/image.go b/api4/image.go index eece83f73f..46006c2bb2 100644 --- a/api4/image.go +++ b/api4/image.go @@ -15,7 +15,7 @@ func getImage(c *Context, w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") if *c.App.Config().ImageProxySettings.Enable { - c.App.ImageProxy.GetImage(w, r, url) + c.App.ImageProxy().GetImage(w, r, url) } else { http.Redirect(w, r, url, http.StatusFound) } diff --git a/api4/integration_action.go b/api4/integration_action.go index 24304ec8d2..b15fc96be3 100644 --- a/api4/integration_action.go +++ b/api4/integration_action.go @@ -41,12 +41,12 @@ func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, cookie.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), cookie.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } } else { - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -55,7 +55,7 @@ func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) { var appErr *model.AppError resp := &model.PostActionAPIResponse{Status: "OK"} - resp.TriggerId, appErr = c.App.DoPostActionWithCookie(c.Params.PostId, c.Params.ActionId, c.App.Session.UserId, + resp.TriggerId, appErr = c.App.DoPostActionWithCookie(c.Params.PostId, c.Params.ActionId, c.App.Session().UserId, actionRequest.SelectedOption, cookie) if appErr != nil { c.Err = appErr @@ -101,14 +101,14 @@ func submitDialog(c *Context, w http.ResponseWriter, r *http.Request) { return } - submit.UserId = c.App.Session.UserId + submit.UserId = c.App.Session().UserId - if !c.App.SessionHasPermissionToChannel(c.App.Session, submit.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), submit.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, submit.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), submit.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } diff --git a/api4/job.go b/api4/job.go index 26b5691a52..7ed365a518 100644 --- a/api4/job.go +++ b/api4/job.go @@ -23,7 +23,7 @@ func getJob(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_JOBS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_JOBS) { c.SetPermissionError(model.PERMISSION_MANAGE_JOBS) return } @@ -44,7 +44,7 @@ func createJob(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_JOBS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_JOBS) { c.SetPermissionError(model.PERMISSION_MANAGE_JOBS) return } @@ -64,7 +64,7 @@ func getJobs(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_JOBS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_JOBS) { c.SetPermissionError(model.PERMISSION_MANAGE_JOBS) return } @@ -84,7 +84,7 @@ func getJobsByType(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_JOBS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_JOBS) { c.SetPermissionError(model.PERMISSION_MANAGE_JOBS) return } @@ -104,7 +104,7 @@ func cancelJob(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_JOBS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_JOBS) { c.SetPermissionError(model.PERMISSION_MANAGE_JOBS) return } diff --git a/api4/job_test.go b/api4/job_test.go index 40785b293d..7c61bdf9a3 100644 --- a/api4/job_test.go +++ b/api4/job_test.go @@ -25,7 +25,7 @@ func TestCreateJob(t *testing.T) { received, resp := th.SystemAdminClient.CreateJob(job) require.Nil(t, resp.Error) - defer th.App.Srv.Store.Job().Delete(received.Id) + defer th.App.Srv().Store.Job().Delete(received.Id) job = &model.Job{ Type: model.NewId(), @@ -46,10 +46,10 @@ func TestGetJob(t *testing.T) { Id: model.NewId(), Status: model.JOB_STATUS_PENDING, } - _, err := th.App.Srv.Store.Job().Save(job) + _, err := th.App.Srv().Store.Job().Save(job) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(job.Id) + defer th.App.Srv().Store.Job().Delete(job.Id) received, resp := th.SystemAdminClient.GetJob(job.Id) require.Nil(t, resp.Error) @@ -93,9 +93,9 @@ func TestGetJobs(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv.Store.Job().Save(job) + _, err := th.App.Srv().Store.Job().Save(job) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(job.Id) + defer th.App.Srv().Store.Job().Delete(job.Id) } received, resp := th.SystemAdminClient.GetJobs(0, 2) @@ -144,9 +144,9 @@ func TestGetJobsByType(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv.Store.Job().Save(job) + _, err := th.App.Srv().Store.Job().Save(job) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(job.Id) + defer th.App.Srv().Store.Job().Delete(job.Id) } received, resp := th.SystemAdminClient.GetJobsByType(jobType, 0, 2) @@ -195,9 +195,9 @@ func TestCancelJob(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv.Store.Job().Save(job) + _, err := th.App.Srv().Store.Job().Save(job) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(job.Id) + defer th.App.Srv().Store.Job().Delete(job.Id) } _, resp := th.Client.CancelJob(jobs[0].Id) diff --git a/api4/ldap.go b/api4/ldap.go index e0a25c84bf..e5fd4b83fb 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -38,7 +38,7 @@ func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -54,7 +54,7 @@ func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -68,7 +68,7 @@ func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { } func getLdapGroups(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -125,7 +125,7 @@ func linkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -214,7 +214,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/license.go b/api4/license.go index 5fdd377a26..9b6463d8b1 100644 --- a/api4/license.go +++ b/api4/license.go @@ -32,7 +32,7 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { var clientLicense map[string]string - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { clientLicense = c.App.ClientLicense() } else { clientLicense = c.App.GetSanitizedClientLicense() @@ -44,7 +44,7 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -105,7 +105,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { func removeLicense(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/oauth.go b/api4/oauth.go index 6904305d0e..61a67b4d70 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -29,16 +29,16 @@ func createOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { oauthApp.IsTrusted = false } - oauthApp.CreatorId = c.App.Session.UserId + oauthApp.CreatorId = c.App.Session().UserId rapp, err := c.App.CreateOAuthApp(oauthApp) if err != nil { @@ -57,7 +57,7 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -82,12 +82,12 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != oldOauthApp.CreatorId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.App.Session().UserId != oldOauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { oauthApp.IsTrusted = oldOauthApp.IsTrusted } @@ -103,17 +103,17 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } func getOAuthApps(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.Err = model.NewAppError("getOAuthApps", "api.command.admin_only.app_error", nil, "", http.StatusForbidden) return } var apps []*model.OAuthApp var err *model.AppError - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { apps, err = c.App.GetOAuthApps(c.Params.Page, c.Params.PerPage) - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { - apps, err = c.App.GetOAuthAppsByCreator(c.App.Session.UserId, c.Params.Page, c.Params.PerPage) + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { + apps, err = c.App.GetOAuthAppsByCreator(c.App.Session().UserId, c.Params.Page, c.Params.PerPage) } else { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return @@ -133,7 +133,7 @@ func getOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -144,7 +144,7 @@ func getOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if oauthApp.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if oauthApp.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -176,7 +176,7 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -187,7 +187,7 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.App.Session().UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -208,7 +208,7 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -219,7 +219,7 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request return } - if oauthApp.CreatorId != c.App.Session.UserId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if oauthApp.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -240,7 +240,7 @@ func getAuthorizedOAuthApps(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/plugin.go b/api4/plugin.go index 47c3ada47d..46a4c46cb2 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -46,7 +46,7 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -92,7 +92,7 @@ func installPluginFromUrl(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -120,7 +120,7 @@ func installMarketplacePlugin(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -147,7 +147,7 @@ func getPlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -167,7 +167,7 @@ func getPluginStatuses(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -192,7 +192,7 @@ func removePlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -243,7 +243,7 @@ func getMarketplacePlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -280,7 +280,7 @@ func enablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -304,7 +304,7 @@ func disablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/post.go b/api4/post.go index d9ef322d52..e61b8852da 100644 --- a/api4/post.go +++ b/api4/post.go @@ -41,14 +41,14 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - post.UserId = c.App.Session.UserId + post.UserId = c.App.Session().UserId hasPermission := false - if c.App.SessionHasPermissionToChannel(c.App.Session, post.ChannelId, model.PERMISSION_CREATE_POST) { + if c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_CREATE_POST) { hasPermission = true } else if channel, err := c.App.GetChannel(post.ChannelId); err == nil { // Temporary permission check method until advanced permissions, please do not copy - if channel.Type == model.CHANNEL_OPEN && c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_CREATE_POST_PUBLIC) { + if channel.Type == model.CHANNEL_OPEN && c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_CREATE_POST_PUBLIC) { hasPermission = true } } @@ -58,11 +58,11 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if post.CreateAt != 0 && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if post.CreateAt != 0 && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { post.CreateAt = 0 } - rp, err := c.App.CreatePostAsUser(c.App.PostWithProxyRemovedFromImageURLs(post), c.App.Session.Id) + rp, err := c.App.CreatePostAsUser(c.App.PostWithProxyRemovedFromImageURLs(post), c.App.Session().Id) if err != nil { c.Err = err return @@ -79,10 +79,10 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { } } if setOnlineBool { - c.App.SetStatusOnline(c.App.Session.UserId, false) + c.App.SetStatusOnline(c.App.Session().UserId, false) } - c.App.UpdateLastActivityAtIfNeeded(c.App.Session) + c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) w.WriteHeader(http.StatusCreated) @@ -104,10 +104,10 @@ func createEphemeralPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - ephRequest.Post.UserId = c.App.Session.UserId + ephRequest.Post.UserId = c.App.Session().UserId ephRequest.Post.CreateAt = model.GetMillis() - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_POST_EPHEMERAL) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_POST_EPHEMERAL) { c.SetPermissionError(model.PERMISSION_CREATE_POST_EPHEMERAL) return } @@ -154,7 +154,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { page := c.Params.Page perPage := c.Params.PerPage - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -213,13 +213,13 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht } userId := c.Params.UserId - if !c.App.SessionHasPermissionToUser(c.App.Session, userId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), userId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } channelId := c.Params.ChannelId - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -263,7 +263,7 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -291,7 +291,7 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) if !ok { allowed = false - if c.App.SessionHasPermissionToChannel(c.App.Session, post.ChannelId, model.PERMISSION_READ_CHANNEL) { + if c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { allowed = true } @@ -334,9 +334,9 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } @@ -368,19 +368,19 @@ func deletePost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId == post.UserId { - if !c.App.SessionHasPermissionToChannel(c.App.Session, post.ChannelId, model.PERMISSION_DELETE_POST) { + if c.App.Session().UserId == post.UserId { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_DELETE_POST) { c.SetPermissionError(model.PERMISSION_DELETE_POST) return } } else { - if !c.App.SessionHasPermissionToChannel(c.App.Session, post.ChannelId, model.PERMISSION_DELETE_OTHERS_POSTS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_DELETE_OTHERS_POSTS) { c.SetPermissionError(model.PERMISSION_DELETE_OTHERS_POSTS) return } } - if _, err := c.App.DeletePost(c.Params.PostId, c.App.Session.UserId); err != nil { + if _, err := c.App.DeletePost(c.Params.PostId, c.App.Session().UserId); err != nil { c.Err = err return } @@ -412,9 +412,9 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { if channel.Type == model.CHANNEL_OPEN { - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } @@ -441,7 +441,7 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -481,10 +481,10 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) { startTime := time.Now() - results, err := c.App.SearchPostsInTeamForUser(terms, c.App.Session.UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) + results, err := c.App.SearchPostsInTeamForUser(terms, c.App.Session().UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) elapsedTime := float64(time.Since(startTime)) / float64(time.Second) - metrics := c.App.Metrics + metrics := c.App.Metrics() if metrics != nil { metrics.IncrementPostsSearchCounter() metrics.ObservePostsSearchDuration(elapsedTime) @@ -522,7 +522,7 @@ func updatePost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_EDIT_POST) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_EDIT_POST) { c.SetPermissionError(model.PERMISSION_EDIT_POST) return } @@ -536,8 +536,8 @@ func updatePost(c *Context, w http.ResponseWriter, r *http.Request) { // Updating the file_ids of a post is not a supported operation and will be ignored post.FileIds = originalPost.FileIds - if c.App.Session.UserId != originalPost.UserId { - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { + if c.App.Session().UserId != originalPost.UserId { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { c.SetPermissionError(model.PERMISSION_EDIT_OTHERS_POSTS) return } @@ -570,7 +570,7 @@ func patchPost(c *Context, w http.ResponseWriter, r *http.Request) { // Updating the file_ids of a post is not a supported operation and will be ignored post.FileIds = nil - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_EDIT_POST) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_EDIT_POST) { c.SetPermissionError(model.PERMISSION_EDIT_POST) return } @@ -581,8 +581,8 @@ func patchPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != originalPost.UserId { - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { + if c.App.Session().UserId != originalPost.UserId { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { c.SetPermissionError(model.PERMISSION_EDIT_OTHERS_POSTS) return } @@ -602,11 +602,11 @@ func setPostUnread(c *Context, w http.ResponseWriter, r *http.Request) { if c.Err != nil { return } - if c.App.Session.UserId != c.Params.UserId && !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -625,13 +625,13 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, r *http.Request, isPinn return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } // Restrict pinning if the experimental read-only-town-square setting is on. - user, err := c.App.GetUser(c.App.Session.UserId) + user, err := c.App.GetUser(c.App.Session().UserId) if err != nil { c.Err = err return @@ -683,7 +683,7 @@ func getFileInfosForPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } diff --git a/api4/post_test.go b/api4/post_test.go index a847982e09..7eaee1b1e9 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -1617,12 +1617,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { // Set channel member's last viewed to 0. // All returned posts are latest posts as if all previous posts were already read by the user. - channelMember, err := th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err := th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = 0 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 20, 20) CheckNoError(t, resp) @@ -1638,12 +1638,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { postIdNames[systemPost1.Id] = "system post 1" // Set channel member's last viewed before post1. - channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err = th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = post1.CreateAt - 1 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3) CheckNoError(t, resp) @@ -1662,12 +1662,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed before post6. - channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err = th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = post6.CreateAt - 1 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3) CheckNoError(t, resp) @@ -1689,12 +1689,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed before post10. - channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err = th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = post10.CreateAt - 1 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3) CheckNoError(t, resp) @@ -1714,12 +1714,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed equal to post10. - channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err = th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = post10.CreateAt - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3) CheckNoError(t, resp) @@ -1754,12 +1754,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { postIdNames[post12.Id] = "post12 (reply to post4)" postIdNames[post13.Id] = "post13" - channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId) + channelMember, err = th.App.Srv().Store.Channel().GetMember(channelId, userId) require.Nil(t, err) channelMember.LastViewedAt = post12.CreateAt - 1 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 1, 2) CheckNoError(t, resp) diff --git a/api4/preference.go b/api4/preference.go index 8dc4a35ee2..0623add030 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -23,7 +23,7 @@ func getPreferences(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -43,7 +43,7 @@ func getPreferencesByCategory(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -63,7 +63,7 @@ func getPreferenceByCategoryAndName(c *Context, w http.ResponseWriter, r *http.R return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -83,7 +83,7 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -104,7 +104,7 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(c.App.Session, post.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -127,7 +127,7 @@ func deletePreferences(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/reaction.go b/api4/reaction.go index 4a781c683f..96d8a3bfd3 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -28,12 +28,12 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if reaction.UserId != c.App.Session.UserId { + if reaction.UserId != c.App.Session().UserId { c.Err = model.NewAppError("saveReaction", "api.reaction.save_reaction.user_id.app_error", nil, "", http.StatusForbidden) return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, reaction.PostId, model.PERMISSION_ADD_REACTION) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), reaction.PostId, model.PERMISSION_ADD_REACTION) { c.SetPermissionError(model.PERMISSION_ADD_REACTION) return } @@ -53,7 +53,7 @@ func getReactions(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -83,12 +83,12 @@ func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, c.Params.PostId, model.PERMISSION_REMOVE_REACTION) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_REMOVE_REACTION) { c.SetPermissionError(model.PERMISSION_REMOVE_REACTION) return } - if c.Params.UserId != c.App.Session.UserId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_REMOVE_OTHERS_REACTIONS) { + if c.Params.UserId != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REMOVE_OTHERS_REACTIONS) { c.SetPermissionError(model.PERMISSION_REMOVE_OTHERS_REACTIONS) return } @@ -111,7 +111,7 @@ func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) { func getBulkReactions(c *Context, w http.ResponseWriter, r *http.Request) { postIds := model.ArrayFromJson(r.Body) for _, postId := range postIds { - if !c.App.SessionHasPermissionToChannelByPost(c.App.Session, postId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), postId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } diff --git a/api4/reaction_test.go b/api4/reaction_test.go index 08ceeaefad..0593b0d1b8 100644 --- a/api4/reaction_test.go +++ b/api4/reaction_test.go @@ -244,7 +244,7 @@ func TestGetReactions(t *testing.T) { var reactions []*model.Reaction for _, userReaction := range userReactions { - reaction, err := th.App.Srv.Store.Reaction().Save(userReaction) + reaction, err := th.App.Srv().Store.Reaction().Save(userReaction) require.Nil(t, err) reactions = append(reactions, reaction) } @@ -595,7 +595,7 @@ func TestGetBulkReactions(t *testing.T) { for _, userReaction := range userReactions { reactions := expectedPostIdsReactionsMap[userReaction.PostId] - reaction, err := th.App.Srv.Store.Reaction().Save(userReaction) + reaction, err := th.App.Srv().Store.Reaction().Save(userReaction) require.Nil(t, err) reactions = append(reactions, reaction) expectedPostIdsReactionsMap[userReaction.PostId] = reactions diff --git a/api4/role.go b/api4/role.go index 85b4c2fc13..80421372ec 100644 --- a/api4/role.go +++ b/api4/role.go @@ -134,7 +134,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/role_test.go b/api4/role_test.go index ae217644d5..fd8d14ffde 100644 --- a/api4/role_test.go +++ b/api4/role_test.go @@ -25,9 +25,9 @@ func TestGetRole(t *testing.T) { SchemeManaged: true, } - role, err := th.App.Srv.Store.Role().Save(role) + role, err := th.App.Srv().Store.Role().Save(role) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role.Id) + defer th.App.Srv().Store.Job().Delete(role.Id) received, resp := th.Client.GetRole(role.Id) CheckNoError(t, resp) @@ -58,9 +58,9 @@ func TestGetRoleByName(t *testing.T) { SchemeManaged: true, } - role, err := th.App.Srv.Store.Role().Save(role) + role, err := th.App.Srv().Store.Role().Save(role) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role.Id) + defer th.App.Srv().Store.Job().Delete(role.Id) received, resp := th.Client.GetRoleByName(role.Name) CheckNoError(t, resp) @@ -105,17 +105,17 @@ func TestGetRolesByNames(t *testing.T) { SchemeManaged: true, } - role1, err := th.App.Srv.Store.Role().Save(role1) + role1, err := th.App.Srv().Store.Role().Save(role1) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role1.Id) + defer th.App.Srv().Store.Job().Delete(role1.Id) - role2, err = th.App.Srv.Store.Role().Save(role2) + role2, err = th.App.Srv().Store.Role().Save(role2) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role2.Id) + defer th.App.Srv().Store.Job().Delete(role2.Id) - role3, err = th.App.Srv.Store.Role().Save(role3) + role3, err = th.App.Srv().Store.Role().Save(role3) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role3.Id) + defer th.App.Srv().Store.Job().Delete(role3.Id) // Check all three roles can be found. received, resp := th.Client.GetRolesByNames([]string{role1.Name, role2.Name, role3.Name}) @@ -154,9 +154,9 @@ func TestPatchRole(t *testing.T) { SchemeManaged: true, } - role, err := th.App.Srv.Store.Role().Save(role) + role, err := th.App.Srv().Store.Role().Save(role) assert.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(role.Id) + defer th.App.Srv().Store.Job().Delete(role.Id) patch := &model.RolePatch{ Permissions: &[]string{"manage_system", "create_public_channel", "manage_incoming_webhooks", "manage_outgoing_webhooks"}, @@ -214,7 +214,7 @@ func TestPatchRole(t *testing.T) { license.Features.GuestAccountsPermissions = model.NewBool(false) th.App.SetLicense(license) - guestRole, err := th.App.Srv.Store.Role().GetByName("system_guest") + guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") require.Nil(t, err) received, resp = th.SystemAdminClient.PatchRole(guestRole.Id, patch) CheckNotImplementedStatus(t, resp) @@ -224,7 +224,7 @@ func TestPatchRole(t *testing.T) { license := model.NewTestLicense() license.Features.GuestAccountsPermissions = model.NewBool(true) th.App.SetLicense(license) - guestRole, err := th.App.Srv.Store.Role().GetByName("system_guest") + guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") require.Nil(t, err) _, resp = th.SystemAdminClient.PatchRole(guestRole.Id, patch) CheckNoError(t, resp) diff --git a/api4/saml.go b/api4/saml.go index a25150b787..feed3e3fcb 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -61,7 +61,7 @@ func parseSamlCertificateRequest(r *http.Request, maxFileSize int64) (*multipart } func addSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -80,7 +80,7 @@ func addSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request } func addSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -99,7 +99,7 @@ func addSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Reques } func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -146,7 +146,7 @@ func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { } func removeSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -160,7 +160,7 @@ func removeSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Requ } func removeSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -174,7 +174,7 @@ func removeSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Req } func removeSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -188,7 +188,7 @@ func removeSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request } func getSamlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -198,7 +198,7 @@ func getSamlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request } func getSamlMetadataFromIdp(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/scheme.go b/api4/scheme.go index 3b9259cc72..b3de3b7f4c 100644 --- a/api4/scheme.go +++ b/api4/scheme.go @@ -31,7 +31,7 @@ func createScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -52,7 +52,7 @@ func getScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -67,7 +67,7 @@ func getScheme(c *Context, w http.ResponseWriter, r *http.Request) { } func getSchemes(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -93,7 +93,7 @@ func getTeamsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -124,7 +124,7 @@ func getChannelsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -172,7 +172,7 @@ func patchScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -198,7 +198,7 @@ func deleteScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/scheme_test.go b/api4/scheme_test.go index bcd469a349..8981ac8af5 100644 --- a/api4/scheme_test.go +++ b/api4/scheme_test.go @@ -308,7 +308,7 @@ func TestGetTeamsForScheme(t *testing.T) { Type: model.TEAM_OPEN, } - team1, err := th.App.Srv.Store.Team().Save(team1) + team1, err := th.App.Srv().Store.Team().Save(team1) require.Nil(t, err) l2, r2 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -316,7 +316,7 @@ func TestGetTeamsForScheme(t *testing.T) { assert.Zero(t, len(l2)) team1.SchemeId = &scheme1.Id - team1, err = th.App.Srv.Store.Team().Update(team1) + team1, err = th.App.Srv().Store.Team().Update(team1) assert.Nil(t, err) l3, r3 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -330,7 +330,7 @@ func TestGetTeamsForScheme(t *testing.T) { Type: model.TEAM_OPEN, SchemeId: &scheme1.Id, } - team2, err = th.App.Srv.Store.Team().Save(team2) + team2, err = th.App.Srv().Store.Team().Save(team2) require.Nil(t, err) l4, r4 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -401,7 +401,7 @@ func TestGetChannelsForScheme(t *testing.T) { Type: model.CHANNEL_OPEN, } - channel1, errCh := th.App.Srv.Store.Channel().Save(channel1, 1000000) + channel1, errCh := th.App.Srv().Store.Channel().Save(channel1, 1000000) assert.Nil(t, errCh) l2, r2 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -409,7 +409,7 @@ func TestGetChannelsForScheme(t *testing.T) { assert.Zero(t, len(l2)) channel1.SchemeId = &scheme1.Id - channel1, err := th.App.Srv.Store.Channel().Update(channel1) + channel1, err := th.App.Srv().Store.Channel().Update(channel1) assert.Nil(t, err) l3, r3 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -424,7 +424,7 @@ func TestGetChannelsForScheme(t *testing.T) { Type: model.CHANNEL_OPEN, SchemeId: &scheme1.Id, } - channel2, err = th.App.Srv.Store.Channel().Save(channel2, 1000000) + channel2, err = th.App.Srv().Store.Channel().Save(channel2, 1000000) assert.Nil(t, err) l4, r4 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -620,7 +620,7 @@ func TestDeleteScheme(t *testing.T) { assert.Zero(t, role6.DeleteAt) // Make sure this scheme is in use by a team. - team, err := th.App.Srv.Store.Team().Save(&model.Team{ + team, err := th.App.Srv().Store.Team().Save(&model.Team{ Name: "zz" + model.NewId(), DisplayName: model.NewId(), Email: model.NewId() + "@nowhere.com", @@ -689,7 +689,7 @@ func TestDeleteScheme(t *testing.T) { assert.Zero(t, role6.DeleteAt) // Make sure this scheme is in use by a team. - channel, err := th.App.Srv.Store.Channel().Save(&model.Channel{ + channel, err := th.App.Srv().Store.Channel().Save(&model.Channel{ TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), diff --git a/api4/status.go b/api4/status.go index 1288b9fcb9..6ab4df139a 100644 --- a/api4/status.go +++ b/api4/status.go @@ -74,7 +74,7 @@ func updateUserStatus(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/system.go b/api4/system.go index e2e5390e47..e1dfa3c109 100644 --- a/api4/system.go +++ b/api4/system.go @@ -80,7 +80,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { currentTime := fmt.Sprintf("%d", time.Now().Unix()) healthCheckKey := "health_check" - writeErr := c.App.Srv.Store.System().SaveOrUpdate(&model.System{ + writeErr := c.App.Srv().Store.System().SaveOrUpdate(&model.System{ Name: healthCheckKey, Value: currentTime, }) @@ -89,7 +89,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { s[dbStatusKey] = model.STATUS_UNHEALTHY s[model.STATUS] = model.STATUS_UNHEALTHY } else { - healthCheck, readErr := c.App.Srv.Store.System().GetByName(healthCheckKey) + healthCheck, readErr := c.App.Srv().Store.System().GetByName(healthCheckKey) if readErr != nil { mlog.Debug("Unable to read from database.", mlog.Err(readErr)) s[dbStatusKey] = model.STATUS_UNHEALTHY @@ -136,7 +136,7 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -146,7 +146,7 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { return } - err := c.App.TestEmail(c.App.Session.UserId, cfg) + err := c.App.TestEmail(c.App.Session().UserId, cfg) if err != nil { c.Err = err return @@ -156,7 +156,7 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { } func testSiteURL(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -182,7 +182,7 @@ func testSiteURL(c *Context, w http.ResponseWriter, r *http.Request) { } func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -198,7 +198,7 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { } func databaseRecycle(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -214,7 +214,7 @@ func databaseRecycle(c *Context, w http.ResponseWriter, r *http.Request) { } func invalidateCaches(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -235,7 +235,7 @@ func invalidateCaches(c *Context, w http.ResponseWriter, r *http.Request) { } func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -253,12 +253,12 @@ func postLog(c *Context, w http.ResponseWriter, r *http.Request) { forceToDebug := false if !*c.App.Config().ServiceSettings.EnableDeveloper { - if c.App.Session.UserId == "" { + if c.App.Session().UserId == "" { c.Err = model.NewAppError("postLog", "api.context.permissions.app_error", nil, "", http.StatusForbidden) return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { forceToDebug = true } } @@ -274,7 +274,7 @@ func postLog(c *Context, w http.ResponseWriter, r *http.Request) { msg = "Client Logs API Endpoint Message: " + msg fields := []mlog.Field{ mlog.String("type", "client_message"), - mlog.String("user_agent", c.App.UserAgent), + mlog.String("user_agent", c.App.UserAgent()), } if !forceToDebug && lvl == "ERROR" { @@ -295,7 +295,7 @@ func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { name = "standard" } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -315,7 +315,7 @@ func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { } func getSupportedTimezones(c *Context, w http.ResponseWriter, r *http.Request) { - supportedTimezones := c.App.Timezones.GetSupported() + supportedTimezones := c.App.Timezones().GetSupported() if supportedTimezones == nil { supportedTimezones = make([]string, 0) } @@ -335,7 +335,7 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -389,7 +389,7 @@ func getRedirectLocation(c *Context, w http.ResponseWriter, r *http.Request) { return } - client := c.App.HTTPService.MakeClient(false) + client := c.App.HTTPService().MakeClient(false) client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } @@ -431,7 +431,7 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { if ack.IsIdLoaded { if err != nil { // Log the error only, then continue to fetch notification message - c.App.NotificationsLog.Error("Notification ack not sent to push proxy", + c.App.NotificationsLog().Error("Notification ack not sent to push proxy", mlog.String("ackId", ack.Id), mlog.String("type", ack.NotificationType), mlog.String("postId", ack.PostId), @@ -439,14 +439,14 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { ) } - notificationInterface := c.App.Notification + notificationInterface := c.App.Notification() if notificationInterface == nil { c.Err = model.NewAppError("pushNotificationAck", "api.system.id_loaded.not_available.app_error", nil, "", http.StatusFound) return } - msg, appError := notificationInterface.GetNotificationMessage(ack, c.App.Session.UserId) + msg, appError := notificationInterface.GetNotificationMessage(ack, c.App.Session().UserId) if appError != nil { c.Err = model.NewAppError("pushNotificationAck", "api.push_notification.id_loaded.fetch.app_error", nil, appError.Error(), http.StatusInternalServerError) return @@ -464,7 +464,7 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { } func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -481,25 +481,25 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.Srv.Busy.Set(time.Second * time.Duration(i)) + c.App.Srv().Busy.Set(time.Second * time.Duration(i)) mlog.Warn("server busy state activated - non-critical services disabled", mlog.Int64("seconds", i)) ReturnStatusOK(w) } func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - c.App.Srv.Busy.Clear() + c.App.Srv().Busy.Clear() mlog.Info("server busy state cleared - non-critical services enabled") ReturnStatusOK(w) } func getServerBusyExpires(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - w.Write([]byte(c.App.Srv.Busy.ToJson())) + w.Write([]byte(c.App.Srv().Busy.ToJson())) } diff --git a/api4/system_test.go b/api4/system_test.go index 9edb8157ca..9076e2609c 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -451,7 +451,7 @@ func TestSupportedTimezones(t *testing.T) { defer th.TearDown() Client := th.Client - supportedTimezonesFromConfig := th.App.Timezones.GetSupported() + supportedTimezonesFromConfig := th.App.Timezones().GetSupported() supportedTimezones, resp := Client.GetSupportedTimezone() CheckNoError(t, resp) @@ -524,14 +524,14 @@ func TestSetServerBusy(t *testing.T) { ok, resp := th.Client.SetServerBusy(secs) CheckForbiddenStatus(t, resp) require.False(t, ok, "should not set server busy due to no permission") - require.False(t, th.App.Srv.Busy.IsBusy(), "server should not be marked busy") + require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") }) t.Run("as system admin", func(t *testing.T) { ok, resp := th.SystemAdminClient.SetServerBusy(secs) CheckNoError(t, resp) require.True(t, ok, "should set server busy successfully") - require.True(t, th.App.Srv.Busy.IsBusy(), "server should be marked busy") + require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") }) } @@ -545,7 +545,7 @@ func TestSetServerBusyInvalidParam(t *testing.T) { ok, resp := th.SystemAdminClient.SetServerBusy(p) CheckBadRequestStatus(t, resp) require.False(t, ok, "should not set server busy due to invalid param ", p) - require.False(t, th.App.Srv.Busy.IsBusy(), "server should not be marked busy due to invalid param ", p) + require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy due to invalid param ", p) } }) } @@ -554,20 +554,20 @@ func TestClearServerBusy(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.Srv.Busy.Set(time.Second * 30) + th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { ok, resp := th.Client.ClearServerBusy() CheckForbiddenStatus(t, resp) require.False(t, ok, "should not clear server busy flag due to no permission.") - require.True(t, th.App.Srv.Busy.IsBusy(), "server should be marked busy") + require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") }) - th.App.Srv.Busy.Set(time.Second * 30) + th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system admin", func(t *testing.T) { ok, resp := th.SystemAdminClient.ClearServerBusy() CheckNoError(t, resp) require.True(t, ok, "should clear server busy flag successfully") - require.False(t, th.App.Srv.Busy.IsBusy(), "server should not be marked busy") + require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") }) } @@ -575,7 +575,7 @@ func TestGetServerBusyExpires(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.Srv.Busy.Set(time.Second * 30) + th.App.Srv().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { _, resp := th.Client.GetServerBusyExpires() @@ -593,7 +593,7 @@ func TestServerBusy503(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.Srv.Busy.Set(time.Second * 30) + th.App.Srv().Busy.Set(time.Second * 30) t.Run("search users while busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} @@ -619,7 +619,7 @@ func TestServerBusy503(t *testing.T) { CheckServiceUnavailableStatus(t, resp) }) - th.App.Srv.Busy.Clear() + th.App.Srv().Busy.Clear() t.Run("search users while not busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} diff --git a/api4/team.go b/api4/team.go index 4a72bd10af..b7e5f76bab 100644 --- a/api4/team.go +++ b/api4/team.go @@ -81,12 +81,12 @@ func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { } team.Email = strings.ToLower(team.Email) - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_TEAM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_TEAM) { c.Err = model.NewAppError("createTeam", "api.team.is_team_creation_allowed.disabled.app_error", nil, "", http.StatusForbidden) return } - rteam, err := c.App.CreateTeamWithUser(team, c.App.Session.UserId) + rteam, err := c.App.CreateTeamWithUser(team, c.App.Session().UserId) if err != nil { c.Err = err return @@ -110,12 +110,12 @@ func getTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(c.App.Session, team.Id, model.PERMISSION_VIEW_TEAM) { + if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.App.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - c.App.SanitizeTeam(c.App.Session, team) + c.App.SanitizeTeam(*c.App.Session(), team) w.Write([]byte(team.ToJson())) } @@ -131,12 +131,12 @@ func getTeamByName(c *Context, w http.ResponseWriter, r *http.Request) { return } - if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(c.App.Session, team.Id, model.PERMISSION_VIEW_TEAM) { + if (!team.AllowOpenInvite || team.Type != model.TEAM_OPEN) && !c.App.SessionHasPermissionToTeam(*c.App.Session(), team.Id, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - c.App.SanitizeTeam(c.App.Session, team) + c.App.SanitizeTeam(*c.App.Session(), team) w.Write([]byte(team.ToJson())) } @@ -160,7 +160,7 @@ func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -171,7 +171,7 @@ func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeam(c.App.Session, updatedTeam) + c.App.SanitizeTeam(*c.App.Session(), updatedTeam) w.Write([]byte(updatedTeam.ToJson())) } @@ -188,7 +188,7 @@ func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -200,7 +200,7 @@ func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeam(c.App.Session, patchedTeam) + c.App.SanitizeTeam(*c.App.Session(), patchedTeam) c.LogAudit("") w.Write([]byte(patchedTeam.ToJson())) @@ -212,7 +212,7 @@ func regenerateTeamInviteId(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -223,7 +223,7 @@ func regenerateTeamInviteId(c *Context, w http.ResponseWriter, r *http.Request) return } - c.App.SanitizeTeam(c.App.Session, patchedTeam) + c.App.SanitizeTeam(*c.App.Session(), patchedTeam) c.LogAudit("") w.Write([]byte(patchedTeam.ToJson())) @@ -235,7 +235,7 @@ func deleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -261,7 +261,7 @@ func getTeamsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -272,7 +272,7 @@ func getTeamsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(c.App.Session, teams) + c.App.SanitizeTeams(*c.App.Session(), teams) w.Write([]byte(model.TeamListToJson(teams))) } @@ -282,7 +282,7 @@ func getTeamsUnreadForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -305,12 +305,12 @@ func getTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -336,12 +336,12 @@ func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -362,12 +362,12 @@ func getTeamMembersForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -400,12 +400,12 @@ func getTeamMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -438,7 +438,7 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if member.UserId == c.App.Session.UserId { + if member.UserId == c.App.Session().UserId { var team *model.Team team, err = c.App.GetTeam(member.TeamId) if err != nil { @@ -446,16 +446,16 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if team.AllowOpenInvite && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_JOIN_PUBLIC_TEAMS) { + if team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_JOIN_PUBLIC_TEAMS) { c.SetPermissionError(model.PERMISSION_JOIN_PUBLIC_TEAMS) return } - if !team.AllowOpenInvite && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_JOIN_PRIVATE_TEAMS) { + if !team.AllowOpenInvite && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_JOIN_PRIVATE_TEAMS) { c.SetPermissionError(model.PERMISSION_JOIN_PRIVATE_TEAMS) return } } else { - if !c.App.SessionHasPermissionToTeam(c.App.Session, member.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), member.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) return } @@ -502,14 +502,14 @@ func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request) var err *model.AppError if len(tokenId) > 0 { - member, err = c.App.AddTeamMemberByToken(c.App.Session.UserId, tokenId) + member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId) } else if len(inviteId) > 0 { - if c.App.Session.Props[model.SESSION_PROP_IS_GUEST] == "true" { + if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { c.Err = model.NewAppError("addUserToTeamFromInvite", "api.team.add_user_to_team_from_invite.guest.app_error", nil, "", http.StatusForbidden) return } - member, err = c.App.AddTeamMemberByInviteId(inviteId, c.App.Session.UserId) + member, err = c.App.AddTeamMemberByInviteId(inviteId, c.App.Session().UserId) } else { err = model.NewAppError("addTeamMember", "api.team.add_user_to_team.missing_parameter.app_error", nil, "", http.StatusBadRequest) } @@ -586,12 +586,12 @@ func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { userIds = append(userIds, member.UserId) } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) return } - membersWithErrors, err := c.App.AddTeamMembers(c.Params.TeamId, userIds, c.App.Session.UserId, graceful) + membersWithErrors, err := c.App.AddTeamMembers(c.Params.TeamId, userIds, c.App.Session().UserId, graceful) if err != nil { c.Err = err @@ -615,8 +615,8 @@ func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId != c.Params.UserId { - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_REMOVE_USER_FROM_TEAM) { + if c.App.Session().UserId != c.Params.UserId { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_REMOVE_USER_FROM_TEAM) { c.SetPermissionError(model.PERMISSION_REMOVE_USER_FROM_TEAM) return } @@ -634,12 +634,12 @@ func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if team.IsGroupConstrained() && (c.Params.UserId != c.App.Session.UserId) && !user.IsBot { + if team.IsGroupConstrained() && (c.Params.UserId != c.App.Session().UserId) && !user.IsBot { c.Err = model.NewAppError("removeTeamMember", "api.team.remove_member.group_constrained.app_error", nil, "", http.StatusBadRequest) return } - if err := c.App.RemoveUserFromTeam(c.Params.TeamId, c.Params.UserId, c.App.Session.UserId); err != nil { + if err := c.App.RemoveUserFromTeam(c.Params.TeamId, c.Params.UserId, c.App.Session().UserId); err != nil { c.Err = err return } @@ -653,12 +653,12 @@ func getTeamUnread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -678,12 +678,12 @@ func getTeamStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -712,7 +712,7 @@ func updateTeamMemberRoles(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } @@ -737,7 +737,7 @@ func updateTeamMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.Requ return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } @@ -755,19 +755,19 @@ func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError var teamsWithCount *model.TeamsWithCount - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PUBLIC_TEAMS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { teams, err = c.App.GetAllTeamsPage(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PRIVATE_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllPrivateTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { teams, err = c.App.GetAllPrivateTeamsPage(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PUBLIC_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { if c.Params.IncludeTotalCount { teamsWithCount, err = c.App.GetAllPublicTeamsPageWithCount(c.Params.Page*c.Params.PerPage, c.Params.PerPage) } else { @@ -780,7 +780,7 @@ func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(c.App.Session, teams) + c.App.SanitizeTeams(*c.App.Session(), teams) var resBody []byte @@ -809,15 +809,15 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { var totalCount int64 var err *model.AppError - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PUBLIC_TEAMS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { teams, totalCount, err = c.App.SearchAllTeams(props) - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PRIVATE_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.private_team_search", nil, "", http.StatusNotImplemented) return } teams, err = c.App.SearchPrivateTeams(props.Term) - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PUBLIC_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { if props.Page != nil || props.PerPage != nil { c.Err = model.NewAppError("searchTeams", "api.team.search_teams.pagination_not_implemented.public_team_search", nil, "", http.StatusNotImplemented) return @@ -832,7 +832,7 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(c.App.Session, teams) + c.App.SanitizeTeams(*c.App.Session(), teams) var payload []byte if props.Page != nil && props.PerPage != nil { @@ -861,7 +861,7 @@ func teamExists(c *Context, w http.ResponseWriter, r *http.Request) { if team != nil { var teamMember *model.TeamMember - teamMember, err = c.App.GetTeamMember(team.Id, c.App.Session.UserId) + teamMember, err = c.App.GetTeamMember(team.Id, c.App.Session().UserId) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err return @@ -869,8 +869,8 @@ func teamExists(c *Context, w http.ResponseWriter, r *http.Request) { // Verify that the user can see the team (be a member or have the permission to list the team) if (teamMember != nil && teamMember.DeleteAt == 0) || - (team.AllowOpenInvite && c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PUBLIC_TEAMS)) || - (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_PRIVATE_TEAMS)) { + (team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS)) || + (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS)) { exists = true } } @@ -885,7 +885,7 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_IMPORT_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_IMPORT_TEAM) { c.SetPermissionError(model.PERMISSION_IMPORT_TEAM) return } @@ -960,12 +960,12 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_INVITE_USER) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_INVITE_USER) { c.SetPermissionError(model.PERMISSION_INVITE_USER) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_INVITE_USER) return } @@ -981,7 +981,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { } if graceful { - invitesWithError, err := c.App.InviteNewUsersToTeamGracefully(emailList, c.Params.TeamId, c.App.Session.UserId) + invitesWithError, err := c.App.InviteNewUsersToTeamGracefully(emailList, c.Params.TeamId, c.App.Session().UserId) if err != nil { c.Err = err return @@ -989,7 +989,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { // in graceful mode we return both the succesful ones and the failed ones w.Write([]byte(model.EmailInviteWithErrorToJson(invitesWithError))) } else { - err := c.App.InviteNewUsersToTeam(emailList, c.Params.TeamId, c.App.Session.UserId) + err := c.App.InviteNewUsersToTeam(emailList, c.Params.TeamId, c.App.Session().UserId) if err != nil { c.Err = err return @@ -1015,7 +1015,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { c.SetPermissionError(model.PERMISSION_INVITE_GUEST) return } @@ -1030,7 +1030,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) } if graceful { - invitesWithError, err := c.App.InviteGuestsToChannelsGracefully(c.Params.TeamId, guestsInvite, c.App.Session.UserId) + invitesWithError, err := c.App.InviteGuestsToChannelsGracefully(c.Params.TeamId, guestsInvite, c.App.Session().UserId) if err != nil { c.Err = err return @@ -1038,7 +1038,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) // in graceful mode we return both the succesful ones and the failed ones w.Write([]byte(model.EmailInviteWithErrorToJson(invitesWithError))) } else { - err := c.App.InviteGuestsToChannels(c.Params.TeamId, guestsInvite, c.App.Session.UserId) + err := c.App.InviteGuestsToChannels(c.Params.TeamId, guestsInvite, c.App.Session().UserId) if err != nil { c.Err = err return @@ -1073,7 +1073,7 @@ func getInviteInfo(c *Context, w http.ResponseWriter, r *http.Request) { } func invalidateAllEmailInvites(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1099,7 +1099,7 @@ func getTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_VIEW_TEAM) && + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) && (team.Type != model.TEAM_OPEN || !team.AllowOpenInvite) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return @@ -1131,7 +1131,7 @@ func setTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -1176,7 +1176,7 @@ func removeTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -1207,7 +1207,7 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1264,7 +1264,7 @@ func teamMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http.Req groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/team_test.go b/api4/team_test.go index 1fb24e2ba8..a40e49e1e4 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -1457,7 +1457,7 @@ func TestAddTeamMember(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": team.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) tm, resp = Client.AddTeamMemberFromInvite(token.Token, "") CheckNoError(t, resp) @@ -1468,7 +1468,7 @@ func TestAddTeamMember(t *testing.T) { require.Equal(t, tm.TeamId, team.Id, "team ids should have matched") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") tm, resp = Client.AddTeamMemberFromInvite("junk", "") @@ -1479,7 +1479,7 @@ func TestAddTeamMember(t *testing.T) { // expired token of more than 50 hours token = model.NewToken(app.TOKEN_TYPE_TEAM_INVITATION, "") token.CreateAt = model.GetMillis() - 1000*60*60*50 - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, resp = Client.AddTeamMemberFromInvite(token.Token, "") CheckBadRequestStatus(t, resp) @@ -1491,7 +1491,7 @@ func TestAddTeamMember(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": testId}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, resp = Client.AddTeamMemberFromInvite(token.Token, "") CheckNotFoundStatus(t, resp) @@ -1533,7 +1533,7 @@ func TestAddTeamMember(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": team.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) tm, resp = Client.AddTeamMemberFromInvite(token.Token, "") require.Equal(t, "app.team.invite_token.group_constrained.error", resp.Error.Id) diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 681ca3e7d5..f8a95239e7 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -26,7 +26,7 @@ func getLatestTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) } func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -38,7 +38,7 @@ func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) text := props["text"] - userId := c.App.Session.UserId + userId := c.App.Session().UserId if text == "" { c.Err = model.NewAppError("Config.IsValid", "api.create_terms_of_service.empty_text.app_error", nil, "", http.StatusBadRequest) diff --git a/api4/user.go b/api4/user.go index 78a53f6511..278c62d386 100644 --- a/api4/user.go +++ b/api4/user.go @@ -98,7 +98,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if len(tokenId) > 0 { var token *model.Token - token, err = c.App.Srv.Store.Token().GetByToken(tokenId) + token, err = c.App.Srv().Store.Token().GetByToken(tokenId) if err != nil { c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_invalid.app_error", nil, err.Error(), http.StatusBadRequest) return @@ -138,7 +138,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) return @@ -155,7 +155,7 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.IsSystemAdmin() || c.App.Session.UserId == user.Id { + if c.IsSystemAdmin() || c.App.Session().UserId == user.Id { userTermsOfService, err := c.App.GetUserTermsOfService(user.Id) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err @@ -174,12 +174,12 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId == user.Id { + if c.App.Session().UserId == user.Id { user.Sanitize(map[string]bool{}) } else { c.App.SanitizeProfile(user, c.IsSystemAdmin()) } - c.App.UpdateLastActivityAtIfNeeded(c.App.Session) + c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Write([]byte(user.ToJson())) } @@ -192,7 +192,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { user, err := c.App.GetUserByUsername(c.Params.Username) if err != nil { - restrictions, err2 := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err2 := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err2 != nil { c.Err = err2 return @@ -205,7 +205,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, user.Id) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, user.Id) if err != nil { c.Err = err return @@ -216,7 +216,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.IsSystemAdmin() || c.App.Session.UserId == user.Id { + if c.IsSystemAdmin() || c.App.Session().UserId == user.Id { userTermsOfService, err := c.App.GetUserTermsOfService(user.Id) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err @@ -235,7 +235,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.UserId == user.Id { + if c.App.Session().UserId == user.Id { user.Sanitize(map[string]bool{}) } else { c.App.SanitizeProfile(user, c.IsSystemAdmin()) @@ -252,13 +252,13 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { sanitizeOptions := c.App.GetSanitizeOptions(c.IsSystemAdmin()) if !sanitizeOptions["email"] { - c.Err = model.NewAppError("getUserByEmail", "api.user.get_user_by_email.permissions.app_error", nil, "userId="+c.App.Session.UserId, http.StatusForbidden) + c.Err = model.NewAppError("getUserByEmail", "api.user.get_user_by_email.permissions.app_error", nil, "userId="+c.App.Session().UserId, http.StatusForbidden) return } user, err := c.App.GetUserByEmail(c.Params.Email) if err != nil { - restrictions, err2 := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err2 := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err2 != nil { c.Err = err2 return @@ -271,7 +271,7 @@ func getUserByEmail(c *Context, w http.ResponseWriter, r *http.Request) { return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, user.Id) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, user.Id) if err != nil { c.Err = err return @@ -299,7 +299,7 @@ func getDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request) return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -333,7 +333,7 @@ func getProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -380,7 +380,7 @@ func setProfileImage(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -428,7 +428,7 @@ func setDefaultProfileImage(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -458,7 +458,7 @@ func getTotalUsersStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -527,7 +527,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { groupConstrainedBool, _ := strconv.ParseBool(groupConstrained) inactiveBool, _ := strconv.ParseBool(inactive) - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -553,21 +553,21 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { if withoutTeamBool, _ := strconv.ParseBool(withoutTeam); withoutTeamBool { // Use a special permission for now - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_LIST_USERS_WITHOUT_TEAM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_USERS_WITHOUT_TEAM) { c.SetPermissionError(model.PERMISSION_LIST_USERS_WITHOUT_TEAM) return } profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) } else if len(notInChannelId) > 0 { - if !c.App.SessionHasPermissionToChannel(c.App.Session, notInChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } profiles, err = c.App.GetUsersNotInChannelPage(inTeamId, notInChannelId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) } else if len(notInTeamId) > 0 { - if !c.App.SessionHasPermissionToTeam(c.App.Session, notInTeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -579,7 +579,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersNotInTeamPage(notInTeamId, groupConstrainedBool, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin(), restrictions) } else if len(inTeamId) > 0 { - if !c.App.SessionHasPermissionToTeam(c.App.Session, inTeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -596,7 +596,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } } else if len(inChannelId) > 0 { - if !c.App.SessionHasPermissionToChannel(c.App.Session, inChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -606,7 +606,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersInChannelPage(inChannelId, c.Params.Page, c.Params.PerPage, c.IsSystemAdmin()) } } else { - userGetOptions, err = c.App.RestrictUsersGetByPermissions(c.App.Session.UserId, userGetOptions) + userGetOptions, err = c.App.RestrictUsersGetByPermissions(c.App.Session().UserId, userGetOptions) if err != nil { c.Err = err return @@ -622,7 +622,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { if len(etag) > 0 { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } - c.App.UpdateLastActivityAtIfNeeded(c.App.Session) + c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) w.Write([]byte(model.UserListToJson(profiles))) } @@ -649,7 +649,7 @@ func getUsersByIds(c *Context, w http.ResponseWriter, r *http.Request) { options.Since = since } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -673,7 +673,7 @@ func getUsersByNames(c *Context, w http.ResponseWriter, r *http.Request) { return } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session.UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) if err != nil { c.Err = err return @@ -705,22 +705,22 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(c.App.Session, props.InChannelId, model.PERMISSION_READ_CHANNEL) { + if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.App.Session(), props.InChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } - if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(c.App.Session, props.NotInChannelId, model.PERMISSION_READ_CHANNEL) { + if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.App.Session(), props.NotInChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } - if props.TeamId != "" && !c.App.SessionHasPermissionToTeam(c.App.Session, props.TeamId, model.PERMISSION_VIEW_TEAM) { + if props.TeamId != "" && !c.App.SessionHasPermissionToTeam(*c.App.Session(), props.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - if props.NotInTeamId != "" && !c.App.SessionHasPermissionToTeam(c.App.Session, props.NotInTeamId, model.PERMISSION_VIEW_TEAM) { + if props.NotInTeamId != "" && !c.App.SessionHasPermissionToTeam(*c.App.Session(), props.NotInTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -738,7 +738,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { Role: props.Role, } - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { options.AllowEmails = true options.AllowFullNames = true } else { @@ -746,7 +746,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName } - options, err := c.App.RestrictUsersSearchByPermissions(c.App.Session.UserId, options) + options, err := c.App.RestrictUsersSearchByPermissions(c.App.Session().UserId, options) if err != nil { c.Err = err return @@ -780,21 +780,21 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { Limit: limit, } - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { options.AllowFullNames = true } else { options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName } if len(channelId) > 0 { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } } if len(teamId) > 0 { - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -803,7 +803,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { var autocomplete model.UserAutocomplete var err *model.AppError - options, err = c.App.RestrictUsersSearchByPermissions(c.App.Session.UserId, options) + options, err = c.App.RestrictUsersSearchByPermissions(c.App.Session().UserId, options) if err != nil { c.Err = err return @@ -859,7 +859,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, user.Id) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), user.Id) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -870,7 +870,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { if ouser.Email != user.Email { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted email update by oauth app" @@ -879,7 +879,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { } // If eMail update is attempted by the currently logged in user, check if correct password was provided - if user.Email != "" && ouser.Email != user.Email && c.App.Session.UserId == c.Params.UserId { + if user.Email != "" && ouser.Email != user.Email && c.App.Session().UserId == c.Params.UserId { err = c.App.DoubleCheckPassword(ouser, user.Password) if err != nil { c.SetInvalidParam("password") @@ -909,7 +909,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -920,7 +920,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth && patch.Email != nil { + if c.App.Session().IsOAuth && patch.Email != nil { if ouser.Email != *patch.Email { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted email update by oauth app" @@ -929,7 +929,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { } // If eMail update is attempted by the currently logged in user, check if correct password was provided - if patch.Email != nil && ouser.Email != *patch.Email && c.App.Session.UserId == c.Params.UserId { + if patch.Email != nil && ouser.Email != *patch.Email && c.App.Session().UserId == c.Params.UserId { if patch.Password == nil { c.SetInvalidParam("password") return @@ -960,13 +960,13 @@ func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { userId := c.Params.UserId - if !c.App.SessionHasPermissionToUser(c.App.Session, userId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), userId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } // if EnableUserDeactivation flag is disabled the user cannot deactivate himself. - if c.Params.UserId == c.App.Session.UserId && !*c.App.Config().TeamSettings.EnableUserDeactivation && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if c.Params.UserId == c.App.Session().UserId && !*c.App.Config().TeamSettings.EnableUserDeactivation && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.Err = model.NewAppError("deleteUser", "api.user.update_active.not_enable.app_error", nil, "userId="+c.Params.UserId, http.StatusUnauthorized) return } @@ -999,7 +999,7 @@ func updateUserRoles(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_ROLES) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_ROLES) return } @@ -1028,9 +1028,9 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { } // true when you're trying to de-activate yourself - isSelfDeactive := !active && c.Params.UserId == c.App.Session.UserId + isSelfDeactive := !active && c.Params.UserId == c.App.Session().UserId - if !isSelfDeactive && !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !isSelfDeactive && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.Err = model.NewAppError("updateUserActive", "api.user.update_active.permissions.app_error", nil, "userId="+c.Params.UserId, http.StatusForbidden) return } @@ -1058,7 +1058,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit(fmt.Sprintf("user_id=%s active=%v", user.Id, active)) if isSelfDeactive { - c.App.Srv.Go(func() { + c.App.Srv().Go(func() { if err = c.App.SendDeactivateAccountEmail(user.Email, user.Locale, c.App.GetSiteURL()); err != nil { mlog.Error(err.Error()) } @@ -1134,13 +1134,13 @@ func updateUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted access by oauth app" return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1178,13 +1178,13 @@ func generateMfaSecret(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted access by oauth app" return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1213,7 +1213,7 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempted") var err *model.AppError - if c.Params.UserId == c.App.Session.UserId { + if c.Params.UserId == c.App.Session().UserId { currentPassword := props["current_password"] if len(currentPassword) <= 0 { c.SetInvalidParam("current_password") @@ -1221,7 +1221,7 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { } err = c.App.UpdatePasswordAsUser(c.Params.UserId, currentPassword, newPassword) - } else if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { err = c.App.UpdatePasswordByUserIdSendEmail(c.Params.UserId, newPassword, c.App.T("api.user.reset_password.method")) } else { err = model.NewAppError("updatePassword", "api.user.update_password.context.app_error", nil, "", http.StatusForbidden) @@ -1431,8 +1431,8 @@ func logout(c *Context, w http.ResponseWriter, r *http.Request) { func Logout(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") c.RemoveSessionCookie(w, r) - if c.App.Session.Id != "" { - if err := c.App.RevokeSessionById(c.App.Session.Id); err != nil { + if c.App.Session().Id != "" { + if err := c.App.RevokeSessionById(c.App.Session().Id); err != nil { c.Err = err return } @@ -1447,7 +1447,7 @@ func getSessions(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1471,7 +1471,7 @@ func revokeSession(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1508,7 +1508,7 @@ func revokeAllSessionsForUser(c *Context, w http.ResponseWriter, r *http.Request return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1522,7 +1522,7 @@ func revokeAllSessionsForUser(c *Context, w http.ResponseWriter, r *http.Request } func revokeAllSessionsAllUsers(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1545,13 +1545,13 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { } // A special case where we logout of all other sessions with the same device id - if err := c.App.RevokeSessionsForDeviceId(c.App.Session.UserId, deviceId, c.App.Session.Id); err != nil { + if err := c.App.RevokeSessionsForDeviceId(c.App.Session().UserId, deviceId, c.App.Session().Id); err != nil { c.Err = err return } - c.App.ClearSessionCacheForUser(c.App.Session.UserId) - c.App.Session.SetExpireInDays(*c.App.Config().ServiceSettings.SessionLengthMobileInDays) + c.App.ClearSessionCacheForUser(c.App.Session().UserId) + c.App.Session().SetExpireInDays(*c.App.Config().ServiceSettings.SessionLengthMobileInDays) maxAge := *c.App.Config().ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 @@ -1565,7 +1565,7 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0) sessionCookie := &http.Cookie{ Name: model.SESSION_COOKIE_TOKEN, - Value: c.App.Session.Token, + Value: c.App.Session().Token, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -1576,7 +1576,7 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { http.SetCookie(w, sessionCookie) - if err := c.App.AttachDeviceId(c.App.Session.Id, deviceId, c.App.Session.ExpiresAt); err != nil { + if err := c.App.AttachDeviceId(c.App.Session().Id, deviceId, c.App.Session().ExpiresAt); err != nil { c.Err = err return } @@ -1591,7 +1591,7 @@ func getUserAudits(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1668,7 +1668,7 @@ func switchAccountType(c *Context, w http.ResponseWriter, r *http.Request) { return } - link, err = c.App.SwitchOAuthToEmail(switchRequest.Email, switchRequest.NewPassword, c.App.Session.UserId) + link, err = c.App.SwitchOAuthToEmail(switchRequest.Email, switchRequest.NewPassword, c.App.Session().UserId) } else if switchRequest.EmailToLdap() { link, err = c.App.SwitchEmailToLdap(switchRequest.Email, switchRequest.Password, switchRequest.MfaCode, switchRequest.LdapLoginId, switchRequest.NewPassword) } else if switchRequest.LdapToEmail() { @@ -1693,7 +1693,7 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) c.Err.DetailedError += ", attempted access by oauth app" return @@ -1712,12 +1712,12 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1736,7 +1736,7 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { } func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1761,7 +1761,7 @@ func searchUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) } func getUserAccessTokens(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1781,12 +1781,12 @@ func getUserAccessTokensForUser(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_READ_USER_ACCESS_TOKEN) return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, c.Params.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1806,7 +1806,7 @@ func getUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_READ_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_READ_USER_ACCESS_TOKEN) return } @@ -1817,7 +1817,7 @@ func getUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1835,7 +1835,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) return } @@ -1846,7 +1846,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1871,7 +1871,7 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) c.LogAudit("") // No separate permission for this action for now - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) return } @@ -1882,7 +1882,7 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1907,7 +1907,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("") // No separate permission for this action for now - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) return } @@ -1918,7 +1918,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUserOrBot(c.App.Session, accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1935,7 +1935,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { func saveUserTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { props := model.StringInterfaceFromJson(r.Body) - userId := c.App.Session.UserId + userId := c.App.Session().UserId termsOfServiceId := props["termsOfServiceId"].(string) accepted := props["accepted"].(bool) @@ -1954,7 +1954,7 @@ func saveUserTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) } func getUserTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { - userId := c.App.Session.UserId + userId := c.App.Session().UserId result, err := c.App.GetUserTermsOfService(userId) if err != nil { c.Err = err @@ -1969,7 +1969,7 @@ func promoteGuestToUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_PROMOTE_GUEST) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_PROMOTE_GUEST) { c.SetPermissionError(model.PERMISSION_PROMOTE_GUEST) return } @@ -1985,7 +1985,7 @@ func promoteGuestToUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := c.App.PromoteGuestToUser(user, c.App.Session.UserId); err != nil { + if err := c.App.PromoteGuestToUser(user, c.App.Session().UserId); err != nil { c.Err = err return } @@ -2009,7 +2009,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_DEMOTE_TO_GUEST) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DEMOTE_TO_GUEST) { c.SetPermissionError(model.PERMISSION_DEMOTE_TO_GUEST) return } diff --git a/api4/user_test.go b/api4/user_test.go index ecd9341822..a7752427b4 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -155,7 +155,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) ruser, resp := th.Client.CreateUserWithToken(&user, token.Token) CheckNoError(t, resp) @@ -165,7 +165,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Equal(t, user.Nickname, ruser.Nickname) require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) - _, err := th.App.Srv.Store.Token().GetByToken(token.Token) + _, err := th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after being used") teams, err := th.App.GetTeamsForUser(ruser.Id) @@ -180,7 +180,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, resp := th.Client.CreateUserWithToken(&user, "") @@ -197,7 +197,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) token.CreateAt = past49Hours - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, resp := th.Client.CreateUserWithToken(&user, token.Token) @@ -226,7 +226,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false }) @@ -244,7 +244,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) enableOpenServer := th.App.Config().TeamSettings.EnableOpenServer defer func() { @@ -261,7 +261,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Equal(t, user.Nickname, ruser.Nickname) require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) - _, err := th.App.Srv.Store.Token().GetByToken(token.Token) + _, err := th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") }) } @@ -1558,7 +1558,7 @@ func TestUpdateUserAuth(t *testing.T) { user := th.CreateUser() th.LinkUserToTeam(user, team) - _, err := th.App.Srv.Store.User().VerifyEmail(user.Id, user.Email) + _, err := th.App.Srv().Store.User().VerifyEmail(user.Id, user.Email) require.Nil(t, err) userAuth := &model.UserAuth{} @@ -1591,7 +1591,7 @@ func TestUpdateUserAuth(t *testing.T) { // Regular user can not use endpoint user2 := th.CreateUser() th.LinkUserToTeam(user2, team) - _, err = th.App.Srv.Store.User().VerifyEmail(user2.Id, user2.Email) + _, err = th.App.Srv().Store.User().VerifyEmail(user2.Id, user2.Email) require.Nil(t, err) th.SystemAdminClient.Login(user2.Email, "passwd1") @@ -1742,7 +1742,7 @@ func TestUpdateUserActive(t *testing.T) { CheckNoError(t, resp) authData := model.NewId() - _, err := th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) + _, err := th.App.Srv().Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) require.Nil(t, err) _, resp = th.SystemAdminClient.UpdateUserActive(user.Id, false) @@ -1933,7 +1933,7 @@ func TestGetUsersWithoutTeam(t *testing.T) { }) CheckNoError(t, resp) th.LinkUserToTeam(user, th.BasicTeam) - defer th.App.Srv.Store.User().PermanentDelete(user.Id) + defer th.App.Srv().Store.User().PermanentDelete(user.Id) user2, resp := th.Client.CreateUser(&model.User{ Username: "a000000001" + model.NewId(), @@ -1941,7 +1941,7 @@ func TestGetUsersWithoutTeam(t *testing.T) { Password: "Password1", }) CheckNoError(t, resp) - defer th.App.Srv.Store.User().PermanentDelete(user2.Id) + defer th.App.Srv().Store.User().PermanentDelete(user2.Id) rusers, resp := th.SystemAdminClient.GetUsersWithoutTeam(0, 100, "") CheckNoError(t, resp) @@ -2377,7 +2377,7 @@ func TestResetPassword(t *testing.T) { loc += 6 recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] } - recoveryToken, err := th.App.Srv.Store.Token().GetByToken(recoveryTokenString) + recoveryToken, err := th.App.Srv().Store.Token().GetByToken(recoveryTokenString) require.Nil(t, err, "Recovery token not found (%s)", recoveryTokenString) _, resp = th.Client.ResetPassword(recoveryToken.Token, "") @@ -2402,7 +2402,7 @@ func TestResetPassword(t *testing.T) { _, resp = th.Client.ResetPassword(recoveryToken.Token, "newpwd") CheckBadRequestStatus(t, resp) authData := model.NewId() - _, err = th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) + _, err = th.App.Srv().Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) require.Nil(t, err) _, resp = th.Client.SendPasswordResetEmail(user.Email) CheckBadRequestStatus(t, resp) @@ -3074,7 +3074,7 @@ func TestSwitchAccount(t *testing.T) { th.LoginBasic() fakeAuthData := model.NewId() - _, err := th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true) + _, err := th.App.Srv().Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true) require.Nil(t, err) sr = &model.SwitchRequest{ diff --git a/api4/webhook.go b/api4/webhook.go index c5c7a42f09..866810ccdb 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -39,18 +39,18 @@ func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } - if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } - incomingHook, err := c.App.CreateIncomingWebhookForChannel(c.App.Session.UserId, channel, hook) + incomingHook, err := c.App.CreateIncomingWebhookForChannel(c.App.Session().UserId, channel, hook) if err != nil { c.Err = err return @@ -92,7 +92,7 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { } if updatedHook.TeamId != oldHook.TeamId { - c.Err = model.NewAppError("updateIncomingHook", "api.webhook.team_mismatch.app_error", nil, "user_id="+c.App.Session.UserId, http.StatusBadRequest) + c.Err = model.NewAppError("updateIncomingHook", "api.webhook.team_mismatch.app_error", nil, "user_id="+c.App.Session().UserId, http.StatusBadRequest) return } @@ -107,18 +107,18 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } - if c.App.Session.UserId != oldHook.UserId && !c.App.SessionHasPermissionToTeam(c.App.Session, channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.Session().UserId != oldHook.UserId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return } - if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return @@ -137,31 +137,31 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { func getIncomingHooks(c *Context, w http.ResponseWriter, r *http.Request) { teamId := r.URL.Query().Get("team_id") - userId := c.App.Session.UserId + userId := c.App.Session().UserId var hooks []*model.IncomingWebhook var err *model.AppError if len(teamId) > 0 { - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { userId = "" } hooks, err = c.App.GetIncomingWebhooksForTeamPageByUser(teamId, userId, c.Params.Page, c.Params.PerPage) } else { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { userId = "" } @@ -200,14 +200,14 @@ func getIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || - (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || + (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { c.LogAudit("fail - bad permissions") c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } - if c.App.Session.UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return @@ -240,14 +240,14 @@ func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || - (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(c.App.Session, hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || + (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { c.LogAudit("fail - bad permissions") c.SetPermissionError(model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) return } - if c.App.Session.UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if c.App.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return @@ -292,22 +292,22 @@ func updateOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { } if updatedHook.TeamId != oldHook.TeamId { - c.Err = model.NewAppError("updateOutgoingHook", "api.webhook.team_mismatch.app_error", nil, "user_id="+c.App.Session.UserId, http.StatusBadRequest) + c.Err = model.NewAppError("updateOutgoingHook", "api.webhook.team_mismatch.app_error", nil, "user_id="+c.App.Session().UserId, http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToTeam(c.App.Session, updatedHook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), updatedHook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } - if c.App.Session.UserId != oldHook.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, updatedHook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.Session().UserId != oldHook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), updatedHook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return } - updatedHook.CreatorId = c.App.Session.UserId + updatedHook.CreatorId = c.App.Session().UserId rhook, err := c.App.UpdateOutgoingWebhook(oldHook, updatedHook) if err != nil { @@ -328,9 +328,9 @@ func createOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - hook.CreatorId = c.App.Session.UserId + hook.CreatorId = c.App.Session().UserId - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } @@ -350,43 +350,43 @@ func createOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) { channelId := r.URL.Query().Get("channel_id") teamId := r.URL.Query().Get("team_id") - userId := c.App.Session.UserId + userId := c.App.Session().UserId var hooks []*model.OutgoingWebhook var err *model.AppError if len(channelId) > 0 { - if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { userId = "" } hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage) } else if len(teamId) > 0 { - if !c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToTeam(c.App.Session, teamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { userId = "" } hooks, err = c.App.GetOutgoingWebhooksForTeamPageByUser(teamId, userId, c.Params.Page, c.Params.PerPage) } else { - if !c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { userId = "" } @@ -415,12 +415,12 @@ func getOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } - if c.App.Session.UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return @@ -444,12 +444,12 @@ func regenOutgoingHookToken(c *Context, w http.ResponseWriter, r *http.Request) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } - if c.App.Session.UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return @@ -478,12 +478,12 @@ func deleteOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } - if c.App.Session.UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(c.App.Session, hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if c.App.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return diff --git a/api4/websocket.go b/api4/websocket.go index ac8b7fe62a..14876305f3 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -30,9 +30,9 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { return } - wc := c.App.NewWebConn(ws, c.App.Session, c.App.T, "") + wc := c.App.NewWebConn(ws, *c.App.Session(), c.App.T, "") - if len(c.App.Session.UserId) > 0 { + if len(c.App.Session().UserId) > 0 { c.App.HubRegister(wc) } diff --git a/api4/websocket_test.go b/api4/websocket_test.go index 5928852029..16dae3c6f3 100644 --- a/api4/websocket_test.go +++ b/api4/websocket_test.go @@ -81,7 +81,7 @@ func TestWebSocketTrailingSlash(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - url := fmt.Sprintf("ws://localhost:%v", th.App.Srv.ListenAddr.Port) + url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) _, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket/", nil) require.NoError(t, err) } @@ -216,7 +216,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - url := fmt.Sprintf("ws://localhost:%v", th.App.Srv.ListenAddr.Port) + url := fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port) // Should fail because origin doesn't match _, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ @@ -227,7 +227,7 @@ func TestWebsocketOriginSecurity(t *testing.T) { // We are not a browser so we can spoof this just fine _, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{ - "Origin": []string{fmt.Sprintf("http://localhost:%v", th.App.Srv.ListenAddr.Port)}, + "Origin": []string{fmt.Sprintf("http://localhost:%v", th.App.Srv().ListenAddr.Port)}, }) require.Nil(t, err, err) @@ -282,13 +282,13 @@ func TestWebSocketStatuses(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"} ruser := Client.Must(Client.CreateUser(&user)).(*model.User) th.LinkUserToTeam(ruser, rteam) - _, err = th.App.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err = th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) require.Nil(t, err) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"} ruser2 := Client.Must(Client.CreateUser(&user2)).(*model.User) th.LinkUserToTeam(ruser2, rteam) - _, err = th.App.Srv.Store.User().VerifyEmail(ruser2.Id, ruser2.Email) + _, err = th.App.Srv().Store.User().VerifyEmail(ruser2.Id, ruser2.Email) require.Nil(t, err) Client.Login(user.Email, user.Password) diff --git a/app/admin.go b/app/admin.go index fa6a75893e..6a5ad462bb 100644 --- a/app/admin.go +++ b/app/admin.go @@ -21,10 +21,10 @@ import ( func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { var lines []string - if a.Cluster != nil && *a.Config().ClusterSettings.Enable { + if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") - lines = append(lines, a.Cluster.GetMyClusterInfo().Hostname) + lines = append(lines, a.Cluster().GetMyClusterInfo().Hostname) lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") } @@ -36,8 +36,8 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { lines = append(lines, melines...) - if a.Cluster != nil && *a.Config().ClusterSettings.Enable { - clines, err := a.Cluster.GetLogs(page, perPage) + if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { + clines, err := a.Cluster().GetLogs(page, perPage) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { func (a *App) GetClusterStatus() []*model.ClusterInfo { infos := make([]*model.ClusterInfo, 0) - if a.Cluster != nil { - infos = a.Cluster.GetClusterInfos() + if a.Cluster() != nil { + infos = a.Cluster().GetClusterInfos() } return infos @@ -133,7 +133,7 @@ func (a *App) InvalidateAllCaches() *model.AppError { debug.FreeOSMemory() a.InvalidateAllCachesSkipSend() - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, @@ -141,7 +141,7 @@ func (a *App) InvalidateAllCaches() *model.AppError { WaitForAllToSend: true, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } return nil @@ -149,25 +149,25 @@ func (a *App) InvalidateAllCaches() *model.AppError { func (a *App) InvalidateAllCachesSkipSend() { mlog.Info("Purging all caches") - a.Srv.sessionCache.Purge() - a.Srv.statusCache.Purge() - a.Srv.Store.Team().ClearCaches() - a.Srv.Store.Channel().ClearCaches() - a.Srv.Store.User().ClearCaches() - a.Srv.Store.Post().ClearCaches() - a.Srv.Store.FileInfo().ClearCaches() - a.Srv.Store.Webhook().ClearCaches() + a.Srv().sessionCache.Purge() + a.Srv().statusCache.Purge() + a.Srv().Store.Team().ClearCaches() + a.Srv().Store.Channel().ClearCaches() + a.Srv().Store.User().ClearCaches() + a.Srv().Store.Post().ClearCaches() + a.Srv().Store.FileInfo().ClearCaches() + a.Srv().Store.Webhook().ClearCaches() a.LoadLicense() } func (a *App) RecycleDatabaseConnection() { - oldStore := a.Srv.Store + oldStore := a.Srv().Store mlog.Warn("Attempting to recycle the database connection.") - a.Srv.Store = a.Srv.newStore() - a.Srv.Jobs.Store = a.Srv.Store + a.Srv().Store = a.Srv().newStore() + a.Srv().Jobs.Store = a.Srv().Store - if a.Srv.Store != oldStore { + if a.Srv().Store != oldStore { time.Sleep(20 * time.Second) oldStore.Close() } @@ -221,7 +221,7 @@ func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError { // ServerBusyStateChanged is called when a CLUSTER_EVENT_BUSY_STATE_CHANGED is received. func (a *App) ServerBusyStateChanged(sbs *model.ServerBusyState) { - a.Srv.Busy.ClusterEventChanged(sbs) + a.Srv().Busy.ClusterEventChanged(sbs) if sbs.Busy { mlog.Warn("server busy state activitated via cluster event - non-critical services disabled", mlog.Int64("expires_sec", sbs.Expires)) } else { diff --git a/app/analytics.go b/app/analytics.go index 9e423be8ae..9c18905a7a 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -17,7 +17,7 @@ const ( func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) { skipIntensiveQueries := false var systemUserCount int64 - systemUserCount, err := a.Srv.Store.User().Count(model.UserCountOptions{}) + systemUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) if err != nil { return nil, err } @@ -44,12 +44,12 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo openChan := make(chan store.StoreResult, 1) privateChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) + count, err := a.Srv().Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) openChan <- store.StoreResult{Data: count, Err: err} close(openChan) }() go func() { - count, err := a.Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) + count, err := a.Srv().Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) privateChan <- store.StoreResult{Data: count, Err: err} close(privateChan) }() @@ -59,14 +59,14 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo if teamId == "" { userInactiveChan = make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.User().AnalyticsGetInactiveUsersCount() + count, err := a.Srv().Store.User().AnalyticsGetInactiveUsersCount() userInactiveChan <- store.StoreResult{Data: count, Err: err} close(userInactiveChan) }() } else { userChan = make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.User().Count(model.UserCountOptions{TeamId: teamId}) + count, err := a.Srv().Store.User().Count(model.UserCountOptions{TeamId: teamId}) userChan <- store.StoreResult{Data: count, Err: err} close(userChan) }() @@ -76,7 +76,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo if !skipIntensiveQueries { postChan = make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Post().AnalyticsPostCount(teamId, false, false) + count, err := a.Srv().Store.Post().AnalyticsPostCount(teamId, false, false) postChan <- store.StoreResult{Data: count, Err: err} close(postChan) }() @@ -84,21 +84,21 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo teamCountChan := make(chan store.StoreResult, 1) go func() { - teamCount, err := a.Srv.Store.Team().AnalyticsTeamCount(false) + teamCount, err := a.Srv().Store.Team().AnalyticsTeamCount(false) teamCountChan <- store.StoreResult{Data: teamCount, Err: err} close(teamCountChan) }() dailyActiveChan := make(chan store.StoreResult, 1) go func() { - dailyActive, err := a.Srv.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + dailyActive, err := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) dailyActiveChan <- store.StoreResult{Data: dailyActive, Err: err} close(dailyActiveChan) }() monthlyActiveChan := make(chan store.StoreResult, 1) go func() { - monthlyActive, err := a.Srv.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + monthlyActive, err := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) monthlyActiveChan <- store.StoreResult{Data: monthlyActive, Err: err} close(monthlyActiveChan) }() @@ -152,15 +152,15 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo rows[4].Value = float64(r.Data.(int64)) // If in HA mode then aggregrate all the stats - if a.Cluster != nil && *a.Config().ClusterSettings.Enable { - stats, err := a.Cluster.GetClusterStats() + if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { + stats, err := a.Cluster().GetClusterStats() if err != nil { return nil, err } totalSockets := a.TotalWebsocketConnections() - totalMasterDb := a.Srv.Store.TotalMasterDbConnections() - totalReadDb := a.Srv.Store.TotalReadDbConnections() + totalMasterDb := a.Srv().Store.TotalMasterDbConnections() + totalReadDb := a.Srv().Store.TotalReadDbConnections() for _, stat := range stats { totalSockets = totalSockets + stat.TotalWebsocketConnections @@ -174,8 +174,8 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo } else { rows[5].Value = float64(a.TotalWebsocketConnections()) - rows[6].Value = float64(a.Srv.Store.TotalMasterDbConnections()) - rows[7].Value = float64(a.Srv.Store.TotalReadDbConnections()) + rows[6].Value = float64(a.Srv().Store.TotalMasterDbConnections()) + rows[7].Value = float64(a.Srv().Store.TotalReadDbConnections()) } r = <-dailyActiveChan @@ -196,7 +196,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo rows := model.AnalyticsRows{&model.AnalyticsRow{Name: "", Value: -1}} return rows, nil } - return a.Srv.Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ + return a.Srv().Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ TeamId: teamId, BotsOnly: true, YesterdayOnly: false, @@ -206,7 +206,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo rows := model.AnalyticsRows{&model.AnalyticsRow{Name: "", Value: -1}} return rows, nil } - return a.Srv.Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ + return a.Srv().Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ TeamId: teamId, BotsOnly: false, YesterdayOnly: false, @@ -217,7 +217,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo return rows, nil } - return a.Srv.Store.Post().AnalyticsUserCountsWithPostsByDay(teamId) + return a.Srv().Store.Post().AnalyticsUserCountsWithPostsByDay(teamId) } else if name == "extra_counts" { var rows model.AnalyticsRows = make([]*model.AnalyticsRow, 6) rows[0] = &model.AnalyticsRow{Name: "file_post_count", Value: 0} @@ -229,28 +229,28 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo iHookChan := make(chan store.StoreResult, 1) go func() { - c, err := a.Srv.Store.Webhook().AnalyticsIncomingCount(teamId) + c, err := a.Srv().Store.Webhook().AnalyticsIncomingCount(teamId) iHookChan <- store.StoreResult{Data: c, Err: err} close(iHookChan) }() oHookChan := make(chan store.StoreResult, 1) go func() { - c, err := a.Srv.Store.Webhook().AnalyticsOutgoingCount(teamId) + c, err := a.Srv().Store.Webhook().AnalyticsOutgoingCount(teamId) oHookChan <- store.StoreResult{Data: c, Err: err} close(oHookChan) }() commandChan := make(chan store.StoreResult, 1) go func() { - c, err := a.Srv.Store.Command().AnalyticsCommandCount(teamId) + c, err := a.Srv().Store.Command().AnalyticsCommandCount(teamId) commandChan <- store.StoreResult{Data: c, Err: err} close(commandChan) }() sessionChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Session().AnalyticsSessionCount() + count, err := a.Srv().Store.Session().AnalyticsSessionCount() sessionChan <- store.StoreResult{Data: count, Err: err} close(sessionChan) }() @@ -261,14 +261,14 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo if !skipIntensiveQueries { fileChan = make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Post().AnalyticsPostCount(teamId, true, false) + count, err := a.Srv().Store.Post().AnalyticsPostCount(teamId, true, false) fileChan <- store.StoreResult{Data: count, Err: err} close(fileChan) }() hashtagChan = make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Post().AnalyticsPostCount(teamId, false, true) + count, err := a.Srv().Store.Post().AnalyticsPostCount(teamId, false, true) hashtagChan <- store.StoreResult{Data: count, Err: err} close(hashtagChan) }() @@ -325,7 +325,7 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo } func (a *App) GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.User, *model.AppError) { - users, err := a.Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, 0, 100, nil) + users, err := a.Srv().Store.User().GetRecentlyActiveUsersForTeam(teamId, 0, 100, nil) if err != nil { return nil, err } @@ -340,7 +340,7 @@ func (a *App) GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.Us } func (a *App) GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, page*perPage, perPage, viewRestrictions) + users, err := a.Srv().Store.User().GetRecentlyActiveUsersForTeam(teamId, page*perPage, perPage, viewRestrictions) if err != nil { return nil, err } @@ -349,7 +349,7 @@ func (a *App) GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int } func (a *App) GetNewUsersForTeamPage(teamId string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv.Store.User().GetNewUsersForTeam(teamId, page*perPage, perPage, viewRestrictions) + users, err := a.Srv().Store.User().GetNewUsersForTeam(teamId, page*perPage, perPage, viewRestrictions) if err != nil { return nil, err } diff --git a/app/app.go b/app/app.go index 1c0fab26ab..35acbfc00c 100644 --- a/app/app.go +++ b/app/app.go @@ -4,6 +4,7 @@ package app import ( + "context" "html/template" "net/http" "strconv" @@ -20,33 +21,35 @@ import ( ) type App struct { - Srv *Server + srv *Server - Log *mlog.Logger - NotificationsLog *mlog.Logger + log *mlog.Logger + notificationsLog *mlog.Logger - T goi18n.TranslateFunc - Session model.Session - RequestId string - IpAddress string - Path string - UserAgent string - AcceptLanguage string + t goi18n.TranslateFunc + session model.Session + requestId string + ipAddress string + path string + userAgent string + acceptLanguage string - AccountMigration einterfaces.AccountMigrationInterface - Cluster einterfaces.ClusterInterface - Compliance einterfaces.ComplianceInterface - DataRetention einterfaces.DataRetentionInterface - Elasticsearch einterfaces.ElasticsearchInterface - Ldap einterfaces.LdapInterface - MessageExport einterfaces.MessageExportInterface - Metrics einterfaces.MetricsInterface - Notification einterfaces.NotificationInterface - Saml einterfaces.SamlInterface + accountMigration einterfaces.AccountMigrationInterface + cluster einterfaces.ClusterInterface + compliance einterfaces.ComplianceInterface + dataRetention einterfaces.DataRetentionInterface + elasticsearch einterfaces.ElasticsearchInterface + ldap einterfaces.LdapInterface + messageExport einterfaces.MessageExportInterface + metrics einterfaces.MetricsInterface + notification einterfaces.NotificationInterface + saml einterfaces.SamlInterface - HTTPService httpservice.HTTPService - ImageProxy *imageproxy.ImageProxy - Timezones *timezones.Timezones + httpService httpservice.HTTPService + imageProxy *imageproxy.ImageProxy + timezones *timezones.Timezones + + context context.Context } func New(options ...AppOption) *App { @@ -63,8 +66,8 @@ func New(options ...AppOption) *App { // This is to avoid having to change all the code in cmd/mattermost/commands/* for now // shutdown should be called directly on the server func (a *App) Shutdown() { - a.Srv.Shutdown() - a.Srv = nil + a.Srv().Shutdown() + a.srv = nil } func (a *App) configOrLicenseListener() { @@ -99,18 +102,18 @@ func (s *Server) initJobs() { } func (a *App) DiagnosticId() string { - return a.Srv.diagnosticId + return a.Srv().diagnosticId } func (a *App) SetDiagnosticId(id string) { - a.Srv.diagnosticId = id + a.Srv().diagnosticId = id } func (a *App) EnsureDiagnosticId() { - if a.Srv.diagnosticId != "" { + if a.Srv().diagnosticId != "" { return } - props, err := a.Srv.Store.System().Get() + props, err := a.Srv().Store.System().Get() if err != nil { return } @@ -119,15 +122,15 @@ func (a *App) EnsureDiagnosticId() { if len(id) == 0 { id = model.NewId() systemId := &model.System{Name: model.SYSTEM_DIAGNOSTIC_ID, Value: id} - a.Srv.Store.System().Save(systemId) + a.Srv().Store.System().Save(systemId) } - a.Srv.diagnosticId = id + a.Srv().diagnosticId = id } func (a *App) HTMLTemplates() *template.Template { - if a.Srv.htmlTemplateWatcher != nil { - return a.Srv.htmlTemplateWatcher.Templates() + if a.Srv().htmlTemplateWatcher != nil { + return a.Srv().htmlTemplateWatcher.Templates() } return nil @@ -146,7 +149,7 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) { } func (a *App) getSystemInstallDate() (int64, *model.AppError) { - systemData, appErr := a.Srv.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) + systemData, appErr := a.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) if appErr != nil { return 0, appErr } @@ -156,3 +159,111 @@ func (a *App) getSystemInstallDate() (int64, *model.AppError) { } return value, nil } + +func (a *App) Srv() *Server { + return a.srv +} +func (a *App) Log() *mlog.Logger { + return a.log +} +func (a *App) NotificationsLog() *mlog.Logger { + return a.notificationsLog +} +func (a *App) T(translationID string, args ...interface{}) string { + return a.t(translationID, args...) +} +func (a *App) Session() *model.Session { + return &a.session +} +func (a *App) RequestId() string { + return a.requestId +} +func (a *App) IpAddress() string { + return a.ipAddress +} +func (a *App) Path() string { + return a.path +} +func (a *App) UserAgent() string { + return a.userAgent +} +func (a *App) AcceptLanguage() string { + return a.acceptLanguage +} +func (a *App) AccountMigration() einterfaces.AccountMigrationInterface { + return a.accountMigration +} +func (a *App) Cluster() einterfaces.ClusterInterface { + return a.cluster +} +func (a *App) Compliance() einterfaces.ComplianceInterface { + return a.compliance +} +func (a *App) DataRetention() einterfaces.DataRetentionInterface { + return a.dataRetention +} +func (a *App) Elasticsearch() einterfaces.ElasticsearchInterface { + return a.elasticsearch +} +func (a *App) Ldap() einterfaces.LdapInterface { + return a.ldap +} +func (a *App) MessageExport() einterfaces.MessageExportInterface { + return a.messageExport +} +func (a *App) Metrics() einterfaces.MetricsInterface { + return a.metrics +} +func (a *App) Notification() einterfaces.NotificationInterface { + return a.notification +} +func (a *App) Saml() einterfaces.SamlInterface { + return a.saml +} +func (a *App) HTTPService() httpservice.HTTPService { + return a.httpService +} +func (a *App) ImageProxy() *imageproxy.ImageProxy { + return a.imageProxy +} +func (a *App) Timezones() *timezones.Timezones { + return a.timezones +} +func (a *App) Context() context.Context { + return a.context +} + +func (a *App) SetSession(s *model.Session) { + a.session = *s +} + +func (a *App) SetT(t goi18n.TranslateFunc) { + a.t = t +} +func (a *App) SetRequestId(s string) { + a.requestId = s +} +func (a *App) SetIpAddress(s string) { + a.ipAddress = s +} +func (a *App) SetUserAgent(s string) { + a.userAgent = s +} +func (a *App) SetAcceptLanguage(s string) { + a.acceptLanguage = s +} +func (a *App) SetPath(s string) { + a.path = s +} +func (a *App) SetContext(c context.Context) { + a.context = c +} +func (a *App) SetServer(srv *Server) { + a.srv = srv +} +func (a *App) GetT() goi18n.TranslateFunc { + return a.t +} +func (a *App) SetLog(l *mlog.Logger) { + a.log = l +} diff --git a/app/app_iface.go b/app/app_iface.go new file mode 100644 index 0000000000..41f6f902a4 --- /dev/null +++ b/app/app_iface.go @@ -0,0 +1,834 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +// Code generated by "make store-layers" +// DO NOT EDIT + +package app + +import ( + "archive/zip" + "bytes" + "context" + "crypto/ecdsa" + "html/template" + "io" + "mime/multipart" + "net/http" + "net/url" + "time" + + "github.com/dyatlov/go-opengraph/opengraph" + "github.com/gorilla/websocket" + "github.com/mattermost/go-i18n/i18n" + goi18n "github.com/mattermost/go-i18n/i18n" + "github.com/mattermost/mattermost-server/v5/einterfaces" + "github.com/mattermost/mattermost-server/v5/mlog" + "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/plugin" + "github.com/mattermost/mattermost-server/v5/services/filesstore" + "github.com/mattermost/mattermost-server/v5/services/httpservice" + "github.com/mattermost/mattermost-server/v5/services/imageproxy" + "github.com/mattermost/mattermost-server/v5/services/timezones" + "github.com/mattermost/mattermost-server/v5/store" + "github.com/mattermost/mattermost-server/v5/utils" +) + +// AppIface is extracted from App struct and contains all it's exported methods. It's provided to allow partial interface passing and app layers creation. +type AppIface interface { + AcceptLanguage() string + AccountMigration() einterfaces.AccountMigrationInterface + ActivateMfa(userId, token string) *model.AppError + AddChannelMember(userId string, channel *model.Channel, userRequestorId string, postRootId string) (*model.ChannelMember, *model.AppError) + AddConfigListener(listener func(*model.Config, *model.Config)) string + AddCursorIdsForPostList(originalList *model.PostList, afterPost, beforePost string, since int64, page, perPage int) + AddDirectChannels(teamId string, user *model.User) *model.AppError + AddLicenseListener(listener func()) string + AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError + AddPublicKey(name string, key io.Reader) *model.AppError + AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError + AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError + AddSamlPublicCertificate(fileData *multipart.FileHeader) *model.AppError + AddSessionToCache(session *model.Session) + AddStatusCache(status *model.Status) + AddStatusCacheSkipClusterSend(status *model.Status) + AddTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) + AddTeamMemberByInviteId(inviteId, userId string) (*model.TeamMember, *model.AppError) + AddTeamMemberByToken(userId, tokenId string) (*model.TeamMember, *model.AppError) + AddTeamMembers(teamId string, userIds []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) + AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) + AddUserToTeam(teamId string, userId string, userRequestorId string) (*model.Team, *model.AppError) + AddUserToTeamByInviteId(inviteId string, userId string) (*model.Team, *model.AppError) + AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError + AddUserToTeamByToken(userId string, tokenId string) (*model.Team, *model.AppError) + AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) + AsymmetricSigningKey() *ecdsa.PrivateKey + AttachDeviceId(sessionId string, deviceId string, expiresAt int64) *model.AppError + AttachSessionCookies(w http.ResponseWriter, r *http.Request) + AuthenticateUserForLogin(id, loginId, password, mfaToken string, ldapOnly bool) (*model.User, *model.AppError) + AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.AppError) + AutocompleteChannels(teamId string, term string) (*model.ChannelList, *model.AppError) + AutocompleteChannelsForSearch(teamId string, userId string, term string) (*model.ChannelList, *model.AppError) + AutocompleteUsersInChannel(teamId string, channelId string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) + AutocompleteUsersInTeam(teamId string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) + BroadcastStatus(status *model.Status) + BuildPostReactions(postId string) (*[]ReactionImportData, *model.AppError) + BuildPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) + BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataResponse, *model.AppError) + BulkExport(writer io.Writer, file string, pathToEmojiDir string, dirNameToExportEmoji string) *model.AppError + BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) + CancelJob(jobId string) *model.AppError + ChannelMembersMinusGroupMembers(channelID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) + ChannelMembersToAdd(since int64, channelID *string) ([]*model.UserChannelIDPair, *model.AppError) + ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *model.AppError) + CheckForClientSideCert(r *http.Request) (string, string, string) + CheckPasswordAndAllCriteria(user *model.User, password string, mfaToken string) *model.AppError + CheckRolesExist(roleNames []string) *model.AppError + CheckUserAllAuthenticationCriteria(user *model.User, mfaToken string) *model.AppError + CheckUserMfa(user *model.User, token string) *model.AppError + CheckUserPostflightAuthenticationCriteria(user *model.User) *model.AppError + CheckUserPreflightAuthenticationCriteria(user *model.User, mfaToken string) *model.AppError + ClearChannelMembersCache(channelID string) + ClearPushNotification(currentSessionId, userId, channelId string) + ClearPushNotificationSync(currentSessionId, userId, channelId string) *model.AppError + ClearSessionCacheForAllUsers() + ClearSessionCacheForAllUsersSkipClusterSend() + ClearSessionCacheForUser(userId string) + ClearSessionCacheForUserSkipClusterSend(userId string) + ClearTeamMembersCache(teamID string) + ClientConfig() map[string]string + ClientConfigHash() string + ClientConfigWithComputed() map[string]string + ClientLicense() map[string]string + Cluster() einterfaces.ClusterInterface + CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) + CompareAndSetPluginKey(pluginId string, key string, oldValue, newValue []byte) (bool, *model.AppError) + CompleteOAuth(service string, body io.ReadCloser, teamId string, props map[string]string) (*model.User, *model.AppError) + CompleteSwitchWithOAuth(service string, userData io.Reader, email string) (*model.User, *model.AppError) + Compliance() einterfaces.ComplianceInterface + Config() *model.Config + Context() context.Context + ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError) + CopyFileInfos(userId string, fileIds []string) ([]string, *model.AppError) + CreateBasicUser(client *model.Client4) *model.AppError + CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) + CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) + CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channel, *model.AppError) + CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) + CreateCommandPost(post *model.Post, teamId string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) + CreateCommandWebhook(commandId string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError) + CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError) + CreateDefaultMemberships(since int64) error + CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) + CreateGroup(group *model.Group) (*model.Group, *model.AppError) + CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) + CreateGuest(user *model.User) (*model.User, *model.AppError) + CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, hook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) + CreateJob(job *model.Job) (*model.Job, *model.AppError) + CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) + CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) + CreateOAuthUser(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) + CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) + CreatePasswordRecoveryToken(userId, email string) (*model.Token, *model.AppError) + CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) (*model.Post, *model.AppError) + CreatePostAsUser(post *model.Post, currentSessionId string) (*model.Post, *model.AppError) + CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) + CreatePushNotificationsHub() + CreateRole(role *model.Role) (*model.Role, *model.AppError) + CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) + CreateSession(session *model.Session) (*model.Session, *model.AppError) + CreateTeam(team *model.Team) (*model.Team, *model.AppError) + CreateTeamWithUser(team *model.Team, userId string) (*model.Team, *model.AppError) + CreateTermsOfService(text, userId string) (*model.TermsOfService, *model.AppError) + CreateUser(user *model.User) (*model.User, *model.AppError) + CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) + CreateUserAsAdmin(user *model.User) (*model.User, *model.AppError) + CreateUserFromSignup(user *model.User) (*model.User, *model.AppError) + CreateUserWithInviteId(user *model.User, inviteId string) (*model.User, *model.AppError) + CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) + CreateVerifyEmailToken(userId string, newEmail string) (*model.Token, *model.AppError) + CreateWebhookPost(userId string, channel *model.Channel, text, overrideUsername, overrideIconUrl, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) + DataRetention() einterfaces.DataRetentionInterface + DeactivateGuests() *model.AppError + DeactivateMfa(userId string) *model.AppError + DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError + DefaultChannelNames() []string + DeleteAllExpiredPluginKeys() *model.AppError + DeleteAllKeysForPlugin(pluginId string) *model.AppError + DeleteBotIconImage(botUserId string) *model.AppError + DeleteBrandImage() *model.AppError + DeleteChannel(channel *model.Channel, userId string) *model.AppError + DeleteCommand(commandId string) *model.AppError + DeleteEmoji(emoji *model.Emoji) *model.AppError + DeleteEphemeralPost(userId, postId string) + DeleteFlaggedPosts(postId string) + DeleteGroup(groupID string) (*model.Group, *model.AppError) + DeleteGroupConstrainedMemberships() error + DeleteGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) + DeleteGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) + DeleteIncomingWebhook(hookId string) *model.AppError + DeleteOAuthApp(appId string) *model.AppError + DeleteOutgoingWebhook(hookId string) *model.AppError + DeletePluginKey(pluginId string, key string) *model.AppError + DeletePost(postId, deleteByID string) (*model.Post, *model.AppError) + DeletePostFiles(post *model.Post) + DeletePreferences(userId string, preferences model.Preferences) *model.AppError + DeletePublicKey(name string) *model.AppError + DeleteReactionForPost(reaction *model.Reaction) *model.AppError + DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) + DeleteToken(token *model.Token) *model.AppError + DemoteUserToGuest(user *model.User) *model.AppError + DiagnosticId() string + DisableAutoResponder(userId string, asAdmin bool) *model.AppError + DisablePlugin(id string) *model.AppError + DisableUserAccessToken(token *model.UserAccessToken) *model.AppError + DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) + DoAdvancedPermissionsMigration() + DoAppMigrations() + DoEmojisPermissionsMigration() + DoGuestRolesCreationMigration() + DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) + DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) *model.AppError + DoPermissionsMigrations() *model.AppError + DoPostAction(postId, actionId, userId, selectedOption string) (string, *model.AppError) + DoPostActionWithCookie(postId, actionId, userId, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) + DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) + DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) + DoubleCheckPassword(user *model.User, password string) *model.AppError + DownloadFromURL(downloadURL string) ([]byte, error) + Elasticsearch() einterfaces.ElasticsearchInterface + EnablePlugin(id string) *model.AppError + EnableUserAccessToken(token *model.UserAccessToken) *model.AppError + EnsureDiagnosticId() + EnvironmentConfig() map[string]interface{} + ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) + ExportAllChannels(writer io.Writer) *model.AppError + ExportAllDirectChannels(writer io.Writer) *model.AppError + ExportAllDirectPosts(writer io.Writer) *model.AppError + ExportAllPosts(writer io.Writer) *model.AppError + ExportAllTeams(writer io.Writer) *model.AppError + ExportAllUsers(writer io.Writer) *model.AppError + ExportCustomEmoji(writer io.Writer, file string, pathToEmojiDir string, dirNameToExportEmoji string) *model.AppError + ExportPermissions(w io.Writer) error + ExportVersion(writer io.Writer) *model.AppError + ExportWriteLine(writer io.Writer, line *LineImportData) *model.AppError + FetchSamlMetadataFromIdp(url string) ([]byte, *model.AppError) + FileBackend() (filesstore.FileBackend, *model.AppError) + FileExists(path string) (bool, *model.AppError) + FileReader(path string) (filesstore.ReadCloseSeeker, *model.AppError) + FillInChannelProps(channel *model.Channel) *model.AppError + FillInChannelsProps(channelList *model.ChannelList) *model.AppError + FillInPostProps(post *model.Post, channel *model.Channel) *model.AppError + FilterNonGroupChannelMembers(userIds []string, channel *model.Channel) ([]string, error) + FilterNonGroupTeamMembers(userIds []string, team *model.Team) ([]string, error) + FindTeamByName(name string) bool + GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) + GeneratePublicLink(siteURL string, info *model.FileInfo) string + GetActivePluginManifests() ([]*model.Manifest, *model.AppError) + GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (*model.ChannelListWithTeamData, *model.AppError) + GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.AppError) + GetAllLdapGroupsPage(page int, perPage int, opts model.LdapGroupSearchOpts) ([]*model.Group, int, *model.AppError) + GetAllPrivateTeams() ([]*model.Team, *model.AppError) + GetAllPrivateTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) + GetAllPrivateTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) + GetAllPublicTeams() ([]*model.Team, *model.AppError) + GetAllPublicTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) + GetAllPublicTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) + GetAllRoles() ([]*model.Role, *model.AppError) + GetAllStatuses() map[string]*model.Status + GetAllTeams() ([]*model.Team, *model.AppError) + GetAllTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) + GetAllTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) + GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) + GetAudits(userId string, limit int) (model.Audits, *model.AppError) + GetAuditsPage(userId string, page int, perPage int) (model.Audits, *model.AppError) + GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) + GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) + GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model.AppError) + GetBotIconImage(botUserId string) ([]byte, *model.AppError) + GetBots(options *model.BotGetOptions) (model.BotList, *model.AppError) + GetBrandImage() ([]byte, *model.AppError) + GetBulkReactionsForPosts(postIds []string) (map[string][]*model.Reaction, *model.AppError) + GetChannel(channelId string) (*model.Channel, *model.AppError) + GetChannelByName(channelName, teamId string, includeDeleted bool) (*model.Channel, *model.AppError) + GetChannelByNameForTeamName(channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) + GetChannelCounts(teamId string, userId string) (*model.ChannelCounts, *model.AppError) + GetChannelGroupUsers(channelID string) ([]*model.User, *model.AppError) + GetChannelGuestCount(channelId string) (int64, *model.AppError) + GetChannelMember(channelId string, userId string) (*model.ChannelMember, *model.AppError) + GetChannelMemberCount(channelId string) (int64, *model.AppError) + GetChannelMembersByIds(channelId string, userIds []string) (*model.ChannelMembers, *model.AppError) + GetChannelMembersForUser(teamId string, userId string) (*model.ChannelMembers, *model.AppError) + GetChannelMembersForUserWithPagination(teamId, userId string, page, perPage int) ([]*model.ChannelMember, *model.AppError) + GetChannelMembersPage(channelId string, page, perPage int) (*model.ChannelMembers, *model.AppError) + GetChannelMembersTimezones(channelId string) ([]string, *model.AppError) + GetChannelPinnedPostCount(channelId string) (int64, *model.AppError) + GetChannelUnread(channelId, userId string) (*model.ChannelUnread, *model.AppError) + GetChannelsByNames(channelNames []string, teamId string) ([]*model.Channel, *model.AppError) + GetChannelsForScheme(scheme *model.Scheme, offset int, limit int) (model.ChannelList, *model.AppError) + GetChannelsForSchemePage(scheme *model.Scheme, page int, perPage int) (model.ChannelList, *model.AppError) + GetChannelsForUser(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError) + GetChannelsUserNotIn(teamId string, userId string, offset int, limit int) (*model.ChannelList, *model.AppError) + GetClusterId() string + GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) + GetClusterStatus() []*model.ClusterInfo + GetCommand(commandId string) (*model.Command, *model.AppError) + GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) + GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) + GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) + GetConfigFile(name string) ([]byte, error) + GetCookieDomain() string + GetDataRetentionPolicy() (*model.DataRetentionPolicy, *model.AppError) + GetDefaultProfileImage(user *model.User) ([]byte, *model.AppError) + GetDeletedChannels(teamId string, offset int, limit int, userId string) (*model.ChannelList, *model.AppError) + GetEmoji(emojiId string) (*model.Emoji, *model.AppError) + GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) + GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) + GetEmojiList(page, perPage int, sort string) ([]*model.Emoji, *model.AppError) + GetEmojiStaticUrl(emojiName string) (string, *model.AppError) + GetEnvironmentConfig() map[string]interface{} + GetFile(fileId string) ([]byte, *model.AppError) + GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) + GetFileInfosForPost(postId string, fromMaster bool) ([]*model.FileInfo, *model.AppError) + GetFileInfosForPostWithMigration(postId string) ([]*model.FileInfo, *model.AppError) + GetFlaggedPosts(userId string, offset int, limit int) (*model.PostList, *model.AppError) + GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) (*model.PostList, *model.AppError) + GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) (*model.PostList, *model.AppError) + GetGroup(id string) (*model.Group, *model.AppError) + GetGroupByName(name string) (*model.Group, *model.AppError) + GetGroupByRemoteID(remoteID string, groupSource model.GroupSource) (*model.Group, *model.AppError) + GetGroupChannel(userIds []string) (*model.Channel, *model.AppError) + GetGroupMemberUsers(groupID string) ([]*model.User, *model.AppError) + GetGroupMemberUsersPage(groupID string, page int, perPage int) ([]*model.User, int, *model.AppError) + GetGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) + GetGroupSyncables(groupID string, syncableType model.GroupSyncableType) ([]*model.GroupSyncable, *model.AppError) + GetGroups(page, perPage int, opts model.GroupSearchOpts) ([]*model.Group, *model.AppError) + GetGroupsByChannel(channelId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) + GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) + GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) + GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) + GetGroupsByUserId(userId string) ([]*model.Group, *model.AppError) + GetHubForUserId(userId string) *Hub + GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) + GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) + GetIncomingWebhooksForTeamPageByUser(teamId string, userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) + GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebhook, *model.AppError) + GetIncomingWebhooksPageByUser(userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) + GetJob(id string) (*model.Job, *model.AppError) + GetJobs(offset int, limit int) ([]*model.Job, *model.AppError) + GetJobsByType(jobType string, offset int, limit int) ([]*model.Job, *model.AppError) + GetJobsByTypePage(jobType string, page int, perPage int) ([]*model.Job, *model.AppError) + GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) + GetLatestTermsOfService() (*model.TermsOfService, *model.AppError) + GetLdapGroup(ldapGroupID string) (*model.Group, *model.AppError) + GetLogs(page, perPage int) ([]string, *model.AppError) + GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) + GetMarketplacePlugins(filter *model.MarketplacePluginFilter) ([]*model.MarketplacePlugin, *model.AppError) + GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string + GetMultipleEmojiByName(names []string) ([]*model.Emoji, *model.AppError) + GetNewUsersForTeamPage(teamId string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetNextPostIdFromPostList(postList *model.PostList) string + GetNotificationNameFormat(user *model.User) string + GetNumberOfChannelsOnTeam(teamId string) (int, *model.AppError) + GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) + GetOAuthAccessTokenForImplicitFlow(userId string, authRequest *model.AuthorizeRequest) (*model.Session, *model.AppError) + GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) + GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppError) + GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) + GetOAuthCodeRedirect(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) + GetOAuthImplicitRedirect(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) + GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamId, action, redirectTo, loginHint string) (string, *model.AppError) + GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamId string) (string, *model.AppError) + GetOAuthStateToken(token string) (*model.Token, *model.AppError) + GetOpenGraphMetadata(requestURL string) *opengraph.OpenGraph + GetOrCreateDirectChannel(userId, otherUserId string) (*model.Channel, *model.AppError) + GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model.AppError) + GetOutgoingWebhooksForChannelPageByUser(channelId string, userId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) + GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) + GetOutgoingWebhooksForTeamPageByUser(teamId string, userId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) + GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) + GetOutgoingWebhooksPageByUser(userId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) + GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) + GetPermalinkPost(postId string, userId string) (*model.PostList, *model.AppError) + GetPinnedPosts(channelId string) (*model.PostList, *model.AppError) + GetPluginKey(pluginId string, key string) ([]byte, *model.AppError) + GetPluginPublicKeyFiles() ([]string, *model.AppError) + GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) + GetPluginStatuses() (model.PluginStatuses, *model.AppError) + GetPlugins() (*model.PluginsResponse, *model.AppError) + GetPluginsEnvironment() *plugin.Environment + GetPostAfterTime(channelId string, time int64) (*model.Post, *model.AppError) + GetPostIdAfterTime(channelId string, time int64) (string, *model.AppError) + GetPostIdBeforeTime(channelId string, time int64) (string, *model.AppError) + GetPostThread(postId string, skipFetchThreads bool) (*model.PostList, *model.AppError) + GetPosts(channelId string, offset int, limit int) (*model.PostList, *model.AppError) + GetPostsAfterPost(options model.GetPostsOptions) (*model.PostList, *model.AppError) + GetPostsAroundPost(before bool, options model.GetPostsOptions) (*model.PostList, *model.AppError) + GetPostsBeforePost(options model.GetPostsOptions) (*model.PostList, *model.AppError) + GetPostsEtag(channelId string) string + GetPostsForChannelAroundLastUnread(channelId, userId string, limitBefore, limitAfter int, skipFetchThreads bool) (*model.PostList, *model.AppError) + GetPostsPage(options model.GetPostsOptions) (*model.PostList, *model.AppError) + GetPostsSince(options model.GetPostsSinceOptions) (*model.PostList, *model.AppError) + GetPreferenceByCategoryAndNameForUser(userId string, category string, preferenceName string) (*model.Preference, *model.AppError) + GetPreferenceByCategoryForUser(userId string, category string) (model.Preferences, *model.AppError) + GetPreferencesForUser(userId string) (model.Preferences, *model.AppError) + GetPrevPostIdFromPostList(postList *model.PostList) string + GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) + GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) (*model.ChannelList, *model.AppError) + GetPublicChannelsForTeam(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) + GetPublicKey(name string) ([]byte, *model.AppError) + GetReactionsForPost(postId string) ([]*model.Reaction, *model.AppError) + GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.User, *model.AppError) + GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetRole(id string) (*model.Role, *model.AppError) + GetRoleByName(name string) (*model.Role, *model.AppError) + GetRolesByNames(names []string) ([]*model.Role, *model.AppError) + GetSamlCertificateStatus() *model.SamlCertificateStatus + GetSamlMetadata() (string, *model.AppError) + GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) + GetSanitizeOptions(asAdmin bool) map[string]bool + GetSanitizedClientLicense() map[string]string + GetSanitizedConfig() *model.Config + GetScheme(id string) (*model.Scheme, *model.AppError) + GetSchemeByName(name string) (*model.Scheme, *model.AppError) + GetSchemeRolesForChannel(channelId string) (string, string, string, *model.AppError) + GetSchemeRolesForTeam(teamId string) (string, string, string, *model.AppError) + GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) + GetSchemesPage(scope string, page int, perPage int) ([]*model.Scheme, *model.AppError) + GetSession(token string) (*model.Session, *model.AppError) + GetSessionById(sessionId string) (*model.Session, *model.AppError) + GetSessions(userId string) ([]*model.Session, *model.AppError) + GetSinglePost(postId string) (*model.Post, *model.AppError) + GetSiteURL() string + GetStatus(userId string) (*model.Status, *model.AppError) + GetStatusFromCache(userId string) *model.Status + GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError) + GetT() goi18n.TranslateFunc + GetTeam(teamId string) (*model.Team, *model.AppError) + GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) + GetTeamByName(name string) (*model.Team, *model.AppError) + GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) + GetTeamIcon(team *model.Team) ([]byte, *model.AppError) + GetTeamIdFromQuery(query url.Values) (string, *model.AppError) + GetTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) + GetTeamMembers(teamId string, offset int, limit int, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, *model.AppError) + GetTeamMembersByIds(teamId string, userIds []string, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, *model.AppError) + GetTeamMembersForUser(userId string) ([]*model.TeamMember, *model.AppError) + GetTeamMembersForUserWithPagination(userId string, page, perPage int) ([]*model.TeamMember, *model.AppError) + GetTeamStats(teamId string, restrictions *model.ViewUsersRestrictions) (*model.TeamStats, *model.AppError) + GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.AppError) + GetTeamsForScheme(scheme *model.Scheme, offset int, limit int) ([]*model.Team, *model.AppError) + GetTeamsForSchemePage(scheme *model.Scheme, page int, perPage int) ([]*model.Team, *model.AppError) + GetTeamsForUser(userId string) ([]*model.Team, *model.AppError) + GetTeamsUnreadForUser(excludeTeamId string, userId string) ([]*model.TeamUnread, *model.AppError) + GetTermsOfService(id string) (*model.TermsOfService, *model.AppError) + GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) (*model.UsersStats, *model.AppError) + GetUser(userId string) (*model.User, *model.AppError) + GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAccessToken, *model.AppError) + GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, *model.AppError) + GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) + GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) + GetUserByEmail(email string) (*model.User, *model.AppError) + GetUserByUsername(username string) (*model.User, *model.AppError) + GetUserForLogin(id, loginId string) (*model.User, *model.AppError) + GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) + GetUserTermsOfService(userId string) (*model.UserTermsOfService, *model.AppError) + GetUsers(options *model.UserGetOptions) ([]*model.User, *model.AppError) + GetUsersByGroupChannelIds(channelIds []string, asAdmin bool) (map[string][]*model.User, *model.AppError) + GetUsersByIds(userIds []string, options *store.UserGetByIdsOpts) ([]*model.User, *model.AppError) + GetUsersByUsernames(usernames []string, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetUsersEtag(restrictionsHash string) string + GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) + GetUsersInChannelByStatus(channelId string, offset int, limit int) ([]*model.User, *model.AppError) + GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) + GetUsersInChannelPage(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) + GetUsersInChannelPageByStatus(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) + GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) + GetUsersInTeamEtag(teamId string, restrictionsHash string) string + GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) + GetUsersNotInChannel(teamId string, channelId string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetUsersNotInChannelMap(teamId string, channelId string, groupConstrained bool, offset int, limit int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) (map[string]*model.User, *model.AppError) + GetUsersNotInChannelPage(teamId string, channelId string, groupConstrained bool, page int, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetUsersNotInTeam(teamId string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetUsersNotInTeamEtag(teamId string, restrictionsHash string) string + GetUsersNotInTeamPage(teamId string, groupConstrained bool, page int, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) + GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) + GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) + GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) + GetVerifyEmailToken(token string) (*model.Token, *model.AppError) + GetViewUsersRestrictions(userId string) (*model.ViewUsersRestrictions, *model.AppError) + GetViewUsersRestrictionsForTeam(userId string, teamId string) ([]string, *model.AppError) + HTMLTemplates() *template.Template + HTTPService() httpservice.HTTPService + Handle404(w http.ResponseWriter, r *http.Request) + HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) + HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) + HandleCommandWebhook(hookId string, response *model.CommandResponse) *model.AppError + HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) + HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *model.AppError + HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config) + HasPermissionTo(askingUserId string, permission *model.Permission) bool + HasPermissionToChannel(askingUserId string, channelId string, permission *model.Permission) bool + HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool + HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool + HasPermissionToUser(askingUserId string, userId string) bool + HubRegister(webConn *WebConn) + HubStart() + HubStop() + HubUnregister(webConn *WebConn) + ImageProxy() *imageproxy.ImageProxy + ImageProxyAdder() func(string) string + ImageProxyRemover() func(string) string + ImportPermissions(jsonl io.Reader) error + InitPlugins(pluginDir, webappPluginDir string) + InitPostMetadata() + InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) + InstallPlugin(pluginFile io.ReadSeeker, replace bool) (*model.Manifest, *model.AppError) + InstallPluginFromData(data model.PluginEventData) + InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) + InvalidateAllCaches() *model.AppError + InvalidateAllCachesSkipSend() + InvalidateAllEmailInvites() *model.AppError + InvalidateCacheForChannel(channel *model.Channel) + InvalidateCacheForChannelByNameSkipClusterSend(teamId, name string) + InvalidateCacheForChannelMembers(channelId string) + InvalidateCacheForChannelMembersNotifyProps(channelId string) + InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId string) + InvalidateCacheForChannelPosts(channelId string) + InvalidateCacheForUser(userId string) + InvalidateCacheForUserSkipClusterSend(userId string) + InvalidateCacheForUserTeams(userId string) + InvalidateCacheForUserTeamsSkipClusterSend(userId string) + InvalidateCacheForWebhook(webhookId string) + InvalidateWebConnSessionCacheForUser(userId string) + InviteGuestsToChannels(teamId string, guestsInvite *model.GuestsInvite, senderId string) *model.AppError + InviteGuestsToChannelsGracefully(teamId string, guestsInvite *model.GuestsInvite, senderId string) ([]*model.EmailInviteWithError, *model.AppError) + InviteNewUsersToTeam(emailList []string, teamId, senderId string) *model.AppError + InviteNewUsersToTeamGracefully(emailList []string, teamId, senderId string) ([]*model.EmailInviteWithError, *model.AppError) + IpAddress() string + IsESAutocompletionEnabled() bool + IsESIndexingEnabled() bool + IsESSearchEnabled() bool + IsFirstUserAccount() bool + IsLeader() bool + IsPasswordValid(password string) *model.AppError + IsPhase2MigrationCompleted() *model.AppError + IsUserAway(lastActivityAt int64) bool + IsUserSignUpAllowed() *model.AppError + IsUsernameTaken(name string) bool + JoinChannel(channel *model.Channel, userId string) *model.AppError + JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError + JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) *model.AppError + Ldap() einterfaces.LdapInterface + LeaveChannel(channelId string, userId string) *model.AppError + LeaveTeam(team *model.Team, user *model.User, requestorId string) *model.AppError + License() *model.License + LimitedClientConfig() map[string]string + LimitedClientConfigWithComputed() map[string]string + ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) + ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) + ListDirectory(path string) ([]string, *model.AppError) + ListPluginKeys(pluginId string, page, perPage int) ([]string, *model.AppError) + ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) + LoadLicense() + Log() *mlog.Logger + LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) + MakePermissionError(permission *model.Permission) *model.AppError + MarkChannelAsUnreadFromPost(postID string, userID string) (*model.ChannelUnreadAt, *model.AppError) + MarkChannelsAsViewed(channelIds []string, userId string, currentSessionId string) (map[string]int64, *model.AppError) + MaxPostSize() int + MessageExport() einterfaces.MessageExportInterface + Metrics() einterfaces.MetricsInterface + MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo + MoveChannel(team *model.Team, channel *model.Channel, user *model.User, removeDeactivatedMembers bool) *model.AppError + MoveCommand(team *model.Team, command *model.Command) *model.AppError + MoveFile(oldPath, newPath string) *model.AppError + NewClusterDiscoveryService() *ClusterDiscoveryService + NewEmailTemplate(name, locale string) *utils.HTMLTemplate + NewPluginAPI(manifest *model.Manifest) plugin.API + NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.TranslateFunc, locale string) *WebConn + NewWebHub() *Hub + Notification() einterfaces.NotificationInterface + NotificationsLog() *mlog.Logger + OldImportChannel(channel *model.Channel, sChannel SlackChannel, users map[string]*model.User) *model.Channel + OldImportFile(timestamp time.Time, file io.Reader, teamId string, channelId string, userId string, fileName string) (*model.FileInfo, error) + OldImportIncomingWebhookPost(post *model.Post, props model.StringInterface) string + OldImportPost(post *model.Post) string + OldImportUser(team *model.Team, user *model.User) *model.User + OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError + OriginChecker() func(*http.Request) bool + OverrideIconURLIfEmoji(post *model.Post) + PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) + PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userId string) (*model.Channel, *model.AppError) + PatchPost(postId string, patch *model.PostPatch) (*model.Post, *model.AppError) + PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError) + PatchScheme(scheme *model.Scheme, patch *model.SchemePatch) (*model.Scheme, *model.AppError) + PatchTeam(teamId string, patch *model.TeamPatch) (*model.Team, *model.AppError) + PatchUser(userId string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError) + Path() string + PermanentDeleteAllUsers() *model.AppError + PermanentDeleteBot(botUserId string) *model.AppError + PermanentDeleteChannel(channel *model.Channel) *model.AppError + PermanentDeleteTeam(team *model.Team) *model.AppError + PermanentDeleteTeamId(teamId string) *model.AppError + PermanentDeleteUser(user *model.User) *model.AppError + PluginCommandsForTeam(teamId string) []*model.Command + PluginContext() *plugin.Context + PostActionCookieSecret() []byte + PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError + PostPatchWithProxyRemovedFromImageURLs(patch *model.PostPatch) *model.PostPatch + PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError + PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError + PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError + PostWithProxyAddedToImageURLs(post *model.Post) *model.Post + PostWithProxyRemovedFromImageURLs(post *model.Post) *model.Post + PreparePostForClient(originalPost *model.Post, isNewPost bool, isEditPost bool) *model.Post + PreparePostListForClient(originalList *model.PostList) *model.PostList + ProcessSlackAttachments(attachments []*model.SlackAttachment) []*model.SlackAttachment + ProcessSlackText(text string) string + PromoteGuestToUser(user *model.User, requestorId string) *model.AppError + Publish(message *model.WebSocketEvent) + PublishSkipClusterSend(message *model.WebSocketEvent) + PurgeElasticsearchIndexes() *model.AppError + ReadFile(path string) ([]byte, *model.AppError) + RecycleDatabaseConnection() + RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) + RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) + RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) + RegenerateTeamInviteId(teamId string) (*model.Team, *model.AppError) + RegisterPluginCommand(pluginId string, command *model.Command) error + ReloadConfig() error + RemoveConfigListener(id string) + RemoveFile(path string) *model.AppError + RemoveLicense() *model.AppError + RemoveLicenseListener(id string) + RemovePlugin(id string) *model.AppError + RemovePluginFromData(data model.PluginEventData) + RemoveSamlIdpCertificate() *model.AppError + RemoveSamlPrivateCertificate() *model.AppError + RemoveSamlPublicCertificate() *model.AppError + RemoveTeamIcon(teamId string) *model.AppError + RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId string) *model.AppError + RemoveUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError + RemoveUserFromTeam(teamId string, userId string, requestorId string) *model.AppError + RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) + RenameTeam(team *model.Team, newTeamName string, newDisplayName string) (*model.Team, *model.AppError) + RequestId() string + ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError + ResetPermissionsSystem() *model.AppError + RestoreChannel(channel *model.Channel, userId string) (*model.Channel, *model.AppError) + RestoreTeam(teamId string) *model.AppError + RestrictUsersGetByPermissions(userId string, options *model.UserGetOptions) (*model.UserGetOptions, *model.AppError) + RestrictUsersSearchByPermissions(userId string, options *model.UserSearchOptions) (*model.UserSearchOptions, *model.AppError) + RevokeAccessToken(token string) *model.AppError + RevokeAllSessions(userId string) *model.AppError + RevokeSession(session *model.Session) *model.AppError + RevokeSessionById(sessionId string) *model.AppError + RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError + RevokeSessionsFromAllUsers() *model.AppError + RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError + RolesGrantPermission(roleNames []string, permissionId string) bool + Saml() einterfaces.SamlInterface + SanitizeProfile(user *model.User, asAdmin bool) + SanitizeTeam(session model.Session, team *model.Team) *model.Team + SanitizeTeams(session model.Session, teams []*model.Team) []*model.Team + SaveAndBroadcastStatus(status *model.Status) + SaveBrandImage(imageData *multipart.FileHeader) *model.AppError + SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) + SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError + SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) + SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) + SaveUserTermsOfService(userId, termsOfServiceId string, accepted bool) *model.AppError + SchemesIterator(batchSize int) func() []*model.Scheme + SearchAllChannels(term string, opts model.ChannelSearchOpts) (*model.ChannelListWithTeamData, int64, *model.AppError) + SearchAllTeams(searchOpts *model.TeamSearch) ([]*model.Team, int64, *model.AppError) + SearchArchivedChannels(teamId string, term string, userId string) (*model.ChannelList, *model.AppError) + SearchChannels(teamId string, term string) (*model.ChannelList, *model.AppError) + SearchChannelsForUser(userId, teamId, term string) (*model.ChannelList, *model.AppError) + SearchChannelsUserNotIn(teamId string, userId string, term string) (*model.ChannelList, *model.AppError) + SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) + SearchGroupChannels(userId, term string) (*model.ChannelList, *model.AppError) + SearchPostsInTeam(teamId string, paramsList []*model.SearchParams) (*model.PostList, *model.AppError) + SearchPostsInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) + SearchPrivateTeams(term string) ([]*model.Team, *model.AppError) + SearchPublicTeams(term string) ([]*model.Team, *model.AppError) + SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError) + SearchUsers(props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SearchUsersInChannel(channelId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SearchUsersInTeam(teamId, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SearchUsersNotInChannel(teamId string, channelId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SearchUsersWithoutTeam(term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) + SendAckToPushProxy(ack *model.PushNotificationAck) error + SendAutoResponse(channel *model.Channel, receiver *model.User) (bool, *model.AppError) + SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User) (bool, *model.AppError) + SendChangeUsernameEmail(oldUsername, newUsername, email, locale, siteURL string) *model.AppError + SendDailyDiagnostics() + SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError + SendDiagnostic(event string, properties map[string]interface{}) + SendEmailChangeEmail(oldEmail, newEmail, locale, siteURL string) *model.AppError + SendEmailChangeVerifyEmail(newUserEmail, locale, siteURL, token string) *model.AppError + SendEmailVerification(user *model.User, newEmail string) *model.AppError + SendEphemeralPost(userId string, post *model.Post) *model.Post + SendGuestInviteEmails(team *model.Team, channels []*model.Channel, senderName string, senderUserId string, invites []string, siteURL string, message string) + SendInviteEmails(team *model.Team, senderName string, senderUserId string, invites []string, siteURL string) + SendMail(to, subject, htmlBody string) *model.AppError + SendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError + SendMfaChangeEmail(email string, activated bool, locale, siteURL string) *model.AppError + SendNotificationMail(to, subject, htmlBody string) *model.AppError + SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList) ([]string, error) + SendPasswordChangeEmail(email, method, locale, siteURL string) *model.AppError + SendPasswordReset(email string, siteURL string) (bool, *model.AppError) + SendPasswordResetEmail(email string, token *model.Token, locale, siteURL string) (bool, *model.AppError) + SendSignInChangeEmail(email, method, locale, siteURL string) *model.AppError + SendUserAccessTokenAddedEmail(email, locale, siteURL string) *model.AppError + SendVerifyEmail(userEmail, locale, siteURL, token string) *model.AppError + SendWelcomeEmail(userId string, email string, verified bool, locale, siteURL string) *model.AppError + ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, sourcePluginId, destinationPluginId string) + ServePluginPublicRequest(w http.ResponseWriter, r *http.Request) + ServePluginRequest(w http.ResponseWriter, r *http.Request) + ServerBusyStateChanged(sbs *model.ServerBusyState) + Session() *model.Session + SessionCacheLength() int + SessionHasPermissionTo(session model.Session, permission *model.Permission) bool + SessionHasPermissionToChannel(session model.Session, channelId string, permission *model.Permission) bool + SessionHasPermissionToChannelByPost(session model.Session, postId string, permission *model.Permission) bool + SessionHasPermissionToManageBot(session model.Session, botUserId string) *model.AppError + SessionHasPermissionToTeam(session model.Session, teamId string, permission *model.Permission) bool + SessionHasPermissionToUser(session model.Session, userId string) bool + SessionHasPermissionToUserOrBot(session model.Session, userId string) bool + SetAcceptLanguage(s string) + SetActiveChannel(userId string, channelId string) *model.AppError + SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) + SetBotIconImage(botUserId string, file io.ReadSeeker) *model.AppError + SetBotIconImageFromMultiPartFile(botUserId string, imageData *multipart.FileHeader) *model.AppError + SetClientLicense(m map[string]string) + SetContext(c context.Context) + SetDefaultProfileImage(user *model.User) *model.AppError + SetDiagnosticId(id string) + SetIpAddress(s string) + SetLicense(license *model.License) bool + SetLog(l *mlog.Logger) + SetPath(s string) + SetPhase2PermissionsMigrationStatus(isComplete bool) error + SetPluginKey(pluginId string, key string, value []byte) *model.AppError + SetPluginKeyWithExpiry(pluginId string, key string, value []byte, expireInSeconds int64) *model.AppError + SetPluginKeyWithOptions(pluginId string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) + SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) + SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppError + SetProfileImageFromFile(userId string, file io.Reader) *model.AppError + SetProfileImageFromMultiPartFile(userId string, file multipart.File) *model.AppError + SetRequestId(s string) + SetSamlIdpCertificateFromMetadata(data []byte) *model.AppError + SetServer(srv *Server) + SetSession(s *model.Session) + SetStatusAwayIfNeeded(userId string, manual bool) + SetStatusDoNotDisturb(userId string) + SetStatusLastActivityAt(userId string, activityAt int64) + SetStatusOffline(userId string, manual bool) + SetStatusOnline(userId string, manual bool) + SetStatusOutOfOffice(userId string) + SetT(t goi18n.TranslateFunc) + SetTeamIcon(teamId string, imageData *multipart.FileHeader) *model.AppError + SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppError + SetTeamIconFromMultiPartFile(teamId string, file multipart.File) *model.AppError + SetUserAgent(s string) + SetupInviteEmailRateLimiting() error + ShutDownPlugins() + Shutdown() + SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User + SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel + SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User) + SlackAddUsers(teamId string, slackusers []SlackUser, importerLog *bytes.Buffer) map[string]*model.User + SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) + SlackUploadFile(slackPostFile *SlackFile, uploads map[string]*zip.File, teamId string, channelId string, userId string, slackTimestamp string) (*model.FileInfo, bool) + SoftDeleteTeam(teamId string) *model.AppError + Srv() *Server + StartPushNotificationsHubWorkers() + StopPushNotificationsHubWorkers() + SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) + SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) + SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) + SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) + SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) + SyncLdap() + SyncPlugins() *model.AppError + SyncPluginsActiveState() + SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType) + SyncSyncableRoles(syncableID string, syncableType model.GroupSyncableType) *model.AppError + T(translationID string, args ...interface{}) string + TeamMembersMinusGroupMembers(teamID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) + TeamMembersToAdd(since int64, teamID *string) ([]*model.UserTeamIDPair, *model.AppError) + TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError) + TestElasticsearch(cfg *model.Config) *model.AppError + TestEmail(userId string, cfg *model.Config) *model.AppError + TestLdap() *model.AppError + TestSiteURL(siteURL string) *model.AppError + Timezones() *timezones.Timezones + ToggleMuteChannel(channelId string, userId string) *model.ChannelMember + TotalWebsocketConnections() int + TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) + UnregisterPluginCommand(pluginId, teamId, trigger string) + UnregisterPluginCommands(pluginId string) + UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) + UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) + UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) + UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) + UpdateChannelLastViewedAt(channelIds []string, userId string) *model.AppError + UpdateChannelMemberNotifyProps(data map[string]string, channelId string, userId string) (*model.ChannelMember, *model.AppError) + UpdateChannelMemberRoles(channelId string, userId string, newRoles string) (*model.ChannelMember, *model.AppError) + UpdateChannelMemberSchemeRoles(channelId string, userId string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) + UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) + UpdateChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) + UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) + UpdateConfig(f func(*model.Config)) + UpdateEphemeralPost(userId string, post *model.Post) *model.Post + UpdateGroup(group *model.Group) (*model.Group, *model.AppError) + UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) + UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) + UpdateLastActivityAtIfNeeded(session model.Session) + UpdateMfa(activate bool, userId, token string) *model.AppError + UpdateMobileAppBadge(userId string) + UpdateMobileAppBadgeSync(userId string) *model.AppError + UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string) *model.AppError + UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) + UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) + UpdatePassword(user *model.User, newPassword string) *model.AppError + UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.AppError + UpdatePasswordByUserIdSendEmail(userId, newPassword, method string) *model.AppError + UpdatePasswordSendEmail(user *model.User, newPassword, method string) *model.AppError + UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) + UpdatePreferences(userId string, preferences model.Preferences) *model.AppError + UpdateRole(role *model.Role) (*model.Role, *model.AppError) + UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) + UpdateSessionsIsGuest(userId string, isGuest bool) + UpdateTeam(team *model.Team) (*model.Team, *model.AppError) + UpdateTeamMemberRoles(teamId string, userId string, newRoles string) (*model.TeamMember, *model.AppError) + UpdateTeamMemberSchemeRoles(teamId string, userId string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.TeamMember, *model.AppError) + UpdateTeamPrivacy(teamId string, teamType string, allowOpenInvite bool) *model.AppError + UpdateTeamScheme(team *model.Team) (*model.Team, *model.AppError) + UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) + UpdateUserActive(userId string, active bool) *model.AppError + UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppError) + UpdateUserAuth(userId string, userAuth *model.UserAuth) (*model.UserAuth, *model.AppError) + UpdateUserNotifyProps(userId string, props map[string]string) (*model.User, *model.AppError) + UpdateUserRoles(userId string, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError) + UpdateWebConnUserActivity(session model.Session, activityAt int64) + UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError + UploadFile(data []byte, channelId string, filename string) (*model.FileInfo, *model.AppError) + UploadFileX(channelId, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) + UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) + UploadMultipartFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) + UpsertGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) + UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) + UserAgent() string + UserCanSeeOtherUser(userId string, otherUserId string) (bool, *model.AppError) + UserIsInAdminRoleGroup(userID, syncableID string, syncableType model.GroupSyncableType) (bool, *model.AppError) + ValidateAndSetLicenseBytes(b []byte) + VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError + VerifyPlugin(plugin, signature io.ReadSeeker) *model.AppError + VerifyUserEmail(userId, email string) *model.AppError + ViewChannel(view *model.ChannelView, userId string, currentSessionId string) (map[string]int64, *model.AppError) + WaitForChannelMembership(channelId string, userId string) + WriteFile(fr io.Reader, path string) (int64, *model.AppError) +} diff --git a/app/audit.go b/app/audit.go index d492a83341..6e991cb8c1 100644 --- a/app/audit.go +++ b/app/audit.go @@ -8,9 +8,9 @@ import ( ) func (a *App) GetAudits(userId string, limit int) (model.Audits, *model.AppError) { - return a.Srv.Store.Audit().Get(userId, 0, limit) + return a.Srv().Store.Audit().Get(userId, 0, limit) } func (a *App) GetAuditsPage(userId string, page int, perPage int) (model.Audits, *model.AppError) { - return a.Srv.Store.Audit().Get(userId, page*perPage, perPage) + return a.Srv().Store.Audit().Get(userId, page*perPage, perPage) } diff --git a/app/authentication.go b/app/authentication.go index 45749309b5..45dab8905e 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -51,7 +51,7 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa } if err := a.checkUserPassword(user, password); err != nil { - if passErr := a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return passErr } return err @@ -61,14 +61,14 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa // If the mfaToken is not set, we assume the client used this as a pre-flight request to query the server // about the MFA state of the user in question if mfaToken != "" { - if passErr := a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return passErr } } return err } - if passErr := a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { + if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { return passErr } @@ -86,13 +86,13 @@ func (a *App) DoubleCheckPassword(user *model.User, password string) *model.AppE } if err := a.checkUserPassword(user, password); err != nil { - if passErr := a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return passErr } return err } - if passErr := a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { + if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { return passErr } @@ -108,12 +108,12 @@ func (a *App) checkUserPassword(user *model.User, password string) *model.AppErr } func (a *App) checkLdapUserPasswordAndAllCriteria(ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) { - if a.Ldap == nil || ldapId == nil { + if a.Ldap() == nil || ldapId == nil { err := model.NewAppError("doLdapAuthentication", "api.user.login_ldap.not_available.app_error", nil, "", http.StatusNotImplemented) return nil, err } - ldapUser, err := a.Ldap.DoLogin(*ldapId, password) + ldapUser, err := a.Ldap().DoLogin(*ldapId, password) if err != nil { err.StatusCode = http.StatusUnauthorized return nil, err @@ -172,7 +172,7 @@ func (a *App) CheckUserMfa(user *model.User, token string) *model.AppError { return nil } - mfaService := mfa.New(a, a.Srv.Store) + mfaService := mfa.New(a, a.Srv().Store) ok, err := mfaService.ValidateToken(user.MfaSecret, token) if err != nil { return err @@ -209,7 +209,7 @@ func checkUserNotBot(user *model.User) *model.AppError { func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) { license := a.License() - ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap != nil && license != nil && *license.Features.LDAP + ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP if user.AuthService == model.USER_AUTH_SERVICE_LDAP { if !ldapAvailable { diff --git a/app/authorization.go b/app/authorization.go index f0e98b4fc9..8d47043433 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -12,7 +12,7 @@ import ( ) func (a *App) MakePermissionError(permission *model.Permission) *model.AppError { - return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+a.Session.UserId+", "+"permission="+permission.Id, http.StatusForbidden) + return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+a.Session().UserId+", "+"permission="+permission.Id, http.StatusForbidden) } func (a *App) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool { @@ -39,7 +39,7 @@ func (a *App) SessionHasPermissionToChannel(session model.Session, channelId str return false } - ids, err := a.Srv.Store.Channel().GetAllChannelMembersForUser(session.UserId, true, true) + ids, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(session.UserId, true, true) var channelRoles []string if err == nil { @@ -64,14 +64,14 @@ func (a *App) SessionHasPermissionToChannel(session model.Session, channelId str } func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postId string, permission *model.Permission) bool { - if channelMember, err := a.Srv.Store.Channel().GetMemberForPost(postId, session.UserId); err == nil { + if channelMember, err := a.Srv().Store.Channel().GetMemberForPost(postId, session.UserId); err == nil { if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) { return true } } - if channel, err := a.Srv.Store.Channel().GetForPost(postId); err == nil { + if channel, err := a.Srv().Store.Channel().GetForPost(postId); err == nil { if channel.TeamId != "" { return a.SessionHasPermissionToTeam(session, channel.TeamId, permission) } @@ -161,13 +161,13 @@ func (a *App) HasPermissionToChannel(askingUserId string, channelId string, perm } func (a *App) HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool { - if channelMember, err := a.Srv.Store.Channel().GetMemberForPost(postId, askingUserId); err == nil { + if channelMember, err := a.Srv().Store.Channel().GetMemberForPost(postId, askingUserId); err == nil { if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) { return true } } - if channel, err := a.Srv.Store.Channel().GetForPost(postId); err == nil { + if channel, err := a.Srv().Store.Channel().GetForPost(postId); err == nil { return a.HasPermissionToTeam(askingUserId, channel.TeamId, permission) } diff --git a/app/auto_users.go b/app/auto_users.go index b86f4d3075..76c33fcabd 100644 --- a/app/auto_users.go +++ b/app/auto_users.go @@ -47,11 +47,11 @@ func (a *App) CreateBasicUser(client *model.Client4) *model.AppError { if resp.Error != nil { return resp.Error } - _, err := a.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err := a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return err } - if _, err = a.Srv.Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id}, *a.Config().TeamSettings.MaxUsersPerTeam); err != nil { + if _, err = a.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id}, *a.Config().TeamSettings.MaxUsersPerTeam); err != nil { return err } } @@ -81,13 +81,13 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, bool) { } status := &model.Status{UserId: ruser.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} - if err := cfg.app.Srv.Store.Status().SaveOrUpdate(status); err != nil { + if err := cfg.app.Srv().Store.Status().SaveOrUpdate(status); err != nil { mlog.Error(err.Error()) return nil, false } // We need to cheat to verify the user's email - _, err := cfg.app.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err := cfg.app.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return nil, false } diff --git a/app/bot.go b/app/bot.go index 5be79588f3..484a6b311f 100644 --- a/app/bot.go +++ b/app/bot.go @@ -17,20 +17,20 @@ import ( // CreateBot creates the given bot and corresponding user. func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { - user, err := a.Srv.Store.User().Save(model.UserFromBot(bot)) + user, err := a.Srv().Store.User().Save(model.UserFromBot(bot)) if err != nil { return nil, err } bot.UserId = user.Id - savedBot, err := a.Srv.Store.Bot().Save(bot) + savedBot, err := a.Srv().Store.Bot().Save(bot) if err != nil { - a.Srv.Store.User().PermanentDelete(bot.UserId) + a.Srv().Store.User().PermanentDelete(bot.UserId) return nil, err } // Get the owner of the bot, if one exists. If not, don't send a message - ownerUser, err := a.Srv.Store.User().Get(bot.OwnerId) + ownerUser, err := a.Srv().Store.User().Get(bot.OwnerId) if err != nil && err.Id != store.MISSING_ACCOUNT_ERROR { mlog.Error(err.Error()) return nil, err @@ -50,7 +50,7 @@ func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { Message: T("api.bot.teams_channels.add_message_mobile"), } - if _, err := a.CreatePostAsUser(botAddPost, a.Session.Id); err != nil { + if _, err := a.CreatePostAsUser(botAddPost, a.Session().Id); err != nil { return nil, err } } @@ -67,7 +67,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, bot.Patch(botPatch) - user, err := a.Srv.Store.User().Get(botUserId) + user, err := a.Srv().Store.User().Get(botUserId) if err != nil { return nil, err } @@ -78,7 +78,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, user.Email = patchedUser.Email user.FirstName = patchedUser.FirstName - userUpdate, err := a.Srv.Store.User().Update(user, true) + userUpdate, err := a.Srv().Store.User().Update(user, true) if err != nil { return nil, err } @@ -86,22 +86,22 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, ruser := userUpdate.New a.sendUpdatedUserEvent(*ruser) - return a.Srv.Store.Bot().Update(bot) + return a.Srv().Store.Bot().Update(bot) } // GetBot returns the given bot. func (a *App) GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model.AppError) { - return a.Srv.Store.Bot().Get(botUserId, includeDeleted) + return a.Srv().Store.Bot().Get(botUserId, includeDeleted) } // GetBots returns the requested page of bots. func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppError) { - return a.Srv.Store.Bot().GetAll(options) + return a.Srv().Store.Bot().GetAll(options) } // UpdateBotActive marks a bot as active or inactive, along with its corresponding user. func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) { - user, err := a.Srv.Store.User().Get(botUserId) + user, err := a.Srv().Store.User().Get(botUserId) if err != nil { return nil, err } @@ -110,7 +110,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model return nil, err } - bot, err := a.Srv.Store.Bot().Get(botUserId, true) + bot, err := a.Srv().Store.Bot().Get(botUserId, true) if err != nil { return nil, err } @@ -125,7 +125,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model } if changed { - bot, err = a.Srv.Store.Bot().Update(bot) + bot, err = a.Srv().Store.Bot().Update(bot) if err != nil { return nil, err } @@ -136,11 +136,11 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model // PermanentDeleteBot permanently deletes a bot and its corresponding user. func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { - if err := a.Srv.Store.Bot().PermanentDelete(botUserId); err != nil { + if err := a.Srv().Store.Bot().PermanentDelete(botUserId); err != nil { return err } - if err := a.Srv.Store.User().PermanentDelete(botUserId); err != nil { + if err := a.Srv().Store.User().PermanentDelete(botUserId); err != nil { return err } @@ -149,14 +149,14 @@ func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { // UpdateBotOwner changes a bot's owner to the given value. func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) { - bot, err := a.Srv.Store.Bot().Get(botUserId, true) + bot, err := a.Srv().Store.Bot().Get(botUserId, true) if err != nil { return nil, err } bot.OwnerId = newOwnerId - bot, err = a.Srv.Store.Bot().Update(bot) + bot, err = a.Srv().Store.Bot().Update(bot) if err != nil { return nil, err } @@ -311,7 +311,7 @@ func (a *App) getDisableBotSysadminMessage(user *model.User, userBots model.BotL // ConvertUserToBot converts a user to bot. func (a *App) ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError) { - return a.Srv.Store.Bot().Save(model.BotFromUser(user)) + return a.Srv().Store.Bot().Save(model.BotFromUser(user)) } // SetBotIconImageFromMultiPartFile sets LHS icon for a bot. @@ -344,7 +344,7 @@ func (a *App) SetBotIconImage(botUserId string, file io.ReadSeeker) *model.AppEr } bot.LastIconUpdate = model.GetMillis() - if _, err = a.Srv.Store.Bot().Update(bot); err != nil { + if _, err = a.Srv().Store.Bot().Update(bot); err != nil { return err } a.invalidateUserCacheAndPublish(botUserId) @@ -364,12 +364,12 @@ func (a *App) DeleteBotIconImage(botUserId string) *model.AppError { return model.NewAppError("DeleteBotIconImage", "api.bot.delete_bot_icon_image.app_error", nil, err.Error(), http.StatusInternalServerError) } - if err = a.Srv.Store.User().UpdateLastPictureUpdate(botUserId); err != nil { + if err = a.Srv().Store.User().UpdateLastPictureUpdate(botUserId); err != nil { mlog.Error(err.Error()) } bot.LastIconUpdate = int64(0) - if _, err = a.Srv.Store.Bot().Update(bot); err != nil { + if _, err = a.Srv().Store.Bot().Update(bot); err != nil { return err } diff --git a/app/channel.go b/app/channel.go index bb93df581f..9703b96090 100644 --- a/app/channel.go +++ b/app/channel.go @@ -66,7 +66,7 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin var requestor *model.User if userRequestorId != "" { var err *model.AppError - requestor, err = a.Srv.Store.User().Get(userRequestorId) + requestor, err = a.Srv().Store.User().Get(userRequestorId) if err != nil { return err } @@ -74,7 +74,7 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin var err *model.AppError for _, channelName := range a.DefaultChannelNames() { - channel, channelErr := a.Srv.Store.Channel().GetByName(teamId, channelName, true) + channel, channelErr := a.Srv().Store.Channel().GetByName(teamId, channelName, true) if channelErr != nil { err = channelErr continue @@ -93,8 +93,8 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin NotifyProps: model.GetDefaultChannelNotifyProps(), } - _, err = a.Srv.Store.Channel().SaveMember(cm) - if histErr := a.Srv.Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); histErr != nil { + _, err = a.Srv().Store.Channel().SaveMember(cm) + if histErr := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); histErr != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(histErr)) return histErr } @@ -113,7 +113,7 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err = a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -190,7 +190,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userId string) (*mod a.Publish(message) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -226,13 +226,13 @@ func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDi func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { channel.DisplayName = strings.TrimSpace(channel.DisplayName) - sc, err := a.Srv.Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) + sc, err := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) if err != nil { return nil, err } if addMember { - user, err := a.Srv.Store.User().Get(channel.CreatorId) + user, err := a.Srv().Store.User().Get(channel.CreatorId) if err != nil { return nil, err } @@ -246,10 +246,10 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan NotifyProps: model.GetDefaultChannelNotifyProps(), } - if _, err := a.Srv.Store.Channel().SaveMember(cm); err != nil { + if _, err := a.Srv().Store.Channel().SaveMember(cm); err != nil { return nil, err } - if err := a.Srv.Store.ChannelMemberHistory().LogJoinEvent(channel.CreatorId, sc.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(channel.CreatorId, sc.Id, model.GetMillis()); err != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(err)) return nil, err } @@ -258,7 +258,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan } if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ChannelHasBeenCreated(pluginContext, sc) @@ -269,14 +269,14 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan if a.IsESIndexingEnabled() { if sc.Type == model.CHANNEL_OPEN { - a.Srv.Go(func() { - if err := a.Elasticsearch.IndexChannel(sc); err != nil { + a.Srv().Go(func() { + if err := a.Elasticsearch().IndexChannel(sc); err != nil { mlog.Error("Encountered error indexing channel", mlog.String("channel_id", sc.Id), mlog.Err(err)) } }) } if addMember { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUserFromId(channel.CreatorId); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", channel.CreatorId), mlog.Err(err)) } @@ -288,7 +288,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan } func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Channel, *model.AppError) { - channel, err := a.Srv.Store.Channel().GetByName("", model.GetDMNameFromIds(userId, otherUserId), true) + channel, err := a.Srv().Store.Channel().GetByName("", model.GetDMNameFromIds(userId, otherUserId), true) if err != nil { if err.Id == store.MISSING_CHANNEL_ERROR { channel, err = a.createDirectChannel(userId, otherUserId) @@ -305,7 +305,7 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann a.InvalidateCacheForUser(otherUserId) if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ChannelHasBeenCreated(pluginContext, channel) @@ -315,7 +315,7 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { for _, id := range []string{userId, otherUserId} { if indexUserErr := a.indexUserFromId(id); indexUserErr != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", id), mlog.Err(indexUserErr)) @@ -339,12 +339,12 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha uc1 := make(chan store.StoreResult, 1) uc2 := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uc1 <- store.StoreResult{Data: user, Err: err} close(uc1) }() go func() { - user, err := a.Srv.Store.User().Get(otherUserId) + user, err := a.Srv().Store.User().Get(otherUserId) uc2 <- store.StoreResult{Data: user, Err: err} close(uc2) }() @@ -361,7 +361,7 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha } otherUser := result.Data.(*model.User) - channel, err := a.Srv.Store.Channel().CreateDirectChannel(user, otherUser) + channel, err := a.Srv().Store.Channel().CreateDirectChannel(user, otherUser) if err != nil { if err.Id == store.CHANNEL_EXISTS_ERROR { return channel, err @@ -369,12 +369,12 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha return nil, err } - if err = a.Srv.Store.ChannelMemberHistory().LogJoinEvent(userId, channel.Id, model.GetMillis()); err != nil { + if err = a.Srv().Store.ChannelMemberHistory().LogJoinEvent(userId, channel.Id, model.GetMillis()); err != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(err)) return nil, err } if userId != otherUserId { - if err = a.Srv.Store.ChannelMemberHistory().LogJoinEvent(otherUserId, channel.Id, model.GetMillis()); err != nil { + if err = a.Srv().Store.ChannelMemberHistory().LogJoinEvent(otherUserId, channel.Id, model.GetMillis()); err != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(err)) return nil, err } @@ -394,7 +394,7 @@ func (a *App) WaitForChannelMembership(channelId string, userId string) { time.Sleep(100 * time.Millisecond) - _, err := a.Srv.Store.Channel().GetMember(channelId, userId) + _, err := a.Srv().Store.Channel().GetMember(channelId, userId) // If the membership was found then return if err == nil { @@ -432,7 +432,7 @@ func (a *App) CreateGroupChannel(userIds []string, creatorId string) (*model.Cha a.Publish(message) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { for _, id := range userIds { if err := a.indexUserFromId(id); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", id), mlog.Err(err)) @@ -449,7 +449,7 @@ func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Cha return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } - users, err := a.Srv.Store.User().GetProfileByIds(userIds, nil, true) + users, err := a.Srv().Store.User().GetProfileByIds(userIds, nil, true) if err != nil { return nil, err } @@ -464,7 +464,7 @@ func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Cha Type: model.CHANNEL_GROUP, } - channel, err := a.Srv.Store.Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam) + channel, err := a.Srv().Store.Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam) if err != nil { if err.Id == store.CHANNEL_EXISTS_ERROR { return channel, err @@ -481,10 +481,10 @@ func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Cha SchemeUser: !user.IsGuest(), } - if _, err := a.Srv.Store.Channel().SaveMember(cm); err != nil { + if _, err := a.Srv().Store.Channel().SaveMember(cm); err != nil { return nil, err } - if err := a.Srv.Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(err)) return nil, err } @@ -498,7 +498,7 @@ func (a *App) GetGroupChannel(userIds []string) (*model.Channel, *model.AppError return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } - users, err := a.Srv.Store.User().GetProfileByIds(userIds, nil, true) + users, err := a.Srv().Store.User().GetProfileByIds(userIds, nil, true) if err != nil { return nil, err } @@ -525,7 +525,7 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE return nil, model.NewAppError("UpdateChannel", "api.channel.update_channel.invalid_character.app_error", nil, "", http.StatusBadRequest) } - _, err := a.Srv.Store.Channel().Update(channel) + _, err := a.Srv().Store.Channel().Update(channel) if err != nil { return nil, err } @@ -537,8 +537,8 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE a.Publish(messageWs) if a.IsESIndexingEnabled() && channel.Type == model.CHANNEL_OPEN { - a.Srv.Go(func() { - if err := a.Elasticsearch.IndexChannel(channel); err != nil { + a.Srv().Go(func() { + if err := a.Elasticsearch().IndexChannel(channel); err != nil { mlog.Error("Encountered error indexing channel", mlog.String("channel_id", channel.Id), mlog.Err(err)) } }) @@ -617,7 +617,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userId string) (*model.Chan return nil, model.NewAppError("restoreChannel", "api.channel.restore_channel.restored.app_error", nil, "", http.StatusBadRequest) } - if err := a.Srv.Store.Channel().Restore(channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store.Channel().Restore(channel.Id, model.GetMillis()); err != nil { return nil, err } channel.DeleteAt = 0 @@ -627,7 +627,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userId string) (*model.Chan message.Add("channel_id", channel.Id) a.Publish(message) - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) if err != nil { return nil, err } @@ -772,7 +772,7 @@ func (a *App) UpdateChannelMemberRoles(channelId string, userId string, newRoles member.ExplicitRoles = strings.Join(newExplicitRoles, " ") - member, err = a.Srv.Store.Channel().UpdateMember(member) + member, err = a.Srv().Store.Channel().UpdateMember(member) if err != nil { return nil, err } @@ -800,7 +800,7 @@ func (a *App) UpdateChannelMemberSchemeRoles(channelId string, userId string, is member.ExplicitRoles = RemoveRoles([]string{model.CHANNEL_GUEST_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID}, member.ExplicitRoles) } - member, err = a.Srv.Store.Channel().UpdateMember(member) + member, err = a.Srv().Store.Channel().UpdateMember(member) if err != nil { return nil, err } @@ -842,7 +842,7 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelId s member.NotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] = ignoreChannelMentions } - member, err = a.Srv.Store.Channel().UpdateMember(member) + member, err = a.Srv().Store.Channel().UpdateMember(member) if err != nil { return nil, err } @@ -861,13 +861,13 @@ func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppErr ohc := make(chan store.StoreResult, 1) go func() { - webhooks, err := a.Srv.Store.Webhook().GetIncomingByChannel(channel.Id) + webhooks, err := a.Srv().Store.Webhook().GetIncomingByChannel(channel.Id) ihc <- store.StoreResult{Data: webhooks, Err: err} close(ihc) }() go func() { - outgoingHooks, err := a.Srv.Store.Webhook().GetOutgoingByChannel(channel.Id, -1, -1) + outgoingHooks, err := a.Srv().Store.Webhook().GetOutgoingByChannel(channel.Id, -1, -1) ohc <- store.StoreResult{Data: outgoingHooks, Err: err} close(ohc) }() @@ -875,7 +875,7 @@ func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppErr var user *model.User if userId != "" { var err *model.AppError - user, err = a.Srv.Store.User().Get(userId) + user, err = a.Srv().Store.User().Get(userId) if err != nil { return err } @@ -924,21 +924,21 @@ func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppErr now := model.GetMillis() for _, hook := range incomingHooks { - if err := a.Srv.Store.Webhook().DeleteIncoming(hook.Id, now); err != nil { + if err := a.Srv().Store.Webhook().DeleteIncoming(hook.Id, now); err != nil { mlog.Error("Encountered error deleting incoming webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } a.InvalidateCacheForWebhook(hook.Id) } for _, hook := range outgoingHooks { - if err := a.Srv.Store.Webhook().DeleteOutgoing(hook.Id, now); err != nil { + if err := a.Srv().Store.Webhook().DeleteOutgoing(hook.Id, now); err != nil { mlog.Error("Encountered error deleting outgoing webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } } deleteAt := model.GetMillis() - if err := a.Srv.Store.Channel().Delete(channel.Id, deleteAt); err != nil { + if err := a.Srv().Store.Channel().Delete(channel.Id, deleteAt); err != nil { return err } a.InvalidateCacheForChannel(channel) @@ -956,7 +956,7 @@ func (a *App) addUserToChannel(user *model.User, channel *model.Channel, teamMem return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) } - channelMember, err := a.Srv.Store.Channel().GetMember(channel.Id, user.Id) + channelMember, err := a.Srv().Store.Channel().GetMember(channel.Id, user.Id) if err != nil { if err.Id != store.MISSING_CHANNEL_MEMBER_ERROR { return nil, err @@ -992,13 +992,13 @@ func (a *App) addUserToChannel(user *model.User, channel *model.Channel, teamMem newMember.SchemeAdmin = userShouldBeAdmin } - if _, err = a.Srv.Store.Channel().SaveMember(newMember); err != nil { + if _, err = a.Srv().Store.Channel().SaveMember(newMember); err != nil { mlog.Error("Failed to add member", mlog.String("user_id", user.Id), mlog.String("channel_id", channel.Id), mlog.Err(err)) return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user.to.channel.failed.app_error", nil, "", http.StatusInternalServerError) } a.WaitForChannelMembership(channel.Id, user.Id) - if err = a.Srv.Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { + if err = a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { mlog.Error("Failed to update ChannelMemberHistory table", mlog.Err(err)) return nil, err } @@ -1010,7 +1010,7 @@ func (a *App) addUserToChannel(user *model.User, channel *model.Channel, teamMem } func (a *App) AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { - teamMember, err := a.Srv.Store.Team().GetMember(channel.TeamId, user.Id) + teamMember, err := a.Srv().Store.Team().GetMember(channel.TeamId, user.Id) if err != nil { return nil, err @@ -1033,7 +1033,7 @@ func (a *App) AddUserToChannel(user *model.User, channel *model.Channel) (*model } func (a *App) AddChannelMember(userId string, channel *model.Channel, userRequestorId string, postRootId string) (*model.ChannelMember, *model.AppError) { - if member, err := a.Srv.Store.Channel().GetMember(channel.Id, userId); err != nil { + if member, err := a.Srv().Store.Channel().GetMember(channel.Id, userId); err != nil { if err.Id != store.MISSING_CHANNEL_MEMBER_ERROR { return nil, err } @@ -1061,7 +1061,7 @@ func (a *App) AddChannelMember(userId string, channel *model.Channel, userReques } if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedChannel(pluginContext, cm, userRequestor) @@ -1071,7 +1071,7 @@ func (a *App) AddChannelMember(userId string, channel *model.Channel, userReques } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -1081,7 +1081,7 @@ func (a *App) AddChannelMember(userId string, channel *model.Channel, userReques if userRequestorId == "" || userId == userRequestorId { a.postJoinChannelMessage(user, channel) } else { - a.Srv.Go(func() { + a.Srv().Go(func() { a.PostAddToChannelMessage(userRequestor, user, channel, postRootId) }) } @@ -1092,7 +1092,7 @@ func (a *App) AddChannelMember(userId string, channel *model.Channel, userReques func (a *App) AddDirectChannels(teamId string, user *model.User) *model.AppError { var profiles []*model.User options := &model.UserGetOptions{InTeamId: teamId, Page: 0, PerPage: 100} - profiles, err := a.Srv.Store.User().GetProfiles(options) + profiles, err := a.Srv().Store.User().GetProfiles(options) if err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamId, "Error": err.Error()}, "", http.StatusInternalServerError) } @@ -1118,7 +1118,7 @@ func (a *App) AddDirectChannels(teamId string, user *model.User) *model.AppError } } - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamId, "Error": err.Error()}, "", http.StatusInternalServerError) } @@ -1126,7 +1126,7 @@ func (a *App) AddDirectChannels(teamId string, user *model.User) *model.AppError } func (a *App) PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) if err != nil { return model.NewAppError("PostUpdateChannelHeaderMessage", "api.channel.post_update_channel_header_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) } @@ -1160,7 +1160,7 @@ func (a *App) PostUpdateChannelHeaderMessage(userId string, channel *model.Chann } func (a *App) PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) if err != nil { return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) } @@ -1193,7 +1193,7 @@ func (a *App) PostUpdateChannelPurposeMessage(userId string, channel *model.Chan } func (a *App) PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) if err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) } @@ -1220,7 +1220,7 @@ func (a *App) PostUpdateChannelDisplayNameMessage(userId string, channel *model. } func (a *App) GetChannel(channelId string) (*model.Channel, *model.AppError) { - channel, errCh := a.Srv.Store.Channel().Get(channelId, true) + channel, errCh := a.Srv().Store.Channel().Get(channelId, true) if errCh != nil { if errCh.Id == "store.sql_channel.get.existing.app_error" { errCh.StatusCode = http.StatusNotFound @@ -1237,9 +1237,9 @@ func (a *App) GetChannelByName(channelName, teamId string, includeDeleted bool) var err *model.AppError if includeDeleted { - channel, err = a.Srv.Store.Channel().GetByNameIncludeDeleted(teamId, channelName, false) + channel, err = a.Srv().Store.Channel().GetByNameIncludeDeleted(teamId, channelName, false) } else { - channel, err = a.Srv.Store.Channel().GetByName(teamId, channelName, false) + channel, err = a.Srv().Store.Channel().GetByName(teamId, channelName, false) } if err != nil && err.Id == "store.sql_channel.get_by_name.missing.app_error" { @@ -1256,7 +1256,7 @@ func (a *App) GetChannelByName(channelName, teamId string, includeDeleted bool) } func (a *App) GetChannelsByNames(channelNames []string, teamId string) ([]*model.Channel, *model.AppError) { - channels, err := a.Srv.Store.Channel().GetByNames(teamId, channelNames, true) + channels, err := a.Srv().Store.Channel().GetByNames(teamId, channelNames, true) if err != nil { if err.Id == "store.sql_channel.get_by_name.missing.app_error" { err.StatusCode = http.StatusNotFound @@ -1271,7 +1271,7 @@ func (a *App) GetChannelsByNames(channelNames []string, teamId string) ([]*model func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { var team *model.Team - team, err := a.Srv.Store.Team().GetByName(teamName) + team, err := a.Srv().Store.Team().GetByName(teamName) if err != nil { err.StatusCode = http.StatusNotFound return nil, err @@ -1280,9 +1280,9 @@ func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeD var result *model.Channel if includeDeleted { - result, err = a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelName, false) + result, err = a.Srv().Store.Channel().GetByNameIncludeDeleted(team.Id, channelName, false) } else { - result, err = a.Srv.Store.Channel().GetByName(team.Id, channelName, false) + result, err = a.Srv().Store.Channel().GetByName(team.Id, channelName, false) } if err != nil && err.Id == "store.sql_channel.get_by_name.missing.app_error" { @@ -1299,7 +1299,7 @@ func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeD } func (a *App) GetChannelsForUser(teamId string, userId string, includeDeleted bool) (*model.ChannelList, *model.AppError) { - return a.Srv.Store.Channel().GetChannels(teamId, userId, includeDeleted) + return a.Srv().Store.Channel().GetChannels(teamId, userId, includeDeleted) } func (a *App) GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (*model.ChannelListWithTeamData, *model.AppError) { @@ -1311,7 +1311,7 @@ func (a *App) GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (* NotAssociatedToGroup: opts.NotAssociatedToGroup, IncludeDeleted: opts.IncludeDeleted, } - return a.Srv.Store.Channel().GetAllChannels(page*perPage, perPage, storeOpts) + return a.Srv().Store.Channel().GetAllChannels(page*perPage, perPage, storeOpts) } func (a *App) GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.AppError) { @@ -1323,35 +1323,35 @@ func (a *App) GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.A NotAssociatedToGroup: opts.NotAssociatedToGroup, IncludeDeleted: opts.IncludeDeleted, } - return a.Srv.Store.Channel().GetAllChannelsCount(storeOpts) + return a.Srv().Store.Channel().GetAllChannelsCount(storeOpts) } func (a *App) GetDeletedChannels(teamId string, offset int, limit int, userId string) (*model.ChannelList, *model.AppError) { - return a.Srv.Store.Channel().GetDeleted(teamId, offset, limit, userId) + return a.Srv().Store.Channel().GetDeleted(teamId, offset, limit, userId) } func (a *App) GetChannelsUserNotIn(teamId string, userId string, offset int, limit int) (*model.ChannelList, *model.AppError) { - return a.Srv.Store.Channel().GetMoreChannels(teamId, userId, offset, limit) + return a.Srv().Store.Channel().GetMoreChannels(teamId, userId, offset, limit) } func (a *App) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) (*model.ChannelList, *model.AppError) { - return a.Srv.Store.Channel().GetPublicChannelsByIdsForTeam(teamId, channelIds) + return a.Srv().Store.Channel().GetPublicChannelsByIdsForTeam(teamId, channelIds) } func (a *App) GetPublicChannelsForTeam(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) { - return a.Srv.Store.Channel().GetPublicChannelsForTeam(teamId, offset, limit) + return a.Srv().Store.Channel().GetPublicChannelsForTeam(teamId, offset, limit) } func (a *App) GetChannelMember(channelId string, userId string) (*model.ChannelMember, *model.AppError) { - return a.Srv.Store.Channel().GetMember(channelId, userId) + return a.Srv().Store.Channel().GetMember(channelId, userId) } func (a *App) GetChannelMembersPage(channelId string, page, perPage int) (*model.ChannelMembers, *model.AppError) { - return a.Srv.Store.Channel().GetMembers(channelId, page*perPage, perPage) + return a.Srv().Store.Channel().GetMembers(channelId, page*perPage, perPage) } func (a *App) GetChannelMembersTimezones(channelId string) ([]string, *model.AppError) { - membersTimezones, err := a.Srv.Store.Channel().GetChannelMembersTimezones(channelId) + membersTimezones, err := a.Srv().Store.Channel().GetChannelMembersTimezones(channelId) if err != nil { return nil, err } @@ -1368,15 +1368,15 @@ func (a *App) GetChannelMembersTimezones(channelId string) ([]string, *model.App } func (a *App) GetChannelMembersByIds(channelId string, userIds []string) (*model.ChannelMembers, *model.AppError) { - return a.Srv.Store.Channel().GetMembersByIds(channelId, userIds) + return a.Srv().Store.Channel().GetMembersByIds(channelId, userIds) } func (a *App) GetChannelMembersForUser(teamId string, userId string) (*model.ChannelMembers, *model.AppError) { - return a.Srv.Store.Channel().GetMembersForUser(teamId, userId) + return a.Srv().Store.Channel().GetMembersForUser(teamId, userId) } func (a *App) GetChannelMembersForUserWithPagination(teamId, userId string, page, perPage int) ([]*model.ChannelMember, *model.AppError) { - m, err := a.Srv.Store.Channel().GetMembersForUserWithPagination(teamId, userId, page, perPage) + m, err := a.Srv().Store.Channel().GetMembersForUserWithPagination(teamId, userId, page, perPage) if err != nil { return nil, err } @@ -1391,23 +1391,23 @@ func (a *App) GetChannelMembersForUserWithPagination(teamId, userId string, page } func (a *App) GetChannelMemberCount(channelId string) (int64, *model.AppError) { - return a.Srv.Store.Channel().GetMemberCount(channelId, true) + return a.Srv().Store.Channel().GetMemberCount(channelId, true) } func (a *App) GetChannelGuestCount(channelId string) (int64, *model.AppError) { - return a.Srv.Store.Channel().GetGuestCount(channelId, true) + return a.Srv().Store.Channel().GetGuestCount(channelId, true) } func (a *App) GetChannelPinnedPostCount(channelId string) (int64, *model.AppError) { - return a.Srv.Store.Channel().GetPinnedPostCount(channelId, true) + return a.Srv().Store.Channel().GetPinnedPostCount(channelId, true) } func (a *App) GetChannelCounts(teamId string, userId string) (*model.ChannelCounts, *model.AppError) { - return a.Srv.Store.Channel().GetChannelCounts(teamId, userId) + return a.Srv().Store.Channel().GetChannelCounts(teamId, userId) } func (a *App) GetChannelUnread(channelId, userId string) (*model.ChannelUnread, *model.AppError) { - channelUnread, err := a.Srv.Store.Channel().GetChannelUnread(channelId, userId) + channelUnread, err := a.Srv().Store.Channel().GetChannelUnread(channelId, userId) if err != nil { return nil, err } @@ -1423,12 +1423,12 @@ func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError userChan := make(chan store.StoreResult, 1) memberChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) userChan <- store.StoreResult{Data: user, Err: err} close(userChan) }() go func() { - member, err := a.Srv.Store.Channel().GetMember(channel.Id, userId) + member, err := a.Srv().Store.Channel().GetMember(channel.Id, userId) memberChan <- store.StoreResult{Data: member, Err: err} close(memberChan) }() @@ -1456,7 +1456,7 @@ func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError } if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedChannel(pluginContext, cm, nil) @@ -1466,7 +1466,7 @@ func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -1527,21 +1527,21 @@ func (a *App) postJoinTeamMessage(user *model.User, channel *model.Channel) *mod func (a *App) LeaveChannel(channelId string, userId string) *model.AppError { sc := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv.Store.Channel().Get(channelId, true) + channel, err := a.Srv().Store.Channel().Get(channelId, true) sc <- store.StoreResult{Data: channel, Err: err} close(sc) }() uc := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uc <- store.StoreResult{Data: user, Err: err} close(uc) }() mcc := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.Channel().GetMemberCount(channelId, false) + count, err := a.Srv().Store.Channel().GetMemberCount(channelId, false) mcc <- store.StoreResult{Data: count, Err: err} close(mcc) }() @@ -1581,7 +1581,7 @@ func (a *App) LeaveChannel(channelId string, userId string) *model.AppError { return nil } - a.Srv.Go(func() { + a.Srv().Go(func() { a.postLeaveChannelMessage(user, channel) }) @@ -1684,7 +1684,7 @@ func (a *App) postRemoveFromChannelMessage(removerUserId string, removedUser *mo } func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError { - user, err := a.Srv.Store.User().Get(userIdToRemove) + user, err := a.Srv().Store.User().Get(userIdToRemove) if err != nil { return err } @@ -1711,10 +1711,10 @@ func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, return err } - if err := a.Srv.Store.Channel().RemoveMember(channel.Id, userIdToRemove); err != nil { + if err := a.Srv().Store.Channel().RemoveMember(channel.Id, userIdToRemove); err != nil { return err } - if err := a.Srv.Store.ChannelMemberHistory().LogLeaveEvent(userIdToRemove, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store.ChannelMemberHistory().LogLeaveEvent(userIdToRemove, channel.Id, model.GetMillis()); err != nil { return err } @@ -1744,7 +1744,7 @@ func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, actorUser, _ = a.GetUser(removerUserId) } - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLeftChannel(pluginContext, cm, actorUser) @@ -1754,7 +1754,7 @@ func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUserFromId(userIdToRemove); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", userIdToRemove), mlog.Err(err)) } @@ -1790,7 +1790,7 @@ func (a *App) RemoveUserFromChannel(userIdToRemove string, removerUserId string, if userIdToRemove == removerUserId { a.postLeaveChannelMessage(user, channel) } else { - a.Srv.Go(func() { + a.Srv().Go(func() { a.postRemoveFromChannelMessage(removerUserId, user, channel) }) } @@ -1800,7 +1800,7 @@ func (a *App) RemoveUserFromChannel(userIdToRemove string, removerUserId string, func (a *App) GetNumberOfChannelsOnTeam(teamId string) (int, *model.AppError) { // Get total number of channels on current team - list, err := a.Srv.Store.Channel().GetTeamChannels(teamId) + list, err := a.Srv().Store.Channel().GetTeamChannels(teamId) if err != nil { return 0, err } @@ -1833,7 +1833,7 @@ func (a *App) SetActiveChannel(userId string, channelId string) *model.AppError } func (a *App) UpdateChannelLastViewedAt(channelIds []string, userId string) *model.AppError { - if _, err := a.Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId); err != nil { + if _, err := a.Srv().Store.Channel().UpdateLastViewedAt(channelIds, userId); err != nil { return err } @@ -1865,7 +1865,7 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string) (*model. return nil, err } - channelUnread, updateErr := a.Srv.Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions) + channelUnread, updateErr := a.Srv().Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions) if updateErr != nil { return channelUnread, updateErr } @@ -1883,14 +1883,14 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string) (*model. } func (a *App) esAutocompleteChannels(teamId, term string, includeDeleted bool) (*model.ChannelList, *model.AppError) { - channelIds, err := a.Elasticsearch.SearchChannels(teamId, term) + channelIds, err := a.Elasticsearch().SearchChannels(teamId, term) if err != nil { return nil, err } channelList := model.ChannelList{} if len(channelIds) > 0 { - channels, err := a.Srv.Store.Channel().GetChannelsByIds(channelIds) + channels, err := a.Srv().Store.Channel().GetChannelsByIds(channelIds) if err != nil { return nil, err } @@ -1919,7 +1919,7 @@ func (a *App) AutocompleteChannels(teamId string, term string) (*model.ChannelLi } if !a.IsESAutocompletionEnabled() || err != nil { - channelList, err = a.Srv.Store.Channel().AutocompleteInTeam(teamId, term, includeDeleted) + channelList, err = a.Srv().Store.Channel().AutocompleteInTeam(teamId, term, includeDeleted) if err != nil { return nil, err } @@ -1933,7 +1933,7 @@ func (a *App) AutocompleteChannelsForSearch(teamId string, userId string, term s term = strings.TrimSpace(term) - return a.Srv.Store.Channel().AutocompleteInTeamForSearch(teamId, userId, term, includeDeleted) + return a.Srv().Store.Channel().AutocompleteInTeamForSearch(teamId, userId, term, includeDeleted) } // SearchAllChannels returns a list of channels, the total count of the results of the search (if the paginate search option is true), and an error. @@ -1952,7 +1952,7 @@ func (a *App) SearchAllChannels(term string, opts model.ChannelSearchOpts) (*mod term = strings.TrimSpace(term) - return a.Srv.Store.Channel().SearchAllChannels(term, storeOpts) + return a.Srv().Store.Channel().SearchAllChannels(term, storeOpts) } func (a *App) SearchChannels(teamId string, term string) (*model.ChannelList, *model.AppError) { @@ -1960,13 +1960,13 @@ func (a *App) SearchChannels(teamId string, term string) (*model.ChannelList, *m term = strings.TrimSpace(term) - return a.Srv.Store.Channel().SearchInTeam(teamId, term, includeDeleted) + return a.Srv().Store.Channel().SearchInTeam(teamId, term, includeDeleted) } func (a *App) SearchArchivedChannels(teamId string, term string, userId string) (*model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) - return a.Srv.Store.Channel().SearchArchivedInTeam(teamId, term, userId) + return a.Srv().Store.Channel().SearchArchivedInTeam(teamId, term, userId) } func (a *App) SearchChannelsForUser(userId, teamId, term string) (*model.ChannelList, *model.AppError) { @@ -1974,7 +1974,7 @@ func (a *App) SearchChannelsForUser(userId, teamId, term string) (*model.Channel term = strings.TrimSpace(term) - return a.Srv.Store.Channel().SearchForUserInTeam(userId, teamId, term, includeDeleted) + return a.Srv().Store.Channel().SearchForUserInTeam(userId, teamId, term, includeDeleted) } func (a *App) SearchGroupChannels(userId, term string) (*model.ChannelList, *model.AppError) { @@ -1982,7 +1982,7 @@ func (a *App) SearchGroupChannels(userId, term string) (*model.ChannelList, *mod return &model.ChannelList{}, nil } - channelList, err := a.Srv.Store.Channel().SearchGroupChannels(userId, term) + channelList, err := a.Srv().Store.Channel().SearchGroupChannels(userId, term) if err != nil { return nil, err } @@ -1991,7 +1991,7 @@ func (a *App) SearchGroupChannels(userId, term string) (*model.ChannelList, *mod func (a *App) SearchChannelsUserNotIn(teamId string, userId string, term string) (*model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) - return a.Srv.Store.Channel().SearchMore(userId, teamId, term) + return a.Srv().Store.Channel().SearchMore(userId, teamId, term) } func (a *App) MarkChannelsAsViewed(channelIds []string, userId string, currentSessionId string) (map[string]int64, *model.AppError) { @@ -1999,13 +1999,13 @@ func (a *App) MarkChannelsAsViewed(channelIds []string, userId string, currentSe channelsToClearPushNotifications := []string{} if *a.Config().EmailSettings.SendPushNotifications { for _, channelId := range channelIds { - channel, errCh := a.Srv.Store.Channel().Get(channelId, true) + channel, errCh := a.Srv().Store.Channel().Get(channelId, true) if errCh != nil { mlog.Warn("Failed to get channel", mlog.Err(errCh)) continue } - member, err := a.Srv.Store.Channel().GetMember(channelId, userId) + member, err := a.Srv().Store.Channel().GetMember(channelId, userId) if err != nil { mlog.Warn("Failed to get membership", mlog.Err(err)) continue @@ -2017,13 +2017,13 @@ func (a *App) MarkChannelsAsViewed(channelIds []string, userId string, currentSe notify = user.NotifyProps[model.PUSH_NOTIFY_PROP] } if notify == model.USER_NOTIFY_ALL { - if count, err := a.Srv.Store.User().GetAnyUnreadPostCountForChannel(userId, channelId); err == nil { + if count, err := a.Srv().Store.User().GetAnyUnreadPostCountForChannel(userId, channelId); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelId) } } } else if notify == model.USER_NOTIFY_MENTION || channel.Type == model.CHANNEL_DIRECT { - if count, err := a.Srv.Store.User().GetUnreadCountForChannel(userId, channelId); err == nil { + if count, err := a.Srv().Store.User().GetUnreadCountForChannel(userId, channelId); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelId) } @@ -2031,7 +2031,7 @@ func (a *App) MarkChannelsAsViewed(channelIds []string, userId string, currentSe } } } - times, err := a.Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId) + times, err := a.Srv().Store.Channel().UpdateLastViewedAt(channelIds, userId) if err != nil { return nil, err } @@ -2072,33 +2072,33 @@ func (a *App) ViewChannel(view *model.ChannelView, userId string, currentSession } func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { - profiles, err := a.Srv.Store.User().GetAllProfilesInChannel(channel.Id, false) + profiles, err := a.Srv().Store.User().GetAllProfilesInChannel(channel.Id, false) if err != nil { return err } - if err := a.Srv.Store.Post().PermanentDeleteByChannel(channel.Id); err != nil { + if err := a.Srv().Store.Post().PermanentDeleteByChannel(channel.Id); err != nil { return err } - if err := a.Srv.Store.Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { + if err := a.Srv().Store.Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { return err } - if err := a.Srv.Store.Webhook().PermanentDeleteIncomingByChannel(channel.Id); err != nil { + if err := a.Srv().Store.Webhook().PermanentDeleteIncomingByChannel(channel.Id); err != nil { return err } - if err := a.Srv.Store.Webhook().PermanentDeleteOutgoingByChannel(channel.Id); err != nil { + if err := a.Srv().Store.Webhook().PermanentDeleteOutgoingByChannel(channel.Id); err != nil { return err } - if err := a.Srv.Store.Channel().PermanentDelete(channel.Id); err != nil { + if err := a.Srv().Store.Channel().PermanentDelete(channel.Id); err != nil { return err } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { for _, user := range profiles { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) @@ -2106,8 +2106,8 @@ func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { } }) if channel.Type == model.CHANNEL_OPEN { - a.Srv.Go(func() { - if err := a.Elasticsearch.DeleteChannel(channel); err != nil { + a.Srv().Go(func() { + if err := a.Elasticsearch().DeleteChannel(channel); err != nil { mlog.Error("Encountered error deleting channel", mlog.String("channel_id", channel.Id), mlog.Err(err)) } }) @@ -2121,7 +2121,7 @@ func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { // is in progress, and therefore should not be used from the API without first fixing this potential race condition. func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model.User, removeDeactivatedMembers bool) *model.AppError { if removeDeactivatedMembers { - if err := a.Srv.Store.Channel().RemoveAllDeactivatedMembers(channel.Id); err != nil { + if err := a.Srv().Store.Channel().RemoveAllDeactivatedMembers(channel.Id); err != nil { return err } } @@ -2149,13 +2149,13 @@ func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model. } // keep instance of the previous team - previousTeam, err := a.Srv.Store.Team().Get(channel.TeamId) + previousTeam, err := a.Srv().Store.Team().Get(channel.TeamId) if err != nil { return err } channel.TeamId = team.Id - if _, err := a.Srv.Store.Channel().Update(channel); err != nil { + if _, err := a.Srv().Store.Channel().Update(channel); err != nil { return err } a.postChannelMoveMessage(user, channel, previousTeam) @@ -2183,11 +2183,11 @@ func (a *App) postChannelMoveMessage(user *model.User, channel *model.Channel, p } func (a *App) GetPinnedPosts(channelId string) (*model.PostList, *model.AppError) { - return a.Srv.Store.Channel().GetPinnedPosts(channelId) + return a.Srv().Store.Channel().GetPinnedPosts(channelId) } func (a *App) ToggleMuteChannel(channelId string, userId string) *model.ChannelMember { - member, err := a.Srv.Store.Channel().GetMember(channelId, userId) + member, err := a.Srv().Store.Channel().GetMember(channelId, userId) if err != nil { return nil } @@ -2198,7 +2198,7 @@ func (a *App) ToggleMuteChannel(channelId string, userId string) *model.ChannelM member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = model.CHANNEL_NOTIFY_MENTION } - a.Srv.Store.Channel().UpdateMember(member) + a.Srv().Store.Channel().UpdateMember(member) return member } @@ -2271,9 +2271,9 @@ func (a *App) ClearChannelMembersCache(channelID string) { page := 0 for { - channelMembers, err := a.Srv.Store.Channel().GetMembers(channelID, page, perPage) + channelMembers, err := a.Srv().Store.Channel().GetMembers(channelID, page, perPage) if err != nil { - a.Log.Warn("error clearing cache for channel members", mlog.String("channel_id", channelID)) + a.Log().Warn("error clearing cache for channel members", mlog.String("channel_id", channelID)) break } diff --git a/app/channel_test.go b/app/channel_test.go index 38ad40cb8e..0944021e0d 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -146,10 +146,10 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi defer th.TearDown() // figure out the initial number of users in town square - channel, err := th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true) + channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true) require.Nil(t, err) townSquareChannelId := channel.Id - users, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) + users, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) require.Nil(t, err) initialNumTownSquareUsers := len(users) @@ -158,7 +158,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) require.Nil(t, err) assert.Len(t, histories, initialNumTownSquareUsers+1) @@ -177,10 +177,10 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing defer th.TearDown() // figure out the initial number of users in off-topic - channel, err := th.App.Srv.Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true) + channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true) require.Nil(t, err) offTopicChannelId := channel.Id - users, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) + users, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) require.Nil(t, err) initialNumTownSquareUsers := len(users) @@ -189,7 +189,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) require.Nil(t, err) assert.Len(t, histories, initialNumTownSquareUsers+1) @@ -233,7 +233,7 @@ func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) { publicChannel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) require.Nil(t, err) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) @@ -248,7 +248,7 @@ func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) { privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) require.Nil(t, err) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) @@ -291,7 +291,7 @@ func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) { channel, err := th.App.CreateGroupChannel(groupUserIds, th.BasicUser.Id) require.Nil(t, err, "Failed to create group channel.") - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.Nil(t, err) assert.Len(t, histories, 3) @@ -316,7 +316,7 @@ func TestCreateDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id) require.Nil(t, err, "Failed to create direct channel.") - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.Nil(t, err) assert.Len(t, histories, 2) @@ -344,7 +344,7 @@ func TestGetDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { require.Nil(t, err, "Failed to create direct channel.") // there should be a ChannelMemberHistory record for both users - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.Nil(t, err) assert.Len(t, histories, 2) @@ -379,7 +379,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.Nil(t, err) assert.Len(t, histories, 2) channelMemberHistoryUserIds := make([]string, 0) @@ -396,7 +396,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { // a user creates a channel publicChannel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) require.Nil(t, err) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) @@ -407,7 +407,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { if err := th.App.LeaveChannel(publicChannel.Id, th.BasicUser.Id); err != nil { t.Fatal("Failed to remove user from channel. Error: " + err.Message) } - histories = store.Must(th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id)).([]*model.ChannelMemberHistoryResult) + histories = store.Must(th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id)).([]*model.ChannelMemberHistoryResult) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) assert.Equal(t, publicChannel.Id, histories[0].ChannelId) @@ -492,7 +492,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv.Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.Nil(t, err) assert.Len(t, histories, 2) channelMemberHistoryUserIds := make([]string, 0) @@ -502,7 +502,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { } assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) - postList, err := th.App.Srv.Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false) + postList, err := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false) require.Nil(t, err) if assert.Len(t, postList.Order, 1) { diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index 9cd8d18fd9..ebf9cb636c 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -31,23 +31,23 @@ func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService { } func (me *ClusterDiscoveryService) Start() { - err := me.app.Srv.Store.ClusterDiscovery().Cleanup() + err := me.app.Srv().Store.ClusterDiscovery().Cleanup() if err != nil { mlog.Error("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err)) } - exists, err := me.app.Srv.Store.ClusterDiscovery().Exists(&me.ClusterDiscovery) + exists, err := me.app.Srv().Store.ClusterDiscovery().Exists(&me.ClusterDiscovery) if err != nil { mlog.Error("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } else { if exists { - if _, err := me.app.Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { + if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } } } - if err := me.app.Srv.Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil { + if err := me.app.Srv().Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) return } @@ -57,7 +57,7 @@ func (me *ClusterDiscoveryService) Start() { ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING) defer func() { ticker.Stop() - if _, err := me.app.Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { + if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson())) @@ -66,7 +66,7 @@ func (me *ClusterDiscoveryService) Start() { for { select { case <-ticker.C: - if err := me.app.Srv.Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil { + if err := me.app.Srv().Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } case <-me.stop: @@ -81,16 +81,16 @@ func (me *ClusterDiscoveryService) Stop() { } func (a *App) IsLeader() bool { - if a.License() != nil && *a.Config().ClusterSettings.Enable && a.Cluster != nil { - return a.Cluster.IsLeader() + if a.License() != nil && *a.Config().ClusterSettings.Enable && a.Cluster() != nil { + return a.Cluster().IsLeader() } return true } func (a *App) GetClusterId() string { - if a.Cluster == nil { + if a.Cluster() == nil { return "" } - return a.Cluster.GetClusterId() + return a.Cluster().GetClusterId() } diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index 9485529e4f..c2e3ef7bab 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -15,18 +15,18 @@ import ( // NewLocalCacheLayer. Be careful to not have duplicated handlers here and // there. func (a *App) registerAllClusterMessageHandlers() { - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, a.clusterPublishHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, a.clusterUpdateStatusHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, a.clusterInvalidateAllCachesHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, a.clusterInvalidateCacheForChannelMembersNotifyPropHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, a.clusterInvalidateCacheForChannelByNameHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, a.clusterInvalidateCacheForUserHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, a.clusterInvalidateCacheForUserTeamsHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, a.clusterClearSessionCacheForUserHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, a.clusterClearSessionCacheForAllUsersHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, a.clusterInstallPluginHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, a.clusterRemovePluginHandler) - a.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, a.clusterBusyStateChgHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, a.clusterPublishHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, a.clusterUpdateStatusHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, a.clusterInvalidateAllCachesHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, a.clusterInvalidateCacheForChannelMembersNotifyPropHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, a.clusterInvalidateCacheForChannelByNameHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, a.clusterInvalidateCacheForUserHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, a.clusterInvalidateCacheForUserTeamsHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, a.clusterClearSessionCacheForUserHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, a.clusterClearSessionCacheForAllUsersHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, a.clusterInstallPluginHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, a.clusterRemovePluginHandler) + a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, a.clusterBusyStateChgHandler) } func (a *App) clusterPublishHandler(msg *model.ClusterMessage) { diff --git a/app/command.go b/app/command.go index 05f91351af..5e24379b38 100644 --- a/app/command.go +++ b/app/command.go @@ -91,7 +91,7 @@ func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([ } if *a.Config().ServiceSettings.EnableCommands { - teamCmds, err := a.Srv.Store.Command().GetByTeam(teamId) + teamCmds, err := a.Srv().Store.Command().GetByTeam(teamId) if err != nil { return nil, err } @@ -113,7 +113,7 @@ func (a *App) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Command().GetByTeam(teamId) + return a.Srv().Store.Command().GetByTeam(teamId) } func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) { @@ -138,7 +138,7 @@ func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.C } if *a.Config().ServiceSettings.EnableCommands { - teamCmds, err := a.Srv.Store.Command().GetByTeam(teamId) + teamCmds, err := a.Srv().Store.Command().GetByTeam(teamId) if err != nil { return nil, err } @@ -217,26 +217,26 @@ func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, m chanChan := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv.Store.Channel().Get(args.ChannelId, true) + channel, err := a.Srv().Store.Channel().Get(args.ChannelId, true) chanChan <- store.StoreResult{Data: channel, Err: err} close(chanChan) }() teamChan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(args.TeamId) + team, err := a.Srv().Store.Team().Get(args.TeamId) teamChan <- store.StoreResult{Data: team, Err: err} close(teamChan) }() userChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(args.UserId) + user, err := a.Srv().Store.User().Get(args.UserId) userChan <- store.StoreResult{Data: user, Err: err} close(userChan) }() - teamCmds, err := a.Srv.Store.Command().GetByTeam(args.TeamId) + teamCmds, err := a.Srv().Store.Command().GetByTeam(args.TeamId) if err != nil { return nil, nil, err } @@ -327,7 +327,7 @@ func (a *App) doCommandRequest(cmd *model.Command, p url.Values) (*model.Command } // Send the request - resp, err := a.HTTPService.MakeClient(false).Do(req) + resp, err := a.HTTPService().MakeClient(false).Do(req) if err != nil { return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError) } @@ -454,7 +454,7 @@ func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError cmd.Trigger = strings.ToLower(cmd.Trigger) - teamCmds, err := a.Srv.Store.Command().GetByTeam(cmd.TeamId) + teamCmds, err := a.Srv().Store.Command().GetByTeam(cmd.TeamId) if err != nil { return nil, err } @@ -472,7 +472,7 @@ func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError } } - return a.Srv.Store.Command().Save(cmd) + return a.Srv().Store.Command().Save(cmd) } func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) { @@ -480,7 +480,7 @@ func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) { return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - cmd, err := a.Srv.Store.Command().Get(commandId) + cmd, err := a.Srv().Store.Command().Get(commandId) if err != nil { err.StatusCode = http.StatusNotFound return nil, err @@ -503,13 +503,13 @@ func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, updatedCmd.CreatorId = oldCmd.CreatorId updatedCmd.TeamId = oldCmd.TeamId - return a.Srv.Store.Command().Update(updatedCmd) + return a.Srv().Store.Command().Update(updatedCmd) } func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppError { command.TeamId = team.Id - _, err := a.Srv.Store.Command().Update(command) + _, err := a.Srv().Store.Command().Update(command) if err != nil { return err } @@ -524,7 +524,7 @@ func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppE cmd.Token = model.NewId() - return a.Srv.Store.Command().Update(cmd) + return a.Srv().Store.Command().Update(cmd) } func (a *App) DeleteCommand(commandId string) *model.AppError { @@ -532,5 +532,5 @@ func (a *App) DeleteCommand(commandId string) *model.AppError { return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Command().Delete(commandId, model.GetMillis()) + return a.Srv().Store.Command().Delete(commandId, model.GetMillis()) } diff --git a/app/command_echo.go b/app/command_echo.go index b9f7c4f1b7..9fd8145900 100644 --- a/app/command_echo.go +++ b/app/command_echo.go @@ -77,7 +77,7 @@ func (me *EchoProvider) DoCommand(a *App, args *model.CommandArgs, message strin } echoSem <- true - a.Srv.Go(func() { + a.Srv().Go(func() { defer func() { <-echoSem }() post := &model.Post{} post.ChannelId = args.ChannelId diff --git a/app/command_expand_collapse.go b/app/command_expand_collapse.go index 9df53d30f5..3ba77e1d4d 100644 --- a/app/command_expand_collapse.go +++ b/app/command_expand_collapse.go @@ -68,7 +68,7 @@ func (a *App) setCollapsePreference(args *model.CommandArgs, isCollapse bool) *m Value: strconv.FormatBool(isCollapse), } - if err := a.Srv.Store.Preference().Save(&model.Preferences{pref}); err != nil { + if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil { return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_groupmsg.go b/app/command_groupmsg.go index bf4a2040ba..2b8c01120e 100644 --- a/app/command_groupmsg.go +++ b/app/command_groupmsg.go @@ -47,7 +47,7 @@ func (me *groupmsgProvider) DoCommand(a *App, args *model.CommandArgs, message s for _, username := range users { username = strings.TrimSpace(username) username = strings.TrimPrefix(username, "@") - targetUser, err := a.Srv.Store.User().GetByUsername(username) + targetUser, err := a.Srv().Store.User().GetByUsername(username) if err != nil { invalidUsernames = append(invalidUsernames, username) continue diff --git a/app/command_invite.go b/app/command_invite.go index 0f788cc1ea..1c96ca232f 100644 --- a/app/command_invite.go +++ b/app/command_invite.go @@ -49,7 +49,7 @@ func (me *InviteProvider) DoCommand(a *App, args *model.CommandArgs, message str targetUsername := splitMessage[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, err := a.Srv.Store.User().GetByUsername(targetUsername) + userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername) if err != nil { mlog.Error(err.Error()) return &model.CommandResponse{ diff --git a/app/command_join.go b/app/command_join.go index 4e79b57b34..aa5c805ccc 100644 --- a/app/command_join.go +++ b/app/command_join.go @@ -43,7 +43,7 @@ func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message strin channelName = message[1:] } - channel, err := a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true) + channel, err := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_loadtest.go b/app/command_loadtest.go index d93b5ad7b0..10f10112bc 100644 --- a/app/command_loadtest.go +++ b/app/command_loadtest.go @@ -218,7 +218,7 @@ func (me *LoadTestProvider) SetupCommand(a *App, args *model.CommandArgs, messag } } } else { - team, err := a.Srv.Store.Team().Get(args.TeamId) + team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -267,7 +267,7 @@ func (me *LoadTestProvider) UsersCommand(a *App, args *model.CommandArgs, messag usersr = utils.Range{Begin: 2, End: 5} } - team, err := a.Srv.Store.Team().Get(args.TeamId) + team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -294,7 +294,7 @@ func (me *LoadTestProvider) ChannelsCommand(a *App, args *model.CommandArgs, mes channelsr = utils.Range{Begin: 2, End: 5} } - team, err := a.Srv.Store.Team().Get(args.TeamId) + team, err := a.Srv().Store.Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -311,7 +311,7 @@ func (me *LoadTestProvider) ChannelsCommand(a *App, args *model.CommandArgs, mes func (me *LoadTestProvider) ThreadedPostCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { var usernames []string options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000} - if profileUsers, err := a.Srv.Store.User().GetProfiles(options); err == nil { + if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil { usernames = make([]string, len(profileUsers)) i := 0 for _, userprof := range profileUsers { @@ -360,7 +360,7 @@ func (me *LoadTestProvider) PostsCommand(a *App, args *model.CommandArgs, messag var usernames []string options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000} - if profileUsers, err := a.Srv.Store.User().GetProfiles(options); err == nil { + if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil { usernames = make([]string, len(profileUsers)) i := 0 for _, userprof := range profileUsers { diff --git a/app/command_msg.go b/app/command_msg.go index d19e6a5a9d..771133e895 100644 --- a/app/command_msg.go +++ b/app/command_msg.go @@ -48,7 +48,7 @@ func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string targetUsername = strings.SplitN(message, " ", 2)[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, err := a.Srv.Store.User().GetByUsername(targetUsername) + userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername) if err != nil { mlog.Error(err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} @@ -71,7 +71,7 @@ func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) targetChannelId := "" - if channel, channelErr := a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil { + if channel, channelErr := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil { if channelErr.Id == "store.sql_channel.get_by_name.missing.app_error" { if !a.SessionHasPermissionTo(args.Session, model.PERMISSION_CREATE_DIRECT_CHANNEL) { return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} diff --git a/app/command_mute.go b/app/command_mute.go index e9d888664d..89faa67369 100644 --- a/app/command_mute.go +++ b/app/command_mute.go @@ -53,7 +53,7 @@ func (me *MuteProvider) DoCommand(a *App, args *model.CommandArgs, message strin } if len(channelName) > 0 && len(message) > 0 { - channel, _ = a.Srv.Store.Channel().GetByName(channel.TeamId, channelName, true) + channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) if channel == nil { return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} @@ -66,7 +66,7 @@ func (me *MuteProvider) DoCommand(a *App, args *model.CommandArgs, message strin } // Invalidate cache to allow cache lookups while sending notifications - a.Srv.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channel.Id) + a.Srv().Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channel.Id) // Direct and Group messages won't have a nice channel title, omit it if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP { diff --git a/app/command_remove.go b/app/command_remove.go index df2a140a36..02f57891ce 100644 --- a/app/command_remove.go +++ b/app/command_remove.go @@ -107,7 +107,7 @@ func doCommand(a *App, args *model.CommandArgs, message string) *model.CommandRe targetUsername = strings.SplitN(message, " ", 2)[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, err := a.Srv.Store.User().GetByUsername(targetUsername) + userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername) if err != nil { mlog.Error(err.Error()) return &model.CommandResponse{ diff --git a/app/command_test.go b/app/command_test.go index 652778a856..44b0380d4b 100644 --- a/app/command_test.go +++ b/app/command_test.go @@ -376,9 +376,9 @@ func TestDoCommandRequest(t *testing.T) { })) defer server.Close() - th.App.HTTPService.(*httpservice.HTTPServiceImpl).RequestTimeout = 100 * time.Millisecond + th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = 100 * time.Millisecond defer func() { - th.App.HTTPService.(*httpservice.HTTPServiceImpl).RequestTimeout = httpservice.RequestTimeout + th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = httpservice.RequestTimeout }() _, _, err := th.App.doCommandRequest(&model.Command{URL: server.URL}, url.Values{}) diff --git a/app/compliance.go b/app/compliance.go index ae4e755e7f..5ec6ed1e7c 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -16,34 +16,34 @@ func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Compliance().GetAll(page*perPage, perPage) + return a.Srv().Store.Compliance().GetAll(page*perPage, perPage) } func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { - if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance == nil { + if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } job.Type = model.COMPLIANCE_TYPE_ADHOC - job, err := a.Srv.Store.Compliance().Save(job) + job, err := a.Srv().Store.Compliance().Save(job) if err != nil { return nil, err } - a.Srv.Go(func() { - a.Compliance.RunComplianceJob(job) + a.Srv().Go(func() { + a.Compliance().RunComplianceJob(job) }) return job, nil } func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { - if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance == nil { + if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Compliance().Get(reportId) + return a.Srv().Store.Compliance().Get(reportId) } func (a *App) GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) { diff --git a/app/config.go b/app/config.go index bfbf40c101..0b0548055b 100644 --- a/app/config.go +++ b/app/config.go @@ -35,7 +35,7 @@ func (s *Server) Config() *model.Config { } func (a *App) Config() *model.Config { - return a.Srv.Config() + return a.Srv().Config() } func (s *Server) EnvironmentConfig() map[string]interface{} { @@ -43,7 +43,7 @@ func (s *Server) EnvironmentConfig() map[string]interface{} { } func (a *App) EnvironmentConfig() map[string]interface{} { - return a.Srv.EnvironmentConfig() + return a.Srv().EnvironmentConfig() } func (s *Server) UpdateConfig(f func(*model.Config)) { @@ -56,7 +56,7 @@ func (s *Server) UpdateConfig(f func(*model.Config)) { } func (a *App) UpdateConfig(f func(*model.Config)) { - a.Srv.UpdateConfig(f) + a.Srv().UpdateConfig(f) } func (s *Server) ReloadConfig() error { @@ -68,19 +68,19 @@ func (s *Server) ReloadConfig() error { } func (a *App) ReloadConfig() error { - return a.Srv.ReloadConfig() + return a.Srv().ReloadConfig() } func (a *App) ClientConfig() map[string]string { - return a.Srv.clientConfig + return a.Srv().clientConfig } func (a *App) ClientConfigHash() string { - return a.Srv.clientConfigHash + return a.Srv().clientConfigHash } func (a *App) LimitedClientConfig() map[string]string { - return a.Srv.limitedClientConfig + return a.Srv().limitedClientConfig } // Registers a function with a given listener to be called when the config is reloaded and may have changed. The function @@ -91,7 +91,7 @@ func (s *Server) AddConfigListener(listener func(*model.Config, *model.Config)) } func (a *App) AddConfigListener(listener func(*model.Config, *model.Config)) string { - return a.Srv.AddConfigListener(listener) + return a.Srv().AddConfigListener(listener) } // Removes a listener function by the unique ID returned when AddConfigListener was called @@ -100,20 +100,20 @@ func (s *Server) RemoveConfigListener(id string) { } func (a *App) RemoveConfigListener(id string) { - a.Srv.RemoveConfigListener(id) + a.Srv().RemoveConfigListener(id) } // ensurePostActionCookieSecret ensures that the key for encrypting PostActionCookie exists // and future calls to PostActionCookieSecret will always return a valid key, same on all // servers in the cluster func (a *App) ensurePostActionCookieSecret() error { - if a.Srv.postActionCookieSecret != nil { + if a.Srv().postActionCookieSecret != nil { return nil } var secret *model.SystemPostActionCookieSecret - value, err := a.Srv.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) if err == nil { if err := json.Unmarshal([]byte(value.Value), &secret); err != nil { return err @@ -139,7 +139,7 @@ func (a *App) ensurePostActionCookieSecret() error { } system.Value = string(v) // If we were able to save the key, use it, otherwise log the error. - if appErr := a.Srv.Store.System().Save(system); appErr != nil { + if appErr := a.Srv().Store.System().Save(system); appErr != nil { mlog.Error("Failed to save PostActionCookieSecret", mlog.Err(appErr)) } else { secret = newSecret @@ -149,7 +149,7 @@ func (a *App) ensurePostActionCookieSecret() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if secret == nil { - value, err := a.Srv.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) if err != nil { return err } @@ -159,20 +159,20 @@ func (a *App) ensurePostActionCookieSecret() error { } } - a.Srv.postActionCookieSecret = secret.Secret + a.Srv().postActionCookieSecret = secret.Secret return nil } // EnsureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to // AsymmetricSigningKey will always return a valid signing key. func (a *App) ensureAsymmetricSigningKey() error { - if a.Srv.asymmetricSigningKey != nil { + if a.Srv().asymmetricSigningKey != nil { return nil } var key *model.SystemAsymmetricSigningKey - value, err := a.Srv.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) if err == nil { if err := json.Unmarshal([]byte(value.Value), &key); err != nil { return err @@ -202,7 +202,7 @@ func (a *App) ensureAsymmetricSigningKey() error { } system.Value = string(v) // If we were able to save the key, use it, otherwise log the error. - if appErr := a.Srv.Store.System().Save(system); appErr != nil { + if appErr := a.Srv().Store.System().Save(system); appErr != nil { mlog.Error("Failed to save AsymmetricSigningKey", mlog.Err(appErr)) } else { key = newKey @@ -212,7 +212,7 @@ func (a *App) ensureAsymmetricSigningKey() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if key == nil { - value, err := a.Srv.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) if err != nil { return err } @@ -229,7 +229,7 @@ func (a *App) ensureAsymmetricSigningKey() error { default: return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve) } - a.Srv.asymmetricSigningKey = &ecdsa.PrivateKey{ + a.Srv().asymmetricSigningKey = &ecdsa.PrivateKey{ PublicKey: ecdsa.PublicKey{ Curve: curve, X: key.ECDSAKey.X, @@ -247,7 +247,7 @@ func (a *App) ensureInstallationDate() error { return nil } - installDate, err := a.Srv.Store.User().InferSystemInstallDate() + installDate, err := a.Srv().Store.User().InferSystemInstallDate() var installationDate int64 if err == nil && installDate > 0 { installationDate = installDate @@ -255,7 +255,7 @@ func (a *App) ensureInstallationDate() error { installationDate = utils.MillisFromTime(time.Now()) } - err = a.Srv.Store.System().SaveOrUpdate(&model.System{ + err = a.Srv().Store.System().SaveOrUpdate(&model.System{ Name: model.SYSTEM_INSTALLATION_DATE_KEY, Value: strconv.FormatInt(installationDate, 10), }) @@ -271,7 +271,7 @@ func (s *Server) AsymmetricSigningKey() *ecdsa.PrivateKey { } func (a *App) AsymmetricSigningKey() *ecdsa.PrivateKey { - return a.Srv.AsymmetricSigningKey() + return a.Srv().AsymmetricSigningKey() } func (s *Server) PostActionCookieSecret() []byte { @@ -279,7 +279,7 @@ func (s *Server) PostActionCookieSecret() []byte { } func (a *App) PostActionCookieSecret() []byte { - return a.Srv.PostActionCookieSecret() + return a.Srv().PostActionCookieSecret() } func (a *App) regenerateClientConfig() { @@ -303,9 +303,9 @@ func (a *App) regenerateClientConfig() { } clientConfigJSON, _ := json.Marshal(clientConfig) - a.Srv.clientConfig = clientConfig - a.Srv.limitedClientConfig = limitedClientConfig - a.Srv.clientConfigHash = fmt.Sprintf("%x", md5.Sum(clientConfigJSON)) + a.Srv().clientConfig = clientConfig + a.Srv().limitedClientConfig = limitedClientConfig + a.Srv().clientConfigHash = fmt.Sprintf("%x", md5.Sum(clientConfigJSON)) } func (a *App) GetCookieDomain() string { @@ -356,7 +356,7 @@ func (a *App) LimitedClientConfigWithComputed() map[string]string { // GetConfigFile proxies access to the given configuration file to the underlying config store. func (a *App) GetConfigFile(name string) ([]byte, error) { - data, err := a.Srv.configStore.GetFile(name) + data, err := a.Srv().configStore.GetFile(name) if err != nil { return nil, errors.Wrapf(err, "failed to get config file %s", name) } @@ -379,25 +379,25 @@ func (a *App) GetEnvironmentConfig() map[string]interface{} { // SaveConfig replaces the active configuration, optionally notifying cluster peers. func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { - oldCfg, err := a.Srv.configStore.Set(newCfg) + oldCfg, err := a.Srv().configStore.Set(newCfg) if errors.Cause(err) == config.ErrReadOnlyConfiguration { return model.NewAppError("saveConfig", "ent.cluster.save_config.error", nil, err.Error(), http.StatusForbidden) } else if err != nil { return model.NewAppError("saveConfig", "app.save_config.app_error", nil, err.Error(), http.StatusInternalServerError) } - if a.Metrics != nil { + if a.Metrics() != nil { if *a.Config().MetricsSettings.Enable { - a.Metrics.StartServer() + a.Metrics().StartServer() } else { - a.Metrics.StopServer() + a.Metrics().StopServer() } } - if a.Cluster != nil { - newCfg = a.Srv.configStore.RemoveEnvironmentOverrides(newCfg) - oldCfg = a.Srv.configStore.RemoveEnvironmentOverrides(oldCfg) - err := a.Cluster.ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage) + if a.Cluster() != nil { + newCfg = a.Srv().configStore.RemoveEnvironmentOverrides(newCfg) + oldCfg = a.Srv().configStore.RemoveEnvironmentOverrides(oldCfg) + err := a.Cluster().ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage) if err != nil { return err } @@ -407,17 +407,17 @@ func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bo } func (a *App) IsESIndexingEnabled() bool { - return a.Elasticsearch != nil && *a.Config().ElasticsearchSettings.EnableIndexing + return a.Elasticsearch() != nil && *a.Config().ElasticsearchSettings.EnableIndexing } func (a *App) IsESSearchEnabled() bool { - esInterface := a.Elasticsearch + esInterface := a.Elasticsearch() license := a.License() return esInterface != nil && *a.Config().ElasticsearchSettings.EnableSearching && license != nil && *license.Features.Elasticsearch } func (a *App) IsESAutocompletionEnabled() bool { - esInterface := a.Elasticsearch + esInterface := a.Elasticsearch() license := a.License() return esInterface != nil && *a.Config().ElasticsearchSettings.EnableAutocomplete && license != nil && *license.Features.Elasticsearch } diff --git a/app/config_test.go b/app/config_test.go index 0d6c38e90e..13a0b73a43 100644 --- a/app/config_test.go +++ b/app/config_test.go @@ -112,7 +112,7 @@ func TestEnsureInstallationDate(t *testing.T) { for _, tc := range tt { t.Run(tc.Name, func(t *testing.T) { - sqlStore := th.App.Srv.Store.User().(*sqlstore.SqlUserStore) + sqlStore := th.App.Srv().Store.User().(*sqlstore.SqlUserStore) sqlStore.GetMaster().Exec("DELETE FROM Users") for _, createAt := range tc.UsersCreationDates { @@ -122,9 +122,9 @@ func TestEnsureInstallationDate(t *testing.T) { } if tc.PrevInstallationDate == nil { - th.App.Srv.Store.System().PermanentDeleteByName(model.SYSTEM_INSTALLATION_DATE_KEY) + th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_INSTALLATION_DATE_KEY) } else { - th.App.Srv.Store.System().SaveOrUpdate(&model.System{ + th.App.Srv().Store.System().SaveOrUpdate(&model.System{ Name: model.SYSTEM_INSTALLATION_DATE_KEY, Value: strconv.FormatInt(*tc.PrevInstallationDate, 10), }) @@ -137,7 +137,7 @@ func TestEnsureInstallationDate(t *testing.T) { } else { assert.NoError(t, err) - data, err := th.App.Srv.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) + data, err := th.App.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) assert.Nil(t, err) value, _ := strconv.ParseInt(data.Value, 10, 64) assert.True(t, *tc.ExpectedInstallationDate <= value && *tc.ExpectedInstallationDate+1000 >= value) diff --git a/app/data_retention.go b/app/data_retention.go index a404513df5..fd29d220c3 100644 --- a/app/data_retention.go +++ b/app/data_retention.go @@ -10,9 +10,9 @@ import ( ) func (a *App) GetDataRetentionPolicy() (*model.DataRetentionPolicy, *model.AppError) { - if a.DataRetention == nil { + if a.DataRetention() == nil { return nil, model.NewAppError("App.GetDataRetentionPolicy", "ent.data_retention.generic.license.error", nil, "", http.StatusNotImplemented) } - return a.DataRetention.GetPolicy() + return a.DataRetention().GetPolicy() } diff --git a/app/diagnostics.go b/app/diagnostics.go index 3a0d7c2151..0e98f60a51 100644 --- a/app/diagnostics.go +++ b/app/diagnostics.go @@ -67,7 +67,7 @@ func (a *App) SendDailyDiagnostics() { func (a *App) sendDailyDiagnostics(override bool) { if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() && (!strings.Contains(SEGMENT_KEY, "placeholder") || override) { - a.Srv.initDiagnostics("") + a.Srv().initDiagnostics("") a.trackActivity() a.trackConfig() a.trackLicense() @@ -80,7 +80,7 @@ func (a *App) sendDailyDiagnostics(override bool) { } func (a *App) SendDiagnostic(event string, properties map[string]interface{}) { - a.Srv.diagnosticClient.Enqueue(analytics.Track{ + a.Srv().diagnosticClient.Enqueue(analytics.Track{ Event: event, UserId: a.DiagnosticId(), Properties: properties, @@ -137,78 +137,78 @@ func (a *App) trackActivity() { activeUsersDailyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersDailyCountChan <- store.StoreResult{Data: count, Err: err} close(activeUsersDailyCountChan) }() activeUsersMonthlyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersMonthlyCountChan <- store.StoreResult{Data: count, Err: err} close(activeUsersMonthlyCountChan) }() - if count, err := a.Srv.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { + if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { userCount = count } - if count, err := a.Srv.Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil { + if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil { botAccountsCount = count } - if iucr, err := a.Srv.Store.User().AnalyticsGetInactiveUsersCount(); err == nil { + if iucr, err := a.Srv().Store.User().AnalyticsGetInactiveUsersCount(); err == nil { inactiveUserCount = iucr } - teamCount, err := a.Srv.Store.Team().AnalyticsTeamCount(false) + teamCount, err := a.Srv().Store.Team().AnalyticsTeamCount(false) if err != nil { mlog.Error(err.Error()) } - if ucc, err := a.Srv.Store.Channel().AnalyticsTypeCount("", "O"); err == nil { + if ucc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "O"); err == nil { publicChannelCount = ucc } - if pcc, err := a.Srv.Store.Channel().AnalyticsTypeCount("", "P"); err == nil { + if pcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "P"); err == nil { privateChannelCount = pcc } - if dcc, err := a.Srv.Store.Channel().AnalyticsTypeCount("", "D"); err == nil { + if dcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "D"); err == nil { directChannelCount = dcc } - if duccr, err := a.Srv.Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil { + if duccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil { deletedPublicChannelCount = duccr } - if dpccr, err := a.Srv.Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil { + if dpccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil { deletedPrivateChannelCount = dpccr } - postsCount, _ = a.Srv.Store.Post().AnalyticsPostCount("", false, false) + postsCount, _ = a.Srv().Store.Post().AnalyticsPostCount("", false, false) postCountsOptions := &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: false, YesterdayOnly: true} - postCountsYesterday, _ := a.Srv.Store.Post().AnalyticsPostCountsByDay(postCountsOptions) + postCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) postsCountPreviousDay = 0 if len(postCountsYesterday) > 0 { postsCountPreviousDay = int64(postCountsYesterday[0].Value) } postCountsOptions = &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: true, YesterdayOnly: true} - botPostCountsYesterday, _ := a.Srv.Store.Post().AnalyticsPostCountsByDay(postCountsOptions) + botPostCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) botPostsCountPreviousDay = 0 if len(botPostCountsYesterday) > 0 { botPostsCountPreviousDay = int64(botPostCountsYesterday[0].Value) } - slashCommandsCount, _ = a.Srv.Store.Command().AnalyticsCommandCount("") + slashCommandsCount, _ = a.Srv().Store.Command().AnalyticsCommandCount("") - if c, err := a.Srv.Store.Webhook().AnalyticsIncomingCount(""); err == nil { + if c, err := a.Srv().Store.Webhook().AnalyticsIncomingCount(""); err == nil { incomingWebhooksCount = c } - outgoingWebhooksCount, _ = a.Srv.Store.Webhook().AnalyticsOutgoingCount("") + outgoingWebhooksCount, _ = a.Srv().Store.Webhook().AnalyticsOutgoingCount("") var activeUsersDailyCount int64 if r := <-activeUsersDailyCountChan; r.Err == nil { @@ -788,7 +788,7 @@ func (a *App) trackServer() { "operating_system": runtime.GOOS, } - if scr, err := a.Srv.Store.User().AnalyticsGetSystemAdminCount(); err == nil { + if scr, err := a.Srv().Store.User().AnalyticsGetSystemAdminCount(); err == nil { data["system_admins"] = scr } @@ -797,12 +797,12 @@ func (a *App) trackServer() { func (a *App) trackPermissions() { phase1Complete := false - if _, err := a.Srv.Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { phase1Complete = true } phase2Complete := false - if _, err := a.Srv.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { + if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { phase2Complete = true } @@ -894,7 +894,7 @@ func (a *App) trackPermissions() { channelGuestPermissions = strings.Join(role.Permissions, " ") } - count, _ := a.Srv.Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id) + count, _ := a.Srv().Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id) a.SendDiagnostic(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{ "scheme_id": scheme.Id, @@ -913,45 +913,45 @@ func (a *App) trackPermissions() { func (a *App) trackElasticsearch() { data := map[string]interface{}{} - if a.Elasticsearch != nil && a.Elasticsearch.GetVersion() != 0 { - data["elasticsearch_server_version"] = a.Elasticsearch.GetVersion() + if a.Elasticsearch() != nil && a.Elasticsearch().GetVersion() != 0 { + data["elasticsearch_server_version"] = a.Elasticsearch().GetVersion() } a.SendDiagnostic(TRACK_ELASTICSEARCH, data) } func (a *App) trackGroups() { - groupCount, err := a.Srv.Store.Group().GroupCount() + groupCount, err := a.Srv().Store.Group().GroupCount() if err != nil { mlog.Error(err.Error()) } - groupTeamCount, err := a.Srv.Store.Group().GroupTeamCount() + groupTeamCount, err := a.Srv().Store.Group().GroupTeamCount() if err != nil { mlog.Error(err.Error()) } - groupChannelCount, err := a.Srv.Store.Group().GroupChannelCount() + groupChannelCount, err := a.Srv().Store.Group().GroupChannelCount() if err != nil { mlog.Error(err.Error()) } - groupSyncedTeamCount, err := a.Srv.Store.Team().GroupSyncedTeamCount() + groupSyncedTeamCount, err := a.Srv().Store.Team().GroupSyncedTeamCount() if err != nil { mlog.Error(err.Error()) } - groupSyncedChannelCount, err := a.Srv.Store.Channel().GroupSyncedChannelCount() + groupSyncedChannelCount, err := a.Srv().Store.Channel().GroupSyncedChannelCount() if err != nil { mlog.Error(err.Error()) } - groupMemberCount, err := a.Srv.Store.Group().GroupMemberCount() + groupMemberCount, err := a.Srv().Store.Group().GroupMemberCount() if err != nil { mlog.Error(err.Error()) } - distinctGroupMemberCount, err := a.Srv.Store.Group().DistinctGroupMemberCount() + distinctGroupMemberCount, err := a.Srv().Store.Group().DistinctGroupMemberCount() if err != nil { mlog.Error(err.Error()) } diff --git a/app/download.go b/app/download.go index 31d137fef2..ed84b981db 100644 --- a/app/download.go +++ b/app/download.go @@ -31,7 +31,7 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { return nil, errors.Errorf("insecure url not allowed %s", downloadURL) } - client := a.HTTPService.MakeClient(true) + client := a.HTTPService().MakeClient(true) client.Timeout = HTTP_REQUEST_TIMEOUT resp, err := client.Get(downloadURL) diff --git a/app/elasticsearch.go b/app/elasticsearch.go index 2f7d6b2fb8..b1906098d6 100644 --- a/app/elasticsearch.go +++ b/app/elasticsearch.go @@ -18,7 +18,7 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { } } - esI := a.Elasticsearch + esI := a.Elasticsearch() if esI == nil { err := model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented) return err @@ -31,7 +31,7 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { } func (a *App) PurgeElasticsearchIndexes() *model.AppError { - esI := a.Elasticsearch + esI := a.Elasticsearch() if esI == nil { err := model.NewAppError("PurgeElasticsearchIndexes", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented) return err diff --git a/app/email.go b/app/email.go index d13a5f9fde..c84c30583a 100644 --- a/app/email.go +++ b/app/email.go @@ -55,7 +55,7 @@ func (a *App) SetupInviteEmailRateLimiting() error { return errors.Wrap(err, "Unable to setup email rate limiting GCRA rate limiter.") } - a.Srv.EmailRateLimiter = rateLimiter + a.Srv().EmailRateLimiter = rateLimiter return nil } @@ -302,18 +302,18 @@ func (a *App) SendMfaChangeEmail(email string, activated bool, locale, siteURL s } func (a *App) SendInviteEmails(team *model.Team, senderName string, senderUserId string, invites []string, siteURL string) { - if a.Srv.EmailRateLimiter == nil { - a.Log.Error("Email invite not sent, rate limiting could not be setup.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id)) + if a.Srv().EmailRateLimiter == nil { + a.Log().Error("Email invite not sent, rate limiting could not be setup.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id)) return } - rateLimited, result, err := a.Srv.EmailRateLimiter.RateLimit(senderUserId, len(invites)) + rateLimited, result, err := a.Srv().EmailRateLimiter.RateLimit(senderUserId, len(invites)) if err != nil { - a.Log.Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err)) + a.Log().Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err)) return } if rateLimited { - a.Log.Error("Invite emails rate limited.", + a.Log().Error("Invite emails rate limited.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.String("retry_after", result.RetryAfter.String()), @@ -349,7 +349,7 @@ func (a *App) SendInviteEmails(team *model.Team, senderName string, senderUserId props["name"] = team.Name data := model.MapToJson(props) - if err := a.Srv.Store.Token().Save(token); err != nil { + if err := a.Srv().Store.Token().Save(token); err != nil { mlog.Error("Failed to send invite email successfully ", mlog.Err(err)) continue } @@ -363,29 +363,29 @@ func (a *App) SendInviteEmails(team *model.Team, senderName string, senderUserId } func (a *App) SendGuestInviteEmails(team *model.Team, channels []*model.Channel, senderName string, senderUserId string, invites []string, siteURL string, message string) { - if a.Srv.EmailRateLimiter == nil { - a.Log.Error("Email invite not sent, rate limiting could not be setup.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id)) + if a.Srv().EmailRateLimiter == nil { + a.Log().Error("Email invite not sent, rate limiting could not be setup.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id)) return } - rateLimited, result, err := a.Srv.EmailRateLimiter.RateLimit(senderUserId, len(invites)) + rateLimited, result, err := a.Srv().EmailRateLimiter.RateLimit(senderUserId, len(invites)) if err != nil { - a.Log.Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err)) + a.Log().Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err)) return } sender, appErr := a.GetUser(senderUserId) if appErr != nil { - a.Log.Error("Email invite not sent, unable to find the sender user.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(appErr)) + a.Log().Error("Email invite not sent, unable to find the sender user.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(appErr)) return } senderProfileImage, _, appErr := a.GetProfileImage(sender) if appErr != nil { - a.Log.Warn("Unable to get the sender user profile image.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(appErr)) + a.Log().Warn("Unable to get the sender user profile image.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(appErr)) } if rateLimited { - a.Log.Error("Invite emails rate limited.", + a.Log().Error("Invite emails rate limited.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.String("retry_after", result.RetryAfter.String()), @@ -437,7 +437,7 @@ func (a *App) SendGuestInviteEmails(team *model.Team, channels []*model.Channel, props["name"] = team.Name data := model.MapToJson(props) - if err := a.Srv.Store.Token().Save(token); err != nil { + if err := a.Srv().Store.Token().Save(token); err != nil { mlog.Error("Failed to send invite email successfully ", mlog.Err(err)) continue } diff --git a/app/email_batching.go b/app/email_batching.go index 839df1e3dc..95ac08f487 100644 --- a/app/email_batching.go +++ b/app/email_batching.go @@ -40,7 +40,7 @@ func (a *App) AddNotificationEmailToBatch(user *model.User, post *model.Post, te return model.NewAppError("AddNotificationEmailToBatch", "api.email_batching.add_notification_email_to_batch.disabled.app_error", nil, "", http.StatusNotImplemented) } - if !a.Srv.EmailBatching.Add(user, post, team) { + if !a.Srv().EmailBatching.Add(user, post, team) { mlog.Error("Email batching job's receiving channel was full. Please increase the EmailBatchingBufferSize.") return model.NewAppError("AddNotificationEmailToBatch", "api.email_batching.add_notification_email_to_batch.channel_full.app_error", nil, "", http.StatusInternalServerError) } diff --git a/app/email_batching_test.go b/app/email_batching_test.go index e3e6b5894d..ca385d10bd 100644 --- a/app/email_batching_test.go +++ b/app/email_batching_test.go @@ -88,13 +88,13 @@ func TestCheckPendingNotifications(t *testing.T) { }, } - channelMember, err := th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) + channelMember, err := th.App.Srv().Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) channelMember.LastViewedAt = 9999999 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) - err = th.App.Srv.Store.Preference().Save(&model.Preferences{{ + err = th.App.Srv().Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, @@ -109,10 +109,10 @@ func TestCheckPendingNotifications(t *testing.T) { require.Len(t, job.pendingNotifications[th.BasicUser.Id], 1, "shouldn't have sent queued post") // test that notifications are cleared if the user has acted - channelMember, err = th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) + channelMember, err = th.App.Srv().Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) channelMember.LastViewedAt = 10001000 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) job.checkPendingNotifications(time.Unix(10002, 0), func(string, []*batchedNotification) {}) @@ -186,10 +186,10 @@ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) { job := NewEmailBatchingJob(th.Server, 128) // bypasses recent user activity check - channelMember, err := th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) + channelMember, err := th.App.Srv().Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) channelMember.LastViewedAt = 9999000 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ @@ -224,14 +224,14 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { job := NewEmailBatchingJob(th.Server, 128) // bypasses recent user activity check - channelMember, err := th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) + channelMember, err := th.App.Srv().Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) channelMember.LastViewedAt = 9999000 - _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) require.Nil(t, err) // preference value is not an integer, so we'll fall back to the default 15min value - err = th.App.Srv.Store.Preference().Save(&model.Preferences{{ + err = th.App.Srv().Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, diff --git a/app/emoji.go b/app/emoji.go index a182c0d6ce..4dd79ef650 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -54,7 +54,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, model.NewAppError("createEmoji", "api.emoji.create.other_user.app_error", nil, "", http.StatusForbidden) } - if existingEmoji, err := a.Srv.Store.Emoji().GetByName(emoji.Name, true); err == nil && existingEmoji != nil { + if existingEmoji, err := a.Srv().Store.Emoji().GetByName(emoji.Name, true); err == nil && existingEmoji != nil { return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest) } @@ -68,7 +68,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, err } - emoji, err := a.Srv.Store.Emoji().Save(emoji) + emoji, err := a.Srv().Store.Emoji().Save(emoji) if err != nil { return nil, err } @@ -80,7 +80,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma } func (a *App) GetEmojiList(page, perPage int, sort string) ([]*model.Emoji, *model.AppError) { - return a.Srv.Store.Emoji().GetList(page*perPage, perPage, sort) + return a.Srv().Store.Emoji().GetList(page*perPage, perPage, sort) } func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError { @@ -157,7 +157,7 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode } func (a *App) DeleteEmoji(emoji *model.Emoji) *model.AppError { - if err := a.Srv.Store.Emoji().Delete(emoji, model.GetMillis()); err != nil { + if err := a.Srv().Store.Emoji().Delete(emoji, model.GetMillis()); err != nil { return err } @@ -175,7 +175,7 @@ func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Emoji().Get(emojiId, false) + return a.Srv().Store.Emoji().Get(emojiId, false) } func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) { @@ -187,7 +187,7 @@ func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Emoji().GetByName(emojiName, true) + return a.Srv().Store.Emoji().GetByName(emojiName, true) } func (a *App) GetMultipleEmojiByName(names []string) ([]*model.Emoji, *model.AppError) { @@ -195,11 +195,11 @@ func (a *App) GetMultipleEmojiByName(names []string) ([]*model.Emoji, *model.App return nil, model.NewAppError("GetMultipleEmojiByName", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Emoji().GetMultipleByName(names) + return a.Srv().Store.Emoji().GetMultipleByName(names) } func (a *App) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) { - _, storeErr := a.Srv.Store.Emoji().Get(emojiId, true) + _, storeErr := a.Srv().Store.Emoji().Get(emojiId, true) if storeErr != nil { return nil, "", storeErr } @@ -222,7 +222,7 @@ func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emo return nil, model.NewAppError("SearchEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Emoji().Search(name, prefixOnly, limit) + return a.Srv().Store.Emoji().Search(name, prefixOnly, limit) } // GetEmojiStaticUrl returns a relative static URL for system default emojis, @@ -234,7 +234,7 @@ func (a *App) GetEmojiStaticUrl(emojiName string) (string, *model.AppError) { return path.Join(subPath, "/static/emoji", id+".png"), nil } - if emoji, err := a.Srv.Store.Emoji().GetByName(emojiName, true); err == nil { + if emoji, err := a.Srv().Store.Emoji().GetByName(emojiName, true); err == nil { return path.Join(subPath, "/api/v4/emoji", emoji.Id, "image"), nil } else { return "", err @@ -289,7 +289,7 @@ func (a *App) deleteEmojiImage(id string) { } func (a *App) deleteReactionsForEmoji(emojiName string) { - if err := a.Srv.Store.Reaction().DeleteAllWithEmojiName(emojiName); err != nil { + if err := a.Srv().Store.Reaction().DeleteAllWithEmojiName(emojiName); err != nil { mlog.Warn("Unable to delete reactions when deleting emoji", mlog.String("emoji_name", emojiName), mlog.Err(err)) } } diff --git a/app/enterprise_test.go b/app/enterprise_test.go index 25d5b83fe8..06093abf44 100644 --- a/app/enterprise_test.go +++ b/app/enterprise_test.go @@ -104,10 +104,10 @@ func TestSAMLSettings(t *testing.T) { th.Server.initEnterprise() if tc.isNil { - assert.Nil(t, th.App.Srv.Saml) + assert.Nil(t, th.App.Srv().Saml) } else { - assert.NotNil(t, th.App.Srv.Saml) - metadata, err := th.App.Srv.Saml.GetMetadata() + assert.NotNil(t, th.App.Srv().Saml) + metadata, err := th.App.Srv().Saml.GetMetadata() assert.Nil(t, err) assert.Equal(t, tc.metadata, metadata) } diff --git a/app/export.go b/app/export.go index 21c80854af..76a8aef306 100644 --- a/app/export.go +++ b/app/export.go @@ -123,7 +123,7 @@ func (a *App) ExportVersion(writer io.Writer) *model.AppError { func (a *App) ExportAllTeams(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - teams, err := a.Srv.Store.Team().GetAllForExportAfter(1000, afterId) + teams, err := a.Srv().Store.Team().GetAllForExportAfter(1000, afterId) if err != nil { return err @@ -154,7 +154,7 @@ func (a *App) ExportAllTeams(writer io.Writer) *model.AppError { func (a *App) ExportAllChannels(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - channels, err := a.Srv.Store.Channel().GetAllChannelsForExportAfter(1000, afterId) + channels, err := a.Srv().Store.Channel().GetAllChannelsForExportAfter(1000, afterId) if err != nil { return err @@ -185,7 +185,7 @@ func (a *App) ExportAllChannels(writer io.Writer) *model.AppError { func (a *App) ExportAllUsers(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - users, err := a.Srv.Store.User().GetAllAfter(1000, afterId) + users, err := a.Srv().Store.User().GetAllAfter(1000, afterId) if err != nil { return err @@ -260,7 +260,7 @@ func (a *App) ExportAllUsers(writer io.Writer) *model.AppError { func (a *App) buildUserTeamAndChannelMemberships(userId string) (*[]UserTeamImportData, *model.AppError) { var memberships []UserTeamImportData - members, err := a.Srv.Store.Team().GetTeamMembersForExport(userId) + members, err := a.Srv().Store.Team().GetTeamMembersForExport(userId) if err != nil { return nil, err @@ -281,7 +281,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userId string) (*[]UserTeamImpo } // Get the user theme - themePreference, err := a.Srv.Store.Preference().Get(member.UserId, model.PREFERENCE_CATEGORY_THEME, member.TeamId) + themePreference, err := a.Srv().Store.Preference().Get(member.UserId, model.PREFERENCE_CATEGORY_THEME, member.TeamId) if err == nil { memberData.Theme = &themePreference.Value } @@ -297,7 +297,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userId string) (*[]UserTeamImpo func (a *App) buildUserChannelMemberships(userId string, teamId string) (*[]UserChannelImportData, *model.AppError) { var memberships []UserChannelImportData - members, err := a.Srv.Store.Channel().GetChannelMembersForExport(userId, teamId) + members, err := a.Srv().Store.Channel().GetChannelMembersForExport(userId, teamId) if err != nil { return nil, err } @@ -339,7 +339,7 @@ func (a *App) ExportAllPosts(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - posts, err := a.Srv.Store.Post().GetParentsForExportAfter(1000, afterId) + posts, err := a.Srv().Store.Post().GetParentsForExportAfter(1000, afterId) if err != nil { return err } @@ -381,7 +381,7 @@ func (a *App) ExportAllPosts(writer io.Writer) *model.AppError { func (a *App) buildPostReplies(postId string) (*[]ReplyImportData, *model.AppError) { var replies []ReplyImportData - replyPosts, err := a.Srv.Store.Post().GetRepliesForExport(postId) + replyPosts, err := a.Srv().Store.Post().GetRepliesForExport(postId) if err != nil { return nil, err } @@ -403,14 +403,14 @@ func (a *App) buildPostReplies(postId string) (*[]ReplyImportData, *model.AppErr func (a *App) BuildPostReactions(postId string) (*[]ReactionImportData, *model.AppError) { var reactionsOfPost []ReactionImportData - reactions, err := a.Srv.Store.Reaction().GetForPost(postId, true) + reactions, err := a.Srv().Store.Reaction().GetForPost(postId, true) if err != nil { return nil, err } for _, reaction := range reactions { var user *model.User - user, err = a.Srv.Store.User().Get(reaction.UserId) + user, err = a.Srv().Store.User().Get(reaction.UserId) if err != nil { if err.Id == store.MISSING_ACCOUNT_ERROR { // this is a valid case, the user that reacted might've been deleted by now mlog.Info("Skipping reactions by user since the entity doesn't exist anymore", mlog.String("user_id", reaction.UserId)) @@ -515,7 +515,7 @@ func (a *App) copyEmojiImages(emojiId string, emojiImagePath string, pathToDir s func (a *App) ExportAllDirectChannels(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - channels, err := a.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, afterId) + channels, err := a.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, afterId) if err != nil { return err } @@ -545,7 +545,7 @@ func (a *App) ExportAllDirectChannels(writer io.Writer) *model.AppError { func (a *App) ExportAllDirectPosts(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - posts, err := a.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, afterId) + posts, err := a.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, afterId) if err != nil { return err } diff --git a/app/export_test.go b/app/export_test.go index a2d521f43f..f0b2d9131e 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -89,7 +89,7 @@ func TestExportUserChannels(t *testing.T) { } var preferences model.Preferences preferences = append(preferences, preference) - err := th.App.Srv.Store.Preference().Save(&preferences) + err := th.App.Srv().Store.Preference().Save(&preferences) require.Nil(t, err) th.App.UpdateChannelMemberNotifyProps(notifyProps, channel.Id, user.Id) @@ -231,7 +231,7 @@ func TestExportDMChannel(t *testing.T) { err := th1.App.BulkExport(&b, "somefile", "somePath", "someDir") require.Nil(t, err) - channels, err := th1.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 1, len(channels)) @@ -240,7 +240,7 @@ func TestExportDMChannel(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 0, len(channels)) @@ -250,7 +250,7 @@ func TestExportDMChannel(t *testing.T) { assert.Equal(t, 0, i) // Ensure the Members of the imported DM channel is the same was from the exported - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 1, len(channels)) assert.ElementsMatch(t, []string{th1.BasicUser.Username, th1.BasicUser2.Username}, *channels[0].Members) @@ -267,14 +267,14 @@ func TestExportDMChannelToSelf(t *testing.T) { err := th1.App.BulkExport(&b, "somefile", "somePath", "someDir") require.Nil(t, err) - channels, err := th1.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 1, len(channels)) th2 := Setup(t) defer th2.TearDown() - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 0, len(channels)) @@ -283,7 +283,7 @@ func TestExportDMChannelToSelf(t *testing.T) { assert.Nil(t, err) assert.Equal(t, 0, i) - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 1, len(channels)) assert.Equal(t, 1, len((*channels[0].Members))) @@ -305,7 +305,7 @@ func TestExportGMChannel(t *testing.T) { err := th1.App.BulkExport(&b, "somefile", "somePath", "someDir") require.Nil(t, err) - channels, err := th1.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 1, len(channels)) @@ -314,7 +314,7 @@ func TestExportGMChannel(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 0, len(channels)) } @@ -337,7 +337,7 @@ func TestExportGMandDMChannels(t *testing.T) { err := th1.App.BulkExport(&b, "somefile", "somePath", "someDir") require.Nil(t, err) - channels, err := th1.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 2, len(channels)) @@ -346,7 +346,7 @@ func TestExportGMandDMChannels(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) assert.Equal(t, 0, len(channels)) @@ -356,7 +356,7 @@ func TestExportGMandDMChannels(t *testing.T) { assert.Equal(t, 0, i) // Ensure the Members of the imported GM channel is the same was from the exported - channels, err = th2.App.Srv.Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, err = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.Nil(t, err) // Adding some deteminism so its possible to assert on slice index @@ -412,7 +412,7 @@ func TestExportDMandGMPost(t *testing.T) { } th1.App.CreatePost(p4, gmChannel, false) - posts, err := th1.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) assert.Equal(t, 4, len(posts)) @@ -425,7 +425,7 @@ func TestExportDMandGMPost(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - posts, err = th2.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) assert.Equal(t, 0, len(posts)) @@ -434,7 +434,7 @@ func TestExportDMandGMPost(t *testing.T) { assert.Nil(t, err) assert.Equal(t, 0, i) - posts, err = th2.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) // Adding some deteminism so its possible to assert on slice index @@ -458,7 +458,7 @@ func TestExportDMPostWithSelf(t *testing.T) { err := th1.App.BulkExport(&b, "somefile", "somePath", "someDir") require.Nil(t, err) - posts, err := th1.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) assert.Equal(t, 1, len(posts)) @@ -467,7 +467,7 @@ func TestExportDMPostWithSelf(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - posts, err = th2.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) assert.Equal(t, 0, len(posts)) @@ -476,7 +476,7 @@ func TestExportDMPostWithSelf(t *testing.T) { assert.Nil(t, err) assert.Equal(t, 0, i) - posts, err = th2.App.Srv.Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.Nil(t, err) assert.Equal(t, 1, len(posts)) assert.Equal(t, 1, len((*posts[0].ChannelMembers))) diff --git a/app/file.go b/app/file.go index 056c70fe0e..bb7e440ce7 100644 --- a/app/file.go +++ b/app/file.go @@ -185,7 +185,7 @@ func (a *App) findTeamIdForFilename(post *model.Post, id, filename string) strin name, _ := url.QueryUnescape(filename) // This post is in a direct channel so we need to figure out what team the files are stored under. - teams, err := a.Srv.Store.Team().GetTeamsByUserId(post.UserId) + teams, err := a.Srv().Store.Team().GetTeamsByUserId(post.UserId) if err != nil { mlog.Error("Unable to get teams when migrating post to use FileInfo", mlog.Err(err), mlog.String("post_id", post.Id)) return "" @@ -237,7 +237,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { return []*model.FileInfo{} } - channel, errCh := a.Srv.Store.Channel().Get(post.ChannelId, true) + channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) // There's a weird bug that rarely happens where a post ends up with duplicate Filenames so remove those filenames := utils.RemoveDuplicatesFromStringArray(post.Filenames) if errCh != nil { @@ -290,7 +290,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { fileMigrationLock.Lock() defer fileMigrationLock.Unlock() - result, err := a.Srv.Store.Post().Get(post.Id, false) + result, err := a.Srv().Store.Post().Get(post.Id, false) if err != nil { mlog.Error("Unable to get post when migrating post to use FileInfos", mlog.Err(err), mlog.String("post_id", post.Id)) return []*model.FileInfo{} @@ -299,7 +299,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { if newPost := result.Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) { // Another thread has already created FileInfos for this post, so just return those var fileInfos []*model.FileInfo - fileInfos, err = a.Srv.Store.FileInfo().GetForPost(post.Id, true, false, false) + fileInfos, err = a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, false) if err != nil { mlog.Error("Unable to get FileInfos for migrated post", mlog.Err(err), mlog.String("post_id", post.Id)) return []*model.FileInfo{} @@ -314,7 +314,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { savedInfos := make([]*model.FileInfo, 0, len(infos)) fileIds := make([]string, 0, len(filenames)) for _, info := range infos { - if _, err = a.Srv.Store.FileInfo().Save(info); err != nil { + if _, err = a.Srv().Store.FileInfo().Save(info); err != nil { mlog.Error( "Unable to save file info when migrating post to use FileInfos", mlog.String("post_id", post.Id), @@ -337,7 +337,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { newPost.FileIds = fileIds // Update Posts to clear Filenames and set FileIds - if _, err = a.Srv.Store.Post().Update(newPost, post); err != nil { + if _, err = a.Srv().Store.Post().Update(newPost, post); err != nil { mlog.Error( "Unable to save migrated post when migrating to use FileInfos", mlog.String("new_file_ids", strings.Join(newPost.FileIds, ",")), @@ -457,43 +457,43 @@ func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, return info, err } -func UploadFileSetTeamId(teamId string) func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetTeamId(teamId string) func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.TeamId = filepath.Base(teamId) } } -func UploadFileSetUserId(userId string) func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetUserId(userId string) func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.UserId = filepath.Base(userId) } } -func UploadFileSetTimestamp(timestamp time.Time) func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetTimestamp(timestamp time.Time) func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.Timestamp = timestamp } } -func UploadFileSetContentLength(contentLength int64) func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetContentLength(contentLength int64) func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.ContentLength = contentLength } } -func UploadFileSetClientId(clientId string) func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetClientId(clientId string) func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.ClientId = clientId } } -func UploadFileSetRaw() func(t *uploadFileTask) { - return func(t *uploadFileTask) { +func UploadFileSetRaw() func(t *UploadFileTask) { + return func(t *UploadFileTask) { t.Raw = true } } -type uploadFileTask struct { +type UploadFileTask struct { // File name. Name string @@ -539,7 +539,7 @@ type uploadFileTask struct { saveToDatabase func(*model.FileInfo) (*model.FileInfo, *model.AppError) } -func (t *uploadFileTask) init(a *App) { +func (t *UploadFileTask) init(a *App) { t.buf = &bytes.Buffer{} t.maxFileSize = *a.Config().FileSettings.MaxFileSize t.limit = *a.Config().FileSettings.MaxFileSize @@ -571,7 +571,7 @@ func (t *uploadFileTask) init(a *App) { t.pluginsEnvironment = a.GetPluginsEnvironment() t.writeFile = a.WriteFile - t.saveToDatabase = a.Srv.Store.FileInfo().Save + t.saveToDatabase = a.Srv().Store.FileInfo().Save } // UploadFileX uploads a single file as specified in t. It applies the upload @@ -580,9 +580,9 @@ func (t *uploadFileTask) init(a *App) { // upload, returning a rejection error. In this case FileInfo would have // contained the last "good" FileInfo before the execution of that plugin. func (a *App) UploadFileX(channelId, name string, input io.Reader, - opts ...func(*uploadFileTask)) (*model.FileInfo, *model.AppError) { + opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) { - t := &uploadFileTask{ + t := &UploadFileTask{ ChannelId: filepath.Base(channelId), Name: filepath.Base(name), Input: input, @@ -644,7 +644,7 @@ func (a *App) UploadFileX(channelId, name string, input io.Reader, return t.fileinfo, nil } -func (t *uploadFileTask) readAll() *model.AppError { +func (t *UploadFileTask) readAll() *model.AppError { _, err := t.buf.ReadFrom(t.limitedInput) if err != nil { // Ugly hack: the error is not exported from net/http. @@ -666,7 +666,7 @@ func (t *uploadFileTask) readAll() *model.AppError { return nil } -func (t *uploadFileTask) runPlugins() *model.AppError { +func (t *UploadFileTask) runPlugins() *model.AppError { if t.pluginsEnvironment == nil { return nil } @@ -703,7 +703,7 @@ func (t *uploadFileTask) runPlugins() *model.AppError { return nil } -func (t *uploadFileTask) preprocessImage() *model.AppError { +func (t *UploadFileTask) preprocessImage() *model.AppError { // If SVG, attempt to extract dimensions and then return if t.fileinfo.MimeType == "image/svg+xml" { svgInfo, err := parseSVG(t.newReader()) @@ -767,7 +767,7 @@ func (t *uploadFileTask) preprocessImage() *model.AppError { return nil } -func (t *uploadFileTask) postprocessImage() { +func (t *UploadFileTask) postprocessImage() { // don't try to process SVG files if t.fileinfo.MimeType == "image/svg+xml" { return @@ -845,7 +845,7 @@ func (t *uploadFileTask) postprocessImage() { wg.Wait() } -func (t uploadFileTask) newReader() io.Reader { +func (t UploadFileTask) newReader() io.Reader { if t.teeInput != nil { return io.MultiReader(bytes.NewReader(t.buf.Bytes()), t.teeInput) } else { @@ -853,7 +853,7 @@ func (t uploadFileTask) newReader() io.Reader { } } -func (t uploadFileTask) pathPrefix() string { +func (t UploadFileTask) pathPrefix() string { return t.Timestamp.Format("20060102") + "/teams/" + t.TeamId + "/channels/" + t.ChannelId + @@ -861,7 +861,7 @@ func (t uploadFileTask) pathPrefix() string { "/" + t.fileinfo.Id + "/" } -func (t uploadFileTask) newAppError(id string, details interface{}, httpStatus int, extra ...interface{}) *model.AppError { +func (t UploadFileTask) newAppError(id string, details interface{}, httpStatus int, extra ...interface{}) *model.AppError { params := map[string]interface{}{ "Name": t.Name, "Filename": t.Name, @@ -950,7 +950,7 @@ func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, ra return nil, data, err } - if _, err := a.Srv.Store.FileInfo().Save(info); err != nil { + if _, err := a.Srv().Store.FileInfo().Save(info); err != nil { return nil, data, err } @@ -1094,7 +1094,7 @@ func (a *App) generatePreviewImage(img image.Image, previewPath string, width in } func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) { - return a.Srv.Store.FileInfo().Get(fileId) + return a.Srv().Store.FileInfo().Get(fileId) } func (a *App) GetFile(fileId string) ([]byte, *model.AppError) { @@ -1117,7 +1117,7 @@ func (a *App) CopyFileInfos(userId string, fileIds []string) ([]string, *model.A now := model.GetMillis() for _, fileId := range fileIds { - fileInfo, err := a.Srv.Store.FileInfo().Get(fileId) + fileInfo, err := a.Srv().Store.FileInfo().Get(fileId) if err != nil { return nil, err } @@ -1128,7 +1128,7 @@ func (a *App) CopyFileInfos(userId string, fileIds []string) ([]string, *model.A fileInfo.UpdateAt = now fileInfo.PostId = "" - if _, err := a.Srv.Store.FileInfo().Save(fileInfo); err != nil { + if _, err := a.Srv().Store.FileInfo().Save(fileInfo); err != nil { return newFileIds, err } diff --git a/app/file.go.orig b/app/file.go.orig new file mode 100644 index 0000000000..056c70fe0e --- /dev/null +++ b/app/file.go.orig @@ -0,0 +1,1139 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package app + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "fmt" + "image" + "image/color" + "image/draw" + "image/gif" + "image/jpeg" + "io" + "mime/multipart" + "net/http" + "net/url" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "github.com/disintegration/imaging" + "github.com/rwcarlsen/goexif/exif" + _ "golang.org/x/image/bmp" + + "github.com/mattermost/mattermost-server/v5/mlog" + "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/plugin" + "github.com/mattermost/mattermost-server/v5/services/filesstore" + "github.com/mattermost/mattermost-server/v5/utils" +) + +const ( + /* + EXIF Image Orientations + 1 2 3 4 5 6 7 8 + + 888888 888888 88 88 8888888888 88 88 8888888888 + 88 88 88 88 88 88 88 88 88 88 88 88 + 8888 8888 8888 8888 88 8888888888 8888888888 88 + 88 88 88 88 + 88 88 888888 888888 + */ + Upright = 1 + UprightMirrored = 2 + UpsideDown = 3 + UpsideDownMirrored = 4 + RotatedCWMirrored = 5 + RotatedCCW = 6 + RotatedCCWMirrored = 7 + RotatedCW = 8 + + MaxImageSize = 6048 * 4032 // 24 megapixels, roughly 36MB as a raw image + ImageThumbnailWidth = 120 + ImageThumbnailHeight = 100 + ImageThumbnailRatio = float64(ImageThumbnailHeight) / float64(ImageThumbnailWidth) + ImagePreviewWidth = 1920 + + UploadFileInitialBufferSize = 2 * 1024 * 1024 // 2Mb + + // Deprecated + IMAGE_THUMBNAIL_PIXEL_WIDTH = 120 + IMAGE_THUMBNAIL_PIXEL_HEIGHT = 100 + IMAGE_PREVIEW_PIXEL_WIDTH = 1920 +) + +func (a *App) FileBackend() (filesstore.FileBackend, *model.AppError) { + license := a.License() + return filesstore.NewFileBackend(&a.Config().FileSettings, license != nil && *license.Features.Compliance) +} + +func (a *App) ReadFile(path string) ([]byte, *model.AppError) { + backend, err := a.FileBackend() + if err != nil { + return nil, err + } + return backend.ReadFile(path) +} + +// Caller must close the first return value +func (a *App) FileReader(path string) (filesstore.ReadCloseSeeker, *model.AppError) { + backend, err := a.FileBackend() + if err != nil { + return nil, err + } + return backend.Reader(path) +} + +func (a *App) FileExists(path string) (bool, *model.AppError) { + backend, err := a.FileBackend() + if err != nil { + return false, err + } + return backend.FileExists(path) +} + +func (a *App) MoveFile(oldPath, newPath string) *model.AppError { + backend, err := a.FileBackend() + if err != nil { + return err + } + return backend.MoveFile(oldPath, newPath) +} + +func (a *App) WriteFile(fr io.Reader, path string) (int64, *model.AppError) { + backend, err := a.FileBackend() + if err != nil { + return 0, err + } + + return backend.WriteFile(fr, path) +} + +func (a *App) RemoveFile(path string) *model.AppError { + backend, err := a.FileBackend() + if err != nil { + return err + } + return backend.RemoveFile(path) +} + +func (a *App) ListDirectory(path string) ([]string, *model.AppError) { + backend, err := a.FileBackend() + if err != nil { + return nil, err + } + paths, err := backend.ListDirectory(path) + if err != nil { + return nil, err + } + + return *paths, nil +} + +func (a *App) getInfoForFilename(post *model.Post, teamId, channelId, userId, oldId, filename string) *model.FileInfo { + name, _ := url.QueryUnescape(filename) + pathPrefix := fmt.Sprintf("teams/%s/channels/%s/users/%s/%s/", teamId, channelId, userId, oldId) + path := pathPrefix + name + + // Open the file and populate the fields of the FileInfo + data, err := a.ReadFile(path) + if err != nil { + mlog.Error( + "File not found when migrating post to use FileInfos", + mlog.String("post_id", post.Id), + mlog.String("filename", filename), + mlog.String("path", path), + mlog.Err(err), + ) + return nil + } + + info, err := model.GetInfoForBytes(name, data) + if err != nil { + mlog.Warn( + "Unable to fully decode file info when migrating post to use FileInfos", + mlog.String("post_id", post.Id), + mlog.String("filename", filename), + mlog.Err(err), + ) + } + + // Generate a new ID because with the old system, you could very rarely get multiple posts referencing the same file + info.Id = model.NewId() + info.CreatorId = post.UserId + info.PostId = post.Id + info.CreateAt = post.CreateAt + info.UpdateAt = post.UpdateAt + info.Path = path + + if info.IsImage() { + nameWithoutExtension := name[:strings.LastIndex(name, ".")] + info.PreviewPath = pathPrefix + nameWithoutExtension + "_preview.jpg" + info.ThumbnailPath = pathPrefix + nameWithoutExtension + "_thumb.jpg" + } + + return info +} + +func (a *App) findTeamIdForFilename(post *model.Post, id, filename string) string { + name, _ := url.QueryUnescape(filename) + + // This post is in a direct channel so we need to figure out what team the files are stored under. + teams, err := a.Srv.Store.Team().GetTeamsByUserId(post.UserId) + if err != nil { + mlog.Error("Unable to get teams when migrating post to use FileInfo", mlog.Err(err), mlog.String("post_id", post.Id)) + return "" + } + + if len(teams) == 1 { + // The user has only one team so the post must've been sent from it + return teams[0].Id + } + + for _, team := range teams { + path := fmt.Sprintf("teams/%s/channels/%s/users/%s/%s/%s", team.Id, post.ChannelId, post.UserId, id, name) + if ok, err := a.FileExists(path); ok && err == nil { + // Found the team that this file was posted from + return team.Id + } + } + + return "" +} + +var fileMigrationLock sync.Mutex +var oldFilenameMatchExp *regexp.Regexp = regexp.MustCompile(`^\/([a-z\d]{26})\/([a-z\d]{26})\/([a-z\d]{26})\/([^\/]+)$`) + +// Parse the path from the Filename of the form /{channelId}/{userId}/{uid}/{nameWithExtension} +func parseOldFilenames(filenames []string, channelId, userId string) [][]string { + parsed := [][]string{} + for _, filename := range filenames { + matches := oldFilenameMatchExp.FindStringSubmatch(filename) + if len(matches) != 5 { + mlog.Error("Failed to parse old Filename", mlog.String("filename", filename)) + continue + } + if matches[1] != channelId { + mlog.Error("ChannelId in Filename does not match", mlog.String("channel_id", channelId), mlog.String("matched", matches[1])) + } else if matches[2] != userId { + mlog.Error("UserId in Filename does not match", mlog.String("user_id", userId), mlog.String("matched", matches[2])) + } else { + parsed = append(parsed, matches[1:]) + } + } + return parsed +} + +// Creates and stores FileInfos for a post created before the FileInfos table existed. +func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { + if len(post.Filenames) == 0 { + mlog.Warn("Unable to migrate post to use FileInfos with an empty Filenames field", mlog.String("post_id", post.Id)) + return []*model.FileInfo{} + } + + channel, errCh := a.Srv.Store.Channel().Get(post.ChannelId, true) + // There's a weird bug that rarely happens where a post ends up with duplicate Filenames so remove those + filenames := utils.RemoveDuplicatesFromStringArray(post.Filenames) + if errCh != nil { + mlog.Error( + "Unable to get channel when migrating post to use FileInfos", + mlog.String("post_id", post.Id), + mlog.String("channel_id", post.ChannelId), + mlog.Err(errCh), + ) + return []*model.FileInfo{} + } + + // Parse and validate filenames before further processing + parsedFilenames := parseOldFilenames(filenames, post.ChannelId, post.UserId) + + if len(parsedFilenames) == 0 { + mlog.Error("Unable to parse filenames") + return []*model.FileInfo{} + } + + // Find the team that was used to make this post since its part of the file path that isn't saved in the Filename + var teamId string + if channel.TeamId == "" { + // This post was made in a cross-team DM channel, so we need to find where its files were saved + teamId = a.findTeamIdForFilename(post, parsedFilenames[0][2], parsedFilenames[0][3]) + } else { + teamId = channel.TeamId + } + + // Create FileInfo objects for this post + infos := make([]*model.FileInfo, 0, len(filenames)) + if teamId == "" { + mlog.Error( + "Unable to find team id for files when migrating post to use FileInfos", + mlog.String("filenames", strings.Join(filenames, ",")), + mlog.String("post_id", post.Id), + ) + } else { + for _, parsed := range parsedFilenames { + info := a.getInfoForFilename(post, teamId, parsed[0], parsed[1], parsed[2], parsed[3]) + if info == nil { + continue + } + + infos = append(infos, info) + } + } + + // Lock to prevent only one migration thread from trying to update the post at once, preventing duplicate FileInfos from being created + fileMigrationLock.Lock() + defer fileMigrationLock.Unlock() + + result, err := a.Srv.Store.Post().Get(post.Id, false) + if err != nil { + mlog.Error("Unable to get post when migrating post to use FileInfos", mlog.Err(err), mlog.String("post_id", post.Id)) + return []*model.FileInfo{} + } + + if newPost := result.Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) { + // Another thread has already created FileInfos for this post, so just return those + var fileInfos []*model.FileInfo + fileInfos, err = a.Srv.Store.FileInfo().GetForPost(post.Id, true, false, false) + if err != nil { + mlog.Error("Unable to get FileInfos for migrated post", mlog.Err(err), mlog.String("post_id", post.Id)) + return []*model.FileInfo{} + } + + mlog.Debug("Post already migrated to use FileInfos", mlog.String("post_id", post.Id)) + return fileInfos + } + + mlog.Debug("Migrating post to use FileInfos", mlog.String("post_id", post.Id)) + + savedInfos := make([]*model.FileInfo, 0, len(infos)) + fileIds := make([]string, 0, len(filenames)) + for _, info := range infos { + if _, err = a.Srv.Store.FileInfo().Save(info); err != nil { + mlog.Error( + "Unable to save file info when migrating post to use FileInfos", + mlog.String("post_id", post.Id), + mlog.String("file_info_id", info.Id), + mlog.String("file_info_path", info.Path), + mlog.Err(err), + ) + continue + } + + savedInfos = append(savedInfos, info) + fileIds = append(fileIds, info.Id) + } + + // Copy and save the updated post + newPost := &model.Post{} + *newPost = *post + + newPost.Filenames = []string{} + newPost.FileIds = fileIds + + // Update Posts to clear Filenames and set FileIds + if _, err = a.Srv.Store.Post().Update(newPost, post); err != nil { + mlog.Error( + "Unable to save migrated post when migrating to use FileInfos", + mlog.String("new_file_ids", strings.Join(newPost.FileIds, ",")), + mlog.String("old_filenames", strings.Join(post.Filenames, ",")), + mlog.String("post_id", post.Id), + mlog.Err(err), + ) + return []*model.FileInfo{} + } + return savedInfos +} + +func (a *App) GeneratePublicLink(siteURL string, info *model.FileInfo) string { + hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt) + return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash) +} + +func GeneratePublicLinkHash(fileId, salt string) string { + hash := sha256.New() + hash.Write([]byte(salt)) + hash.Write([]byte(fileId)) + + return base64.RawURLEncoding.EncodeToString(hash.Sum(nil)) +} + +func (a *App) UploadMultipartFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { + files := make([]io.ReadCloser, len(fileHeaders)) + filenames := make([]string, len(fileHeaders)) + + for i, fileHeader := range fileHeaders { + file, fileErr := fileHeader.Open() + if fileErr != nil { + return nil, model.NewAppError("UploadFiles", "api.file.upload_file.read_request.app_error", + map[string]interface{}{"Filename": fileHeader.Filename}, fileErr.Error(), http.StatusBadRequest) + } + + // Will be closed after UploadFiles returns + defer file.Close() + + files[i] = file + filenames[i] = fileHeader.Filename + } + + return a.UploadFiles(teamId, channelId, userId, files, filenames, clientIds, now) +} + +// Uploads some files to the given team and channel as the given user. files and filenames should have +// the same length. clientIds should either not be provided or have the same length as files and filenames. +// The provided files should be closed by the caller so that they are not leaked. +func (a *App) UploadFiles(teamId string, channelId string, userId string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { + if len(*a.Config().FileSettings.DriverName) == 0 { + return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) + } + + if len(filenames) != len(files) || (len(clientIds) > 0 && len(clientIds) != len(files)) { + return nil, model.NewAppError("UploadFiles", "api.file.upload_file.incorrect_number_of_files.app_error", nil, "", http.StatusBadRequest) + } + + resStruct := &model.FileUploadResponse{ + FileInfos: []*model.FileInfo{}, + ClientIds: []string{}, + } + + previewPathList := []string{} + thumbnailPathList := []string{} + imageDataList := [][]byte{} + + for i, file := range files { + buf := bytes.NewBuffer(nil) + io.Copy(buf, file) + data := buf.Bytes() + + info, data, err := a.DoUploadFileExpectModification(now, teamId, channelId, userId, filenames[i], data) + if err != nil { + return nil, err + } + + if info.PreviewPath != "" || info.ThumbnailPath != "" { + previewPathList = append(previewPathList, info.PreviewPath) + thumbnailPathList = append(thumbnailPathList, info.ThumbnailPath) + imageDataList = append(imageDataList, data) + } + + resStruct.FileInfos = append(resStruct.FileInfos, info) + + if len(clientIds) > 0 { + resStruct.ClientIds = append(resStruct.ClientIds, clientIds[i]) + } + } + + a.HandleImages(previewPathList, thumbnailPathList, imageDataList) + + return resStruct, nil +} + +// UploadFile uploads a single file in form of a completely constructed byte array for a channel. +func (a *App) UploadFile(data []byte, channelId string, filename string) (*model.FileInfo, *model.AppError) { + info, _, appError := a.DoUploadFileExpectModification(time.Now(), "noteam", channelId, "nouser", filename, data) + + if appError != nil { + return nil, appError + } + + if info.PreviewPath != "" || info.ThumbnailPath != "" { + previewPathList := []string{info.PreviewPath} + thumbnailPathList := []string{info.ThumbnailPath} + imageDataList := [][]byte{data} + + a.HandleImages(previewPathList, thumbnailPathList, imageDataList) + } + + return info, nil +} + +func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { + info, _, err := a.DoUploadFileExpectModification(now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) + return info, err +} + +func UploadFileSetTeamId(teamId string) func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.TeamId = filepath.Base(teamId) + } +} + +func UploadFileSetUserId(userId string) func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.UserId = filepath.Base(userId) + } +} + +func UploadFileSetTimestamp(timestamp time.Time) func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.Timestamp = timestamp + } +} + +func UploadFileSetContentLength(contentLength int64) func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.ContentLength = contentLength + } +} + +func UploadFileSetClientId(clientId string) func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.ClientId = clientId + } +} + +func UploadFileSetRaw() func(t *uploadFileTask) { + return func(t *uploadFileTask) { + t.Raw = true + } +} + +type uploadFileTask struct { + // File name. + Name string + + ChannelId string + TeamId string + UserId string + + // Time stamp to use when creating the file. + Timestamp time.Time + + // The value of the Content-Length http header, when available. + ContentLength int64 + + // The file data stream. + Input io.Reader + + // An optional, client-assigned Id field. + ClientId string + + // If Raw, do not execute special processing for images, just upload + // the file. Plugins are still invoked. + Raw bool + + //============================================================= + // Internal state + + buf *bytes.Buffer + limit int64 + limitedInput io.Reader + teeInput io.Reader + fileinfo *model.FileInfo + maxFileSize int64 + + // Cached image data that (may) get initialized in preprocessImage and + // is used in postprocessImage + decoded image.Image + imageType string + imageOrientation int + + // Testing: overrideable dependency functions + pluginsEnvironment *plugin.Environment + writeFile func(io.Reader, string) (int64, *model.AppError) + saveToDatabase func(*model.FileInfo) (*model.FileInfo, *model.AppError) +} + +func (t *uploadFileTask) init(a *App) { + t.buf = &bytes.Buffer{} + t.maxFileSize = *a.Config().FileSettings.MaxFileSize + t.limit = *a.Config().FileSettings.MaxFileSize + + t.fileinfo = model.NewInfo(filepath.Base(t.Name)) + t.fileinfo.Id = model.NewId() + t.fileinfo.CreatorId = t.UserId + t.fileinfo.CreateAt = t.Timestamp.UnixNano() / int64(time.Millisecond) + t.fileinfo.Path = t.pathPrefix() + t.Name + + // Prepare to read ContentLength if it is known, otherwise limit + // ourselves to MaxFileSize. Add an extra byte to check and fail if the + // client sent too many bytes. + if t.ContentLength > 0 { + t.limit = t.ContentLength + // Over-Grow the buffer to prevent bytes.ReadFrom from doing it + // at the very end. + t.buf.Grow(int(t.limit + 1 + bytes.MinRead)) + } else { + // If we don't know the upload size, grow the buffer somewhat + // anyway to avoid extra reslicing. + t.buf.Grow(UploadFileInitialBufferSize) + } + t.limitedInput = &io.LimitedReader{ + R: t.Input, + N: t.limit + 1, + } + t.teeInput = io.TeeReader(t.limitedInput, t.buf) + + t.pluginsEnvironment = a.GetPluginsEnvironment() + t.writeFile = a.WriteFile + t.saveToDatabase = a.Srv.Store.FileInfo().Save +} + +// UploadFileX uploads a single file as specified in t. It applies the upload +// constraints, executes plugins and image processing logic as needed. It +// returns a filled-out FileInfo and an optional error. A plugin may reject the +// upload, returning a rejection error. In this case FileInfo would have +// contained the last "good" FileInfo before the execution of that plugin. +func (a *App) UploadFileX(channelId, name string, input io.Reader, + opts ...func(*uploadFileTask)) (*model.FileInfo, *model.AppError) { + + t := &uploadFileTask{ + ChannelId: filepath.Base(channelId), + Name: filepath.Base(name), + Input: input, + } + for _, o := range opts { + o(t) + } + t.init(a) + + if len(*a.Config().FileSettings.DriverName) == 0 { + return nil, t.newAppError("api.file.upload_file.storage.app_error", + "", http.StatusNotImplemented) + } + if t.ContentLength > t.maxFileSize { + return nil, t.newAppError("api.file.upload_file.too_large_detailed.app_error", + "", http.StatusRequestEntityTooLarge, "Length", t.ContentLength, "Limit", t.maxFileSize) + } + + var aerr *model.AppError + if !t.Raw && t.fileinfo.IsImage() { + aerr = t.preprocessImage() + if aerr != nil { + return t.fileinfo, aerr + } + } + + aerr = t.readAll() + if aerr != nil { + return t.fileinfo, aerr + } + + aerr = t.runPlugins() + if aerr != nil { + return t.fileinfo, aerr + } + + // Concurrently upload and update DB, and post-process the image. + wg := sync.WaitGroup{} + + if !t.Raw && t.fileinfo.IsImage() { + wg.Add(1) + go func() { + t.postprocessImage() + wg.Done() + }() + } + + _, aerr = t.writeFile(t.newReader(), t.fileinfo.Path) + if aerr != nil { + return nil, aerr + } + + if _, err := t.saveToDatabase(t.fileinfo); err != nil { + return nil, err + } + + wg.Wait() + + return t.fileinfo, nil +} + +func (t *uploadFileTask) readAll() *model.AppError { + _, err := t.buf.ReadFrom(t.limitedInput) + if err != nil { + // Ugly hack: the error is not exported from net/http. + if err.Error() == "http: request body too large" { + return t.newAppError("api.file.upload_file.too_large_detailed.app_error", + "", http.StatusRequestEntityTooLarge, "Length", t.buf.Len(), "Limit", t.limit) + } + return t.newAppError("api.file.upload_file.read_request.app_error", + err.Error(), http.StatusBadRequest) + } + if int64(t.buf.Len()) > t.limit { + return t.newAppError("api.file.upload_file.too_large_detailed.app_error", + "", http.StatusRequestEntityTooLarge, "Length", t.buf.Len(), "Limit", t.limit) + } + t.fileinfo.Size = int64(t.buf.Len()) + + t.limitedInput = nil + t.teeInput = nil + return nil +} + +func (t *uploadFileTask) runPlugins() *model.AppError { + if t.pluginsEnvironment == nil { + return nil + } + + pluginContext := &plugin.Context{} + var rejectionError *model.AppError + + t.pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { + buf := &bytes.Buffer{} + replacementInfo, rejectionReason := hooks.FileWillBeUploaded(pluginContext, + t.fileinfo, t.newReader(), buf) + if rejectionReason != "" { + rejectionError = t.newAppError("api.file.upload_file.rejected_by_plugin.app_error", + rejectionReason, http.StatusForbidden, "Reason", rejectionReason) + return false + } + if replacementInfo != nil { + t.fileinfo = replacementInfo + } + if buf.Len() != 0 { + t.buf = buf + t.teeInput = nil + t.limitedInput = nil + t.fileinfo.Size = int64(buf.Len()) + } + + return true + }, plugin.FileWillBeUploadedId) + + if rejectionError != nil { + return rejectionError + } + + return nil +} + +func (t *uploadFileTask) preprocessImage() *model.AppError { + // If SVG, attempt to extract dimensions and then return + if t.fileinfo.MimeType == "image/svg+xml" { + svgInfo, err := parseSVG(t.newReader()) + if err != nil { + mlog.Error("Failed to parse SVG", mlog.Err(err)) + } + if svgInfo.Width > 0 && svgInfo.Height > 0 { + t.fileinfo.Width = svgInfo.Width + t.fileinfo.Height = svgInfo.Height + } + t.fileinfo.HasPreviewImage = false + return nil + } + + // If we fail to decode, return "as is". + config, _, err := image.DecodeConfig(t.newReader()) + if err != nil { + return nil + } + + t.fileinfo.Width = config.Width + t.fileinfo.Height = config.Height + + // Check dimensions before loading the whole thing into memory later on. + if t.fileinfo.Width*t.fileinfo.Height > MaxImageSize { + return t.newAppError("api.file.upload_file.large_image_detailed.app_error", + "", http.StatusBadRequest) + } + t.fileinfo.HasPreviewImage = true + nameWithoutExtension := t.Name[:strings.LastIndex(t.Name, ".")] + t.fileinfo.PreviewPath = t.pathPrefix() + nameWithoutExtension + "_preview.jpg" + t.fileinfo.ThumbnailPath = t.pathPrefix() + nameWithoutExtension + "_thumb.jpg" + + // check the image orientation with goexif; consume the bytes we + // already have first, then keep Tee-ing from input. + // TODO: try to reuse exif's .Raw buffer rather than Tee-ing + if t.imageOrientation, err = getImageOrientation(t.newReader()); err == nil && + (t.imageOrientation == RotatedCWMirrored || + t.imageOrientation == RotatedCCW || + t.imageOrientation == RotatedCCWMirrored || + t.imageOrientation == RotatedCW) { + t.fileinfo.Width, t.fileinfo.Height = t.fileinfo.Height, t.fileinfo.Width + } + + // For animated GIFs disable the preview; since we have to Decode gifs + // anyway, cache the decoded image for later. + if t.fileinfo.MimeType == "image/gif" { + gifConfig, err := gif.DecodeAll(t.newReader()) + if err == nil { + if len(gifConfig.Image) >= 1 { + t.fileinfo.HasPreviewImage = false + + } + if len(gifConfig.Image) > 0 { + t.decoded = gifConfig.Image[0] + t.imageType = "gif" + } + } + } + + return nil +} + +func (t *uploadFileTask) postprocessImage() { + // don't try to process SVG files + if t.fileinfo.MimeType == "image/svg+xml" { + return + } + + decoded, typ := t.decoded, t.imageType + if decoded == nil { + var err error + decoded, typ, err = image.Decode(t.newReader()) + if err != nil { + mlog.Error("Unable to decode image", mlog.Err(err)) + return + } + } + + // Fill in the background of a potentially-transparent png file as + // white. + if typ == "png" { + dst := image.NewRGBA(decoded.Bounds()) + draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) + draw.Draw(dst, dst.Bounds(), decoded, decoded.Bounds().Min, draw.Over) + decoded = dst + } + + decoded = makeImageUpright(decoded, t.imageOrientation) + if decoded == nil { + return + } + + writeJPEG := func(img image.Image, path string) { + r, w := io.Pipe() + go func() { + _, aerr := t.writeFile(r, path) + if aerr != nil { + mlog.Error("Unable to upload", mlog.String("path", path), mlog.Err(aerr)) + return + } + }() + + err := jpeg.Encode(w, img, &jpeg.Options{Quality: 90}) + if err != nil { + mlog.Error("Unable to encode image as jpeg", mlog.String("path", path), mlog.Err(err)) + w.CloseWithError(err) + } else { + w.Close() + } + } + + w := decoded.Bounds().Dx() + h := decoded.Bounds().Dy() + + wg := &sync.WaitGroup{} + wg.Add(2) + go func() { + defer wg.Done() + thumb := decoded + if h > ImageThumbnailHeight || w > ImageThumbnailWidth { + if float64(h)/float64(w) < ImageThumbnailRatio { + thumb = imaging.Resize(decoded, 0, ImageThumbnailHeight, imaging.Lanczos) + } else { + thumb = imaging.Resize(decoded, ImageThumbnailWidth, 0, imaging.Lanczos) + } + } + writeJPEG(thumb, t.fileinfo.ThumbnailPath) + }() + + go func() { + defer wg.Done() + preview := decoded + if w > ImagePreviewWidth { + preview = imaging.Resize(decoded, ImagePreviewWidth, 0, imaging.Lanczos) + } + writeJPEG(preview, t.fileinfo.PreviewPath) + }() + wg.Wait() +} + +func (t uploadFileTask) newReader() io.Reader { + if t.teeInput != nil { + return io.MultiReader(bytes.NewReader(t.buf.Bytes()), t.teeInput) + } else { + return bytes.NewReader(t.buf.Bytes()) + } +} + +func (t uploadFileTask) pathPrefix() string { + return t.Timestamp.Format("20060102") + + "/teams/" + t.TeamId + + "/channels/" + t.ChannelId + + "/users/" + t.UserId + + "/" + t.fileinfo.Id + "/" +} + +func (t uploadFileTask) newAppError(id string, details interface{}, httpStatus int, extra ...interface{}) *model.AppError { + params := map[string]interface{}{ + "Name": t.Name, + "Filename": t.Name, + "ChannelId": t.ChannelId, + "TeamId": t.TeamId, + "UserId": t.UserId, + "ContentLength": t.ContentLength, + "ClientId": t.ClientId, + } + if t.fileinfo != nil { + params["Width"] = t.fileinfo.Width + params["Height"] = t.fileinfo.Height + } + for i := 0; i+1 < len(extra); i += 2 { + params[fmt.Sprintf("%v", extra[i])] = extra[i+1] + } + + return model.NewAppError("uploadFileTask", id, params, fmt.Sprintf("%v", details), httpStatus) +} + +func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) { + filename := filepath.Base(rawFilename) + teamId := filepath.Base(rawTeamId) + channelId := filepath.Base(rawChannelId) + userId := filepath.Base(rawUserId) + + info, err := model.GetInfoForBytes(filename, data) + if err != nil { + err.StatusCode = http.StatusBadRequest + return nil, data, err + } + + if orientation, err := getImageOrientation(bytes.NewReader(data)); err == nil && + (orientation == RotatedCWMirrored || + orientation == RotatedCCW || + orientation == RotatedCCWMirrored || + orientation == RotatedCW) { + info.Width, info.Height = info.Height, info.Width + } + + info.Id = model.NewId() + info.CreatorId = userId + info.CreateAt = now.UnixNano() / int64(time.Millisecond) + + pathPrefix := now.Format("20060102") + "/teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + info.Id + "/" + info.Path = pathPrefix + filename + + if info.IsImage() { + // Check dimensions before loading the whole thing into memory later on + if info.Width*info.Height > MaxImageSize { + err := model.NewAppError("uploadFile", "api.file.upload_file.large_image.app_error", map[string]interface{}{"Filename": filename}, "", http.StatusBadRequest) + return nil, data, err + } + + nameWithoutExtension := filename[:strings.LastIndex(filename, ".")] + info.PreviewPath = pathPrefix + nameWithoutExtension + "_preview.jpg" + info.ThumbnailPath = pathPrefix + nameWithoutExtension + "_thumb.jpg" + } + + if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { + var rejectionError *model.AppError + pluginContext := a.PluginContext() + pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { + var newBytes bytes.Buffer + replacementInfo, rejectionReason := hooks.FileWillBeUploaded(pluginContext, info, bytes.NewReader(data), &newBytes) + if rejectionReason != "" { + rejectionError = model.NewAppError("DoUploadFile", "File rejected by plugin. "+rejectionReason, nil, "", http.StatusBadRequest) + return false + } + if replacementInfo != nil { + info = replacementInfo + } + if newBytes.Len() != 0 { + data = newBytes.Bytes() + info.Size = int64(len(data)) + } + + return true + }, plugin.FileWillBeUploadedId) + if rejectionError != nil { + return nil, data, rejectionError + } + } + + if _, err := a.WriteFile(bytes.NewReader(data), info.Path); err != nil { + return nil, data, err + } + + if _, err := a.Srv.Store.FileInfo().Save(info); err != nil { + return nil, data, err + } + + return info, data, nil +} + +func (a *App) HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) { + wg := new(sync.WaitGroup) + + for i := range fileData { + img, width, height := prepareImage(fileData[i]) + if img != nil { + wg.Add(2) + go func(img image.Image, path string, width int, height int) { + defer wg.Done() + a.generateThumbnailImage(img, path, width, height) + }(img, thumbnailPathList[i], width, height) + + go func(img image.Image, path string, width int) { + defer wg.Done() + a.generatePreviewImage(img, path, width) + }(img, previewPathList[i], width) + } + } + wg.Wait() +} + +func prepareImage(fileData []byte) (image.Image, int, int) { + // Decode image bytes into Image object + img, imgType, err := image.Decode(bytes.NewReader(fileData)) + if err != nil { + mlog.Error("Unable to decode image", mlog.Err(err)) + return nil, 0, 0 + } + + width := img.Bounds().Dx() + height := img.Bounds().Dy() + + // Fill in the background of a potentially-transparent png file as white + if imgType == "png" { + dst := image.NewRGBA(img.Bounds()) + draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) + draw.Draw(dst, dst.Bounds(), img, img.Bounds().Min, draw.Over) + img = dst + } + + // Flip the image to be upright + orientation, _ := getImageOrientation(bytes.NewReader(fileData)) + img = makeImageUpright(img, orientation) + + return img, width, height +} + +func makeImageUpright(img image.Image, orientation int) image.Image { + switch orientation { + case UprightMirrored: + return imaging.FlipH(img) + case UpsideDown: + return imaging.Rotate180(img) + case UpsideDownMirrored: + return imaging.FlipV(img) + case RotatedCWMirrored: + return imaging.Transpose(img) + case RotatedCCW: + return imaging.Rotate270(img) + case RotatedCCWMirrored: + return imaging.Transverse(img) + case RotatedCW: + return imaging.Rotate90(img) + default: + return img + } +} + +func getImageOrientation(input io.Reader) (int, error) { + exifData, err := exif.Decode(input) + if err != nil { + return Upright, err + } + + tag, err := exifData.Get("Orientation") + if err != nil { + return Upright, err + } + + orientation, err := tag.Int(0) + if err != nil { + return Upright, err + } + + return orientation, nil +} + +func (a *App) generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) { + thumbWidth := float64(IMAGE_THUMBNAIL_PIXEL_WIDTH) + thumbHeight := float64(IMAGE_THUMBNAIL_PIXEL_HEIGHT) + imgWidth := float64(width) + imgHeight := float64(height) + + var thumbnail image.Image + if imgHeight < IMAGE_THUMBNAIL_PIXEL_HEIGHT && imgWidth < thumbWidth { + thumbnail = img + } else if imgHeight/imgWidth < thumbHeight/thumbWidth { + thumbnail = imaging.Resize(img, 0, IMAGE_THUMBNAIL_PIXEL_HEIGHT, imaging.Lanczos) + } else { + thumbnail = imaging.Resize(img, IMAGE_THUMBNAIL_PIXEL_WIDTH, 0, imaging.Lanczos) + } + + buf := new(bytes.Buffer) + if err := jpeg.Encode(buf, thumbnail, &jpeg.Options{Quality: 90}); err != nil { + mlog.Error("Unable to encode image as jpeg", mlog.String("path", thumbnailPath), mlog.Err(err)) + return + } + + if _, err := a.WriteFile(buf, thumbnailPath); err != nil { + mlog.Error("Unable to upload thumbnail", mlog.String("path", thumbnailPath), mlog.Err(err)) + return + } +} + +func (a *App) generatePreviewImage(img image.Image, previewPath string, width int) { + var preview image.Image + + if width > IMAGE_PREVIEW_PIXEL_WIDTH { + preview = imaging.Resize(img, IMAGE_PREVIEW_PIXEL_WIDTH, 0, imaging.Lanczos) + } else { + preview = img + } + + buf := new(bytes.Buffer) + + if err := jpeg.Encode(buf, preview, &jpeg.Options{Quality: 90}); err != nil { + mlog.Error("Unable to encode image as preview jpg", mlog.Err(err), mlog.String("path", previewPath)) + return + } + + if _, err := a.WriteFile(buf, previewPath); err != nil { + mlog.Error("Unable to upload preview", mlog.Err(err), mlog.String("path", previewPath)) + return + } +} + +func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) { + return a.Srv.Store.FileInfo().Get(fileId) +} + +func (a *App) GetFile(fileId string) ([]byte, *model.AppError) { + info, err := a.GetFileInfo(fileId) + if err != nil { + return nil, err + } + + data, err := a.ReadFile(info.Path) + if err != nil { + return nil, err + } + + return data, nil +} + +func (a *App) CopyFileInfos(userId string, fileIds []string) ([]string, *model.AppError) { + var newFileIds []string + + now := model.GetMillis() + + for _, fileId := range fileIds { + fileInfo, err := a.Srv.Store.FileInfo().Get(fileId) + if err != nil { + return nil, err + } + + fileInfo.Id = model.NewId() + fileInfo.CreatorId = userId + fileInfo.CreateAt = now + fileInfo.UpdateAt = now + fileInfo.PostId = "" + + if _, err := a.Srv.Store.FileInfo().Save(fileInfo); err != nil { + return newFileIds, err + } + + newFileIds = append(newFileIds, fileInfo.Id) + } + + return newFileIds, nil +} diff --git a/app/file_bench_test.go b/app/file_bench_test.go index 73a18495b4..0d75efe19d 100644 --- a/app/file_bench_test.go +++ b/app/file_bench_test.go @@ -60,7 +60,7 @@ func BenchmarkUploadFile(b *testing.B) { th := Setup(b).InitBasic() defer th.TearDown() // disable logging in the benchmark, as best we can - th.App.Log.SetConsoleLevel(mlog.LevelError) + th.App.Log().SetConsoleLevel(mlog.LevelError) teamId := model.NewId() channelId := model.NewId() userId := model.NewId() @@ -91,7 +91,7 @@ func BenchmarkUploadFile(b *testing.B) { if err != nil { b.Fatal(err) } - th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }, @@ -110,7 +110,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv.Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -128,7 +128,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv.Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -143,7 +143,7 @@ func BenchmarkUploadFile(b *testing.B) { if err != nil { b.Fatal(err) } - th.App.Srv.Store.FileInfo().PermanentDelete(resp.FileInfos[0].Id) + th.App.Srv().Store.FileInfo().PermanentDelete(resp.FileInfos[0].Id) th.App.RemoveFile(resp.FileInfos[0].Path) }, }, @@ -160,7 +160,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv.Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -177,7 +177,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv.Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, diff --git a/app/file_test.go b/app/file_test.go index 7f3c96812f..b259679b9f 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -48,7 +48,7 @@ func TestDoUploadFile(t *testing.T) { info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -58,7 +58,7 @@ func TestDoUploadFile(t *testing.T) { info2, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info2.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info2.Id) th.App.RemoveFile(info2.Path) }() @@ -68,7 +68,7 @@ func TestDoUploadFile(t *testing.T) { info3, err := th.App.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info3.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info3.Id) th.App.RemoveFile(info3.Path) }() @@ -78,7 +78,7 @@ func TestDoUploadFile(t *testing.T) { info4, err := th.App.DoUploadFile(time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamId, "../../"+channelId, "../../"+userId, "../../"+filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info4.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info4.Id) th.App.RemoveFile(info4.Path) }() @@ -97,7 +97,7 @@ func TestUploadFile(t *testing.T) { info1, err := th.App.UploadFile(data, channelId, filename) require.Nil(t, err, "UploadFile should succeed with valid data") defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -275,7 +275,7 @@ func TestCopyFileInfos(t *testing.T) { info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) require.Nil(t, err) defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -285,7 +285,7 @@ func TestCopyFileInfos(t *testing.T) { info2, err := th.App.GetFileInfo(infoIds[0]) require.Nil(t, err) defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info2.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info2.Id) th.App.RemoveFile(info2.Path) }() diff --git a/app/group.go b/app/group.go index 475f464ece..0a4dfb0978 100644 --- a/app/group.go +++ b/app/group.go @@ -8,48 +8,48 @@ import ( ) func (a *App) GetGroup(id string) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().Get(id) + return a.Srv().Store.Group().Get(id) } func (a *App) GetGroupByName(name string) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetByName(name) + return a.Srv().Store.Group().GetByName(name) } func (a *App) GetGroupByRemoteID(remoteID string, groupSource model.GroupSource) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetByRemoteID(remoteID, groupSource) + return a.Srv().Store.Group().GetByRemoteID(remoteID, groupSource) } func (a *App) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetAllBySource(groupSource) + return a.Srv().Store.Group().GetAllBySource(groupSource) } func (a *App) GetGroupsByUserId(userId string) ([]*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetByUser(userId) + return a.Srv().Store.Group().GetByUser(userId) } func (a *App) CreateGroup(group *model.Group) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().Create(group) + return a.Srv().Store.Group().Create(group) } func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().Update(group) + return a.Srv().Store.Group().Update(group) } func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) { - return a.Srv.Store.Group().Delete(groupID) + return a.Srv().Store.Group().Delete(groupID) } func (a *App) GetGroupMemberUsers(groupID string) ([]*model.User, *model.AppError) { - return a.Srv.Store.Group().GetMemberUsers(groupID) + return a.Srv().Store.Group().GetMemberUsers(groupID) } func (a *App) GetGroupMemberUsersPage(groupID string, page int, perPage int) ([]*model.User, int, *model.AppError) { - members, err := a.Srv.Store.Group().GetMemberUsersPage(groupID, page, perPage) + members, err := a.Srv().Store.Group().GetMemberUsersPage(groupID, page, perPage) if err != nil { return nil, 0, err } - count, err := a.Srv.Store.Group().GetMemberCount(groupID) + count, err := a.Srv().Store.Group().GetMemberCount(groupID) if err != nil { return nil, 0, err } @@ -57,26 +57,26 @@ func (a *App) GetGroupMemberUsersPage(groupID string, page int, perPage int) ([] } func (a *App) UpsertGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) { - return a.Srv.Store.Group().UpsertMember(groupID, userID) + return a.Srv().Store.Group().UpsertMember(groupID, userID) } func (a *App) DeleteGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) { - return a.Srv.Store.Group().DeleteMember(groupID, userID) + return a.Srv().Store.Group().DeleteMember(groupID, userID) } func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) { - gs, err := a.Srv.Store.Group().GetGroupSyncable(groupSyncable.GroupId, groupSyncable.SyncableId, groupSyncable.Type) + gs, err := a.Srv().Store.Group().GetGroupSyncable(groupSyncable.GroupId, groupSyncable.SyncableId, groupSyncable.Type) if err != nil && err.Id != "store.sql_group.no_rows" { return nil, err } if gs == nil { - gs, err = a.Srv.Store.Group().CreateGroupSyncable(groupSyncable) + gs, err = a.Srv().Store.Group().CreateGroupSyncable(groupSyncable) if err != nil { return nil, err } } else { - gs, err = a.Srv.Store.Group().UpdateGroupSyncable(groupSyncable) + gs, err = a.Srv().Store.Group().UpdateGroupSyncable(groupSyncable) if err != nil { return nil, err } @@ -84,7 +84,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr // if the type is channel, then upsert the associated GroupTeam [MM-14675] if gs.Type == model.GroupSyncableTypeChannel { - channel, err := a.Srv.Store.Channel().Get(gs.SyncableId, true) + channel, err := a.Srv().Store.Channel().Get(gs.SyncableId, true) if err != nil { return nil, err } @@ -103,11 +103,11 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } func (a *App) GetGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) { - return a.Srv.Store.Group().GetGroupSyncable(groupID, syncableID, syncableType) + return a.Srv().Store.Group().GetGroupSyncable(groupID, syncableID, syncableType) } func (a *App) GetGroupSyncables(groupID string, syncableType model.GroupSyncableType) ([]*model.GroupSyncable, *model.AppError) { - return a.Srv.Store.Group().GetAllGroupSyncablesByGroupId(groupID, syncableType) + return a.Srv().Store.Group().GetAllGroupSyncablesByGroupId(groupID, syncableType) } func (a *App) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) { @@ -116,7 +116,7 @@ func (a *App) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr if groupSyncable.DeleteAt == 0 { // updating a *deleted* GroupSyncable, so no need to ensure the GroupTeam is present (as done in the upsert) - gs, err = a.Srv.Store.Group().UpdateGroupSyncable(groupSyncable) + gs, err = a.Srv().Store.Group().UpdateGroupSyncable(groupSyncable) } else { // do an upsert to ensure that there's an associated GroupTeam gs, err = a.UpsertGroupSyncable(groupSyncable) @@ -129,20 +129,20 @@ func (a *App) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) { - gs, err := a.Srv.Store.Group().DeleteGroupSyncable(groupID, syncableID, syncableType) + gs, err := a.Srv().Store.Group().DeleteGroupSyncable(groupID, syncableID, syncableType) if err != nil { return nil, err } // if a GroupTeam is being deleted delete all associated GroupChannels if gs.Type == model.GroupSyncableTypeTeam { - allGroupChannels, err := a.Srv.Store.Group().GetAllGroupSyncablesByGroupId(gs.GroupId, model.GroupSyncableTypeChannel) + allGroupChannels, err := a.Srv().Store.Group().GetAllGroupSyncablesByGroupId(gs.GroupId, model.GroupSyncableTypeChannel) if err != nil { return nil, err } for _, groupChannel := range allGroupChannels { - _, err = a.Srv.Store.Group().DeleteGroupSyncable(groupChannel.GroupId, groupChannel.SyncableId, groupChannel.Type) + _, err = a.Srv().Store.Group().DeleteGroupSyncable(groupChannel.GroupId, groupChannel.SyncableId, groupChannel.Type) if err != nil { return nil, err } @@ -153,28 +153,28 @@ func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableTyp } func (a *App) TeamMembersToAdd(since int64, teamID *string) ([]*model.UserTeamIDPair, *model.AppError) { - return a.Srv.Store.Group().TeamMembersToAdd(since, teamID) + return a.Srv().Store.Group().TeamMembersToAdd(since, teamID) } func (a *App) ChannelMembersToAdd(since int64, channelID *string) ([]*model.UserChannelIDPair, *model.AppError) { - return a.Srv.Store.Group().ChannelMembersToAdd(since, channelID) + return a.Srv().Store.Group().ChannelMembersToAdd(since, channelID) } func (a *App) TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError) { - return a.Srv.Store.Group().TeamMembersToRemove(teamID) + return a.Srv().Store.Group().TeamMembersToRemove(teamID) } func (a *App) ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *model.AppError) { - return a.Srv.Store.Group().ChannelMembersToRemove(teamID) + return a.Srv().Store.Group().ChannelMembersToRemove(teamID) } func (a *App) GetGroupsByChannel(channelId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) { - groups, err := a.Srv.Store.Group().GetGroupsByChannel(channelId, opts) + groups, err := a.Srv().Store.Group().GetGroupsByChannel(channelId, opts) if err != nil { return nil, 0, err } - count, err := a.Srv.Store.Group().CountGroupsByChannel(channelId, opts) + count, err := a.Srv().Store.Group().CountGroupsByChannel(channelId, opts) if err != nil { return nil, 0, err } @@ -183,12 +183,12 @@ func (a *App) GetGroupsByChannel(channelId string, opts model.GroupSearchOpts) ( } func (a *App) GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) { - groups, err := a.Srv.Store.Group().GetGroupsByTeam(teamId, opts) + groups, err := a.Srv().Store.Group().GetGroupsByTeam(teamId, opts) if err != nil { return nil, 0, err } - count, err := a.Srv.Store.Group().CountGroupsByTeam(teamId, opts) + count, err := a.Srv().Store.Group().CountGroupsByTeam(teamId, opts) if err != nil { return nil, 0, err } @@ -197,7 +197,7 @@ func (a *App) GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*mod } func (a *App) GetGroups(page, perPage int, opts model.GroupSearchOpts) ([]*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetGroups(page, perPage, opts) + return a.Srv().Store.Group().GetGroups(page, perPage, opts) } // TeamMembersMinusGroupMembers returns the set of users on the given team minus the set of users in the given @@ -206,7 +206,7 @@ func (a *App) GetGroups(page, perPage int, opts model.GroupSearchOpts) ([]*model // The result can be used, for example, to determine the set of users who would be removed from a team if the team // were group-constrained with the given groups. func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) { - users, err := a.Srv.Store.Group().TeamMembersMinusGroupMembers(teamID, groupIDs, page, perPage) + users, err := a.Srv().Store.Group().TeamMembersMinusGroupMembers(teamID, groupIDs, page, perPage) if err != nil { return nil, 0, err } @@ -248,7 +248,7 @@ func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, pag } } - totalCount, err := a.Srv.Store.Group().CountTeamMembersMinusGroupMembers(teamID, groupIDs) + totalCount, err := a.Srv().Store.Group().CountTeamMembersMinusGroupMembers(teamID, groupIDs) if err != nil { return nil, 0, err } @@ -256,7 +256,7 @@ func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, pag } func (a *App) GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) { - return a.Srv.Store.Group().GetByIDs(groupIDs) + return a.Srv().Store.Group().GetByIDs(groupIDs) } // ChannelMembersMinusGroupMembers returns the set of users in the given channel minus the set of users in the given @@ -265,7 +265,7 @@ func (a *App) GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError // The result can be used, for example, to determine the set of users who would be removed from a channel if the // channel were group-constrained with the given groups. func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) { - users, err := a.Srv.Store.Group().ChannelMembersMinusGroupMembers(channelID, groupIDs, page, perPage) + users, err := a.Srv().Store.Group().ChannelMembersMinusGroupMembers(channelID, groupIDs, page, perPage) if err != nil { return nil, 0, err } @@ -307,7 +307,7 @@ func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []strin } } - totalCount, err := a.Srv.Store.Group().CountChannelMembersMinusGroupMembers(channelID, groupIDs) + totalCount, err := a.Srv().Store.Group().CountChannelMembersMinusGroupMembers(channelID, groupIDs) if err != nil { return nil, 0, err } @@ -317,7 +317,7 @@ func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []strin // UserIsInAdminRoleGroup returns true at least one of the user's groups are configured to set the members as // admins in the given syncable. func (a *App) UserIsInAdminRoleGroup(userID, syncableID string, syncableType model.GroupSyncableType) (bool, *model.AppError) { - groupIDs, err := a.Srv.Store.Group().AdminRoleGroupsForSyncableMember(userID, syncableID, syncableType) + groupIDs, err := a.Srv().Store.Group().AdminRoleGroupsForSyncableMember(userID, syncableID, syncableType) if err != nil { return false, err } diff --git a/app/helper_test.go b/app/helper_test.go index 9a6db5216f..7ae258c9ce 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -78,7 +78,7 @@ func setupTestHelper(enterprise bool, tb testing.TB) *TestHelper { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) - th.App.Srv.Store.MarkSystemRanUnitTests() + th.App.Srv().Store.MarkSystemRanUnitTests() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -204,7 +204,7 @@ func (me *TestHelper) CreateBot() *model.Bot { OwnerId: me.BasicUser.Id, } - me.App.Log.SetConsoleLevel(mlog.LevelError) + me.App.Log().SetConsoleLevel(mlog.LevelError) bot, err := me.App.CreateBot(bot) if err != nil { mlog.Error(err.Error()) @@ -212,7 +212,7 @@ func (me *TestHelper) CreateBot() *model.Bot { time.Sleep(time.Second) panic(err) } - me.App.Log.SetConsoleLevel(mlog.LevelDebug) + me.App.Log().SetConsoleLevel(mlog.LevelDebug) return bot } @@ -431,7 +431,7 @@ func (me *TestHelper) CreateGroup() *model.Group { func (me *TestHelper) CreateEmoji() *model.Emoji { utils.DisableDebugLogForTest() - emoji, err := me.App.Srv.Store.Emoji().Save(&model.Emoji{ + emoji, err := me.App.Srv().Store.Emoji().Save(&model.Emoji{ CreatorId: me.BasicUser.Id, Name: model.NewRandomString(10), }) @@ -522,13 +522,13 @@ func (me *TestHelper) ResetEmojisMigration() { } func (me *TestHelper) CheckTeamCount(t *testing.T, expected int64) { - teamCount, err := me.App.Srv.Store.Team().AnalyticsTeamCount(false) + teamCount, err := me.App.Srv().Store.Team().AnalyticsTeamCount(false) require.Nil(t, err, "Failed to get team count.") require.Equalf(t, teamCount, expected, "Unexpected number of teams. Expected: %v, found: %v", expected, teamCount) } func (me *TestHelper) CheckChannelsCount(t *testing.T, expected int64) { - count, err := me.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) + count, err := me.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) require.Nilf(t, err, "Failed to get channel count.") require.Equalf(t, count, expected, "Unexpected number of channels. Expected: %v, found: %v", expected, count) } diff --git a/app/import.go b/app/import.go index fefd3d37c2..26de668985 100644 --- a/app/import.go +++ b/app/import.go @@ -37,8 +37,8 @@ func (a *App) BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model scanner := bufio.NewScanner(fileReader) lineNumber := 0 - a.Srv.Store.LockToMaster() - defer a.Srv.Store.UnlockFromMaster() + a.Srv().Store.LockToMaster() + defer a.Srv().Store.UnlockFromMaster() errorsChan := make(chan LineImportWorkerError, (2*workers)+1) // size chosen to ensure it never gets filled up completely. var wg sync.WaitGroup diff --git a/app/import_functions.go b/app/import_functions.go index 71c798b1fe..7bf26f4a70 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -163,7 +163,7 @@ func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError { } var team *model.Team - team, err := a.Srv.Store.Team().GetByName(*data.Name) + team, err := a.Srv().Store.Team().GetByName(*data.Name) if err != nil { team = &model.Team{} @@ -221,13 +221,13 @@ func (a *App) importChannel(data *ChannelImportData, dryRun bool) *model.AppErro return nil } - team, err := a.Srv.Store.Team().GetByName(*data.Team) + team, err := a.Srv().Store.Team().GetByName(*data.Team) if err != nil { return model.NewAppError("BulkImport", "app.import.import_channel.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest) } var channel *model.Channel - if result, err := a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); err == nil { + if result, err := a.Srv().Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); err == nil { channel = result } else { channel = &model.Channel{} @@ -295,7 +295,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { var user *model.User var err *model.AppError - user, err = a.Srv.Store.User().GetByUsername(*data.Username) + user, err = a.Srv().Store.User().GetByUsername(*data.Username) if err != nil { user = &model.User{} user.MakeNonNil() @@ -499,7 +499,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { } } else { if hasUserAuthDataChanged { - if _, err = a.Srv.Store.User().UpdateAuthData(user.Id, authService, authData, user.Email, false); err != nil { + if _, err = a.Srv().Store.User().UpdateAuthData(user.Id, authService, authData, user.Email, false); err != nil { return err } } @@ -636,7 +636,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { } if len(preferences) > 0 { - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_user.save_preferences.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -721,7 +721,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod } if len(teamThemePreferences) > 0 { - if err := a.Srv.Store.Preference().Save(&teamThemePreferences); err != nil { + if err := a.Srv().Store.Preference().Save(&teamThemePreferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_user_teams.save_preferences.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -818,7 +818,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, teamMember } if len(preferences) > 0 { - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_user_channels.save_preferences.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -833,7 +833,7 @@ func (a *App) importReaction(data *ReactionImportData, post *model.Post, dryRun } var user *model.User - user, err = a.Srv.Store.User().GetByUsername(*data.User) + user, err = a.Srv().Store.User().GetByUsername(*data.User) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": data.User}, err.Error(), http.StatusBadRequest) } @@ -844,7 +844,7 @@ func (a *App) importReaction(data *ReactionImportData, post *model.Post, dryRun EmojiName: *data.EmojiName, CreateAt: *data.CreateAt, } - if _, err = a.Srv.Store.Reaction().Save(reaction); err != nil { + if _, err = a.Srv().Store.Reaction().Save(reaction); err != nil { return err } @@ -858,13 +858,13 @@ func (a *App) importReply(data *ReplyImportData, post *model.Post, teamId string } var user *model.User - user, err = a.Srv.Store.User().GetByUsername(*data.User) + user, err = a.Srv().Store.User().GetByUsername(*data.User) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": data.User}, err.Error(), http.StatusBadRequest) } // Check if this post already exists. - replies, err := a.Srv.Store.Post().GetPostsCreatedAt(post.ChannelId, *data.CreateAt) + replies, err := a.Srv().Store.Post().GetPostsCreatedAt(post.ChannelId, *data.CreateAt) if err != nil { return err } @@ -893,7 +893,7 @@ func (a *App) importReply(data *ReplyImportData, post *model.Post, teamId string } for _, fileID := range reply.FileIds { if _, ok := fileIds[fileID]; !ok { - a.Srv.Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store.FileInfo().PermanentDelete(fileID) } } reply.FileIds = make([]string, 0) @@ -902,11 +902,11 @@ func (a *App) importReply(data *ReplyImportData, post *model.Post, teamId string } if reply.Id == "" { - if _, err := a.Srv.Store.Post().Save(reply); err != nil { + if _, err := a.Srv().Store.Post().Save(reply); err != nil { return err } } else { - if _, err := a.Srv.Store.Post().Overwrite(reply); err != nil { + if _, err := a.Srv().Store.Post().Overwrite(reply); err != nil { return err } } @@ -971,24 +971,24 @@ func (a *App) importPost(data *PostImportData, dryRun bool) *model.AppError { return nil } - team, err := a.Srv.Store.Team().GetByName(*data.Team) + team, err := a.Srv().Store.Team().GetByName(*data.Team) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, err.Error(), http.StatusBadRequest) } - channel, err := a.Srv.Store.Channel().GetByName(team.Id, *data.Channel, false) + channel, err := a.Srv().Store.Channel().GetByName(team.Id, *data.Channel, false) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]interface{}{"ChannelName": *data.Channel}, err.Error(), http.StatusBadRequest) } var user *model.User - user, err = a.Srv.Store.User().GetByUsername(*data.User) + user, err = a.Srv().Store.User().GetByUsername(*data.User) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, err.Error(), http.StatusBadRequest) } // Check if this post already exists. - posts, err := a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt) + posts, err := a.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt) if err != nil { return err } @@ -1018,7 +1018,7 @@ func (a *App) importPost(data *PostImportData, dryRun bool) *model.AppError { } for _, fileID := range post.FileIds { if _, ok := fileIds[fileID]; !ok { - a.Srv.Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store.FileInfo().PermanentDelete(fileID) } } post.FileIds = make([]string, 0) @@ -1027,11 +1027,11 @@ func (a *App) importPost(data *PostImportData, dryRun bool) *model.AppError { } if post.Id == "" { - if _, err = a.Srv.Store.Post().Save(post); err != nil { + if _, err = a.Srv().Store.Post().Save(post); err != nil { return err } } else { - if _, err = a.Srv.Store.Post().Overwrite(post); err != nil { + if _, err = a.Srv().Store.Post().Overwrite(post); err != nil { return err } } @@ -1041,7 +1041,7 @@ func (a *App) importPost(data *PostImportData, dryRun bool) *model.AppError { for _, username := range *data.FlaggedBy { var user *model.User - user, err = a.Srv.Store.User().GetByUsername(username) + user, err = a.Srv().Store.User().GetByUsername(username) if err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": username}, err.Error(), http.StatusBadRequest) } @@ -1055,7 +1055,7 @@ func (a *App) importPost(data *PostImportData, dryRun bool) *model.AppError { } if len(preferences) > 0 { - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_post.save_preferences.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -1099,7 +1099,7 @@ func (a *App) uploadAttachments(attachments *[]AttachmentImportData, post *model func (a *App) updateFileInfoWithPostId(post *model.Post) { for _, fileId := range post.FileIds { - if err := a.Srv.Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId); err != nil { + if err := a.Srv().Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId); err != nil { mlog.Error("Error attaching files to post.", mlog.String("post_id", post.Id), mlog.Any("post_file_ids", post.FileIds), mlog.Err(err)) } } @@ -1119,7 +1119,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m userMap := make(map[string]string) for _, username := range *data.Members { var user *model.User - user, err = a.Srv.Store.User().GetByUsername(username) + user, err = a.Srv().Store.User().GetByUsername(username) if err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_channel.member_not_found.error", nil, err.Error(), http.StatusBadRequest) } @@ -1165,14 +1165,14 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m } } - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { err.StatusCode = http.StatusBadRequest return err } if data.Header != nil { channel.Header = *data.Header - if _, appErr := a.Srv.Store.Channel().Update(channel); appErr != nil { + if _, appErr := a.Srv().Store.Channel().Update(channel); appErr != nil { return model.NewAppError("BulkImport", "app.import.import_direct_channel.update_header_failed.error", nil, appErr.Error(), http.StatusBadRequest) } } @@ -1194,7 +1194,7 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A var userIds []string for _, username := range *data.ChannelMembers { var user *model.User - user, err = a.Srv.Store.User().GetByUsername(username) + user, err = a.Srv().Store.User().GetByUsername(username) if err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.channel_member_not_found.error", nil, err.Error(), http.StatusBadRequest) } @@ -1218,13 +1218,13 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A } var user *model.User - user, err = a.Srv.Store.User().GetByUsername(*data.User) + user, err = a.Srv().Store.User().GetByUsername(*data.User) if err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, "", http.StatusBadRequest) } // Check if this post already exists. - posts, err := a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt) + posts, err := a.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt) if err != nil { return err } @@ -1254,7 +1254,7 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A } for _, fileID := range post.FileIds { if _, ok := fileIds[fileID]; !ok { - a.Srv.Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store.FileInfo().PermanentDelete(fileID) } } post.FileIds = make([]string, 0) @@ -1263,11 +1263,11 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A } if post.Id == "" { - if _, err = a.Srv.Store.Post().Save(post); err != nil { + if _, err = a.Srv().Store.Post().Save(post); err != nil { return err } } else { - if _, err = a.Srv.Store.Post().Overwrite(post); err != nil { + if _, err = a.Srv().Store.Post().Overwrite(post); err != nil { return err } } @@ -1277,7 +1277,7 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A for _, username := range *data.FlaggedBy { var user *model.User - user, err = a.Srv.Store.User().GetByUsername(username) + user, err = a.Srv().Store.User().GetByUsername(username) if err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.user_not_found.error", map[string]interface{}{"Username": username}, "", http.StatusBadRequest) } @@ -1291,7 +1291,7 @@ func (a *App) importDirectPost(data *DirectPostImportData, dryRun bool) *model.A } if len(preferences) > 0 { - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.save_preferences.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -1329,7 +1329,7 @@ func (a *App) importEmoji(data *EmojiImportData, dryRun bool) *model.AppError { var emoji *model.Emoji - emoji, appError := a.Srv.Store.Emoji().GetByName(*data.Name, true) + emoji, appError := a.Srv().Store.Emoji().GetByName(*data.Name, true) if appError != nil && appError.StatusCode != http.StatusNotFound { return appError } @@ -1353,7 +1353,7 @@ func (a *App) importEmoji(data *EmojiImportData, dryRun bool) *model.AppError { } if !alreadyExists { - if _, err := a.Srv.Store.Emoji().Save(emoji); err != nil { + if _, err := a.Srv().Store.Emoji().Save(emoji); err != nil { return err } } diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 79d7bd2b65..fc18c32667 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -24,10 +24,10 @@ func TestImportImportScheme(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() // Try importing an invalid scheme in dryRun mode. @@ -64,7 +64,7 @@ func TestImportImportScheme(t *testing.T) { err := th.App.importScheme(&data, true) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing a valid scheme in dryRun mode. @@ -73,7 +73,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, true) require.Nil(t, err, "Should have succeeded.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing an invalid scheme. @@ -82,7 +82,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing a valid scheme with all params set. @@ -91,7 +91,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded.") - scheme, err := th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err := th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -99,42 +99,42 @@ func TestImportImportScheme(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, err := th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole) + role, err := th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -148,7 +148,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded: %v", err) - scheme, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -156,42 +156,42 @@ func TestImportImportScheme(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -204,7 +204,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - scheme, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -219,10 +219,10 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() // Try importing an invalid scheme in dryRun mode. @@ -251,7 +251,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err := th.App.importScheme(&data, true) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing a valid scheme in dryRun mode. @@ -260,7 +260,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, true) require.Nil(t, err, "Should have succeeded.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing an invalid scheme. @@ -269,7 +269,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + _, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.NotNil(t, err, "Scheme should not have imported.") // Try importing a valid scheme with all params set. @@ -278,7 +278,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded.") - scheme, err := th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err := th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -286,42 +286,42 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, err := th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole) + role, err := th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -335,7 +335,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded: %v", err) - scheme, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -343,42 +343,42 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultTeamGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelAdminRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelUserRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, err = th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelGuestRole) + role, err = th.App.Srv().Store.Role().GetByName(scheme.DefaultChannelGuestRole) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -391,7 +391,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - scheme, err = th.App.Srv.Store.Scheme().GetByName(*data.Name) + scheme, err = th.App.Srv().Store.Scheme().GetByName(*data.Name) require.Nil(t, err, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -413,7 +413,7 @@ func TestImportImportRole(t *testing.T) { err := th.App.importRole(&data, true, false) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Role().GetByName(rid1) + _, err = th.App.Srv().Store.Role().GetByName(rid1) require.NotNil(t, err, "Should have failed to import.") // Try importing the valid role in dryRun mode. @@ -422,7 +422,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, true, false) require.Nil(t, err, "Should have succeeded.") - _, err = th.App.Srv.Store.Role().GetByName(rid1) + _, err = th.App.Srv().Store.Role().GetByName(rid1) require.NotNil(t, err, "Role should not have imported as we are in dry run mode.") // Try importing an invalid role. @@ -431,7 +431,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, false) require.NotNil(t, err, "Should have failed to import.") - _, err = th.App.Srv.Store.Role().GetByName(rid1) + _, err = th.App.Srv().Store.Role().GetByName(rid1) require.NotNil(t, err, "Role should not have imported.") // Try importing a valid role with all params set. @@ -442,7 +442,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, false) require.Nil(t, err, "Should have succeeded.") - role, err := th.App.Srv.Store.Role().GetByName(rid1) + role, err := th.App.Srv().Store.Role().GetByName(rid1) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.Name, role.Name) @@ -460,7 +460,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, true) require.Nil(t, err, "Should have succeeded. %v", err) - role, err = th.App.Srv.Store.Role().GetByName(rid1) + role, err = th.App.Srv().Store.Role().GetByName(rid1) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data.Name, role.Name) @@ -479,7 +479,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data2, false, false) require.Nil(t, err, "Should have succeeded.") - role, err = th.App.Srv.Store.Role().GetByName(rid1) + role, err = th.App.Srv().Store.Role().GetByName(rid1) require.Nil(t, err, "Should have found the imported role.") assert.Equal(t, *data2.Name, role.Name) @@ -495,17 +495,17 @@ func TestImportImportTeam(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() scheme1 := th.SetupTeamScheme() scheme2 := th.SetupTeamScheme() // Check how many teams are in the database. - teamsCount, err := th.App.Srv.Store.Team().AnalyticsTeamCount(false) + teamsCount, err := th.App.Srv().Store.Team().AnalyticsTeamCount(false) require.Nil(t, err, "Failed to get team count.") data := TeamImportData{ @@ -585,10 +585,10 @@ func TestImportImportChannel(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() scheme1 := th.SetupChannelScheme() @@ -605,7 +605,7 @@ func TestImportImportChannel(t *testing.T) { require.Nil(t, err, "Failed to get team from database.") // Check how many channels are in the database. - channelCount, err := th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) + channelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN) require.Nil(t, err, "Failed to get team count.") // Do an invalid channel in dry-run mode. @@ -705,7 +705,7 @@ func TestImportImportUser(t *testing.T) { defer th.TearDown() // Check how many users are in the database. - userCount, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -719,7 +719,7 @@ func TestImportImportUser(t *testing.T) { require.NotNil(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. - userCount2, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount2, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -735,7 +735,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, err, "Should have succeeded to import valid user.") // Check that no more users are in the DB. - userCount3, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount3, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -750,7 +750,7 @@ func TestImportImportUser(t *testing.T) { require.NotNil(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. - userCount4, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount4, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -773,7 +773,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, err, "Should have succeeded to import valid user.") // Check that one more user is in the DB. - userCount5, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount5, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -816,7 +816,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, err, "Should have succeeded to update valid user %v", err) // Check user count the same. - userCount6, err := th.App.Srv.Store.User().Count(model.UserCountOptions{ + userCount6, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -1334,10 +1334,10 @@ func TestImportImportUser(t *testing.T) { // to the appropriate scheme-managed-role booleans. // Mark the phase 2 permissions migration as completed. - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() teamSchemeData := &SchemeImportData{ @@ -1374,7 +1374,7 @@ func TestImportImportUser(t *testing.T) { err = th.App.importScheme(teamSchemeData, false) assert.Nil(t, err) - teamScheme, err := th.App.Srv.Store.Scheme().GetByName(*teamSchemeData.Name) + teamScheme, err := th.App.Srv().Store.Scheme().GetByName(*teamSchemeData.Name) require.Nil(t, err, "Failed to import scheme") teamData := &TeamImportData{ @@ -1600,7 +1600,7 @@ func TestImportImportPost(t *testing.T) { require.Nil(t, err, "Failed to get user from database.") // Count the number of posts in the testing team. - initialPostCount, err := th.App.Srv.Store.Post().AnalyticsPostCount(team.Id, false, false) + initialPostCount, err := th.App.Srv().Store.Post().AnalyticsPostCount(team.Id, false, false) require.Nil(t, err) // Try adding an invalid post in dry run mode. @@ -1686,7 +1686,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, err := th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, err := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1708,7 +1708,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1755,7 +1755,7 @@ func TestImportImportPost(t *testing.T) { assert.Nil(t, err) AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1794,7 +1794,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 5, team.Id) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, flagsTime) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1827,7 +1827,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 6, team.Id) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, reactionPostTime) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, reactionPostTime) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1836,7 +1836,7 @@ func TestImportImportPost(t *testing.T) { postBool = post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id || !post.HasReactions require.False(t, postBool, "Post properties not as expected") - reactions, err := th.App.Srv.Store.Reaction().GetForPost(post.Id, false) + reactions, err := th.App.Srv().Store.Reaction().GetForPost(post.Id, false) require.Nil(t, err, "Can't get reaction") require.Len(t, reactions, 1, "Invalid number of reactions") @@ -1862,7 +1862,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 8, team.Id) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, replyPostTime) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyPostTime) require.Nil(t, err) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -1872,7 +1872,7 @@ func TestImportImportPost(t *testing.T) { require.False(t, postBool, "Post properties not as expected") // Check the reply values. - replies, err := th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, replyTime) + replies, err := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyTime) require.Nil(t, err) require.Len(t, replies, 1, "Unexpected number of posts found.") @@ -1943,10 +1943,10 @@ func TestImportImportDirectChannel(t *testing.T) { defer th.TearDown() // Check how many channels are in the database. - directChannelCount, err := th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT) + directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT) require.Nil(t, err, "Failed to get direct channel count.") - groupChannelCount, err := th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP) + groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP) require.Nil(t, err, "Failed to get group channel count.") // Do an invalid channel in dry-run mode. @@ -2128,7 +2128,7 @@ func TestImportImportDirectPost(t *testing.T) { directChannel = channel // Get the number of posts in the system. - result, err := th.App.Srv.Store.Post().AnalyticsPostCount("", false, false) + result, err := th.App.Srv().Store.Post().AnalyticsPostCount("", false, false) require.Nil(t, err) initialPostCount := result @@ -2188,7 +2188,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, err := th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) + posts, err := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2203,7 +2203,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2231,7 +2231,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Nil(t, err) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2260,7 +2260,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Nil(t, err) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2294,7 +2294,7 @@ func TestImportImportDirectPost(t *testing.T) { groupChannel = channel // Get the number of posts in the system. - result, err = th.App.Srv.Store.Post().AnalyticsPostCount("", false, false) + result, err = th.App.Srv().Store.Post().AnalyticsPostCount("", false, false) require.Nil(t, err) initialPostCount = result @@ -2359,7 +2359,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2374,7 +2374,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2402,7 +2402,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Nil(t, err) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2432,7 +2432,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Nil(t, err) // Check the post values. - posts, err = th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) + posts, err = th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt) require.Nil(t, err) require.Len(t, posts, 1) @@ -2455,7 +2455,7 @@ func TestImportImportEmoji(t *testing.T) { err := th.App.importEmoji(&data, true) assert.NotNil(t, err, "Invalid emoji should have failed dry run") - emoji, err := th.App.Srv.Store.Emoji().GetByName(*data.Name, true) + emoji, err := th.App.Srv().Store.Emoji().GetByName(*data.Name, true) assert.Nil(t, emoji, "Emoji should not have been imported") assert.NotNil(t, err) @@ -2475,7 +2475,7 @@ func TestImportImportEmoji(t *testing.T) { err = th.App.importEmoji(&data, false) assert.Nil(t, err, "Valid emoji should have succeeded apply mode") - emoji, err = th.App.Srv.Store.Emoji().GetByName(*data.Name, true) + emoji, err = th.App.Srv().Store.Emoji().GetByName(*data.Name, true) assert.NotNil(t, emoji, "Emoji should have been imported") assert.Nil(t, err, "Emoji should have been imported without any error") diff --git a/app/import_test.go b/app/import_test.go index 58764d2fdc..e3c2c6d7bd 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -33,7 +33,7 @@ func ptrBool(b bool) *bool { } func checkPreference(t *testing.T, a *App, userId string, category string, name string, value string) { - preferences, err := a.Srv.Store.Preference().GetCategory(userId, category) + preferences, err := a.Srv().Store.Preference().GetCategory(userId, category) require.Nilf(t, err, "Failed to get preferences for user %v with category %v", userId, category) found := false for _, preference := range preferences { @@ -61,13 +61,13 @@ func checkNoError(t *testing.T, err *model.AppError) { } func AssertAllPostsCount(t *testing.T, a *App, initialCount int64, change int64, teamName string) { - result, err := a.Srv.Store.Post().AnalyticsPostCount(teamName, false, false) + result, err := a.Srv().Store.Post().AnalyticsPostCount(teamName, false, false) require.Nil(t, err) require.Equal(t, initialCount+change, result, "Did not find the expected number of posts.") } func AssertChannelCount(t *testing.T, a *App, channelType string, expectedCount int64) { - count, err := a.Srv.Store.Channel().AnalyticsTypeCount("", channelType) + count, err := a.Srv().Store.Channel().AnalyticsTypeCount("", channelType) require.Equalf(t, expectedCount, count, "Channel count of type: %v. Expected: %v, Got: %v", channelType, expectedCount, count) require.Nil(t, err, "Failed to get channel count.") } @@ -219,7 +219,7 @@ func TestImportProcessImportDataFileVersionLine(t *testing.T) { } func GetAttachments(userId string, th *TestHelper, t *testing.T) []*model.FileInfo { - fileInfos, err := th.App.Srv.Store.FileInfo().GetForUser(userId) + fileInfos, err := th.App.Srv().Store.FileInfo().GetForUser(userId) require.Nil(t, err) return fileInfos } @@ -228,7 +228,7 @@ func AssertFileIdsInPost(files []*model.FileInfo, th *TestHelper, t *testing.T) postId := files[0].PostId assert.NotNil(t, postId) - posts, err := th.App.Srv.Store.Post().GetPostsByIds([]string{postId}) + posts, err := th.App.Srv().Store.Post().GetPostsByIds([]string{postId}) require.Nil(t, err) assert.Equal(t, len(posts), 1) diff --git a/app/integration_action.go b/app/integration_action.go index ffbddd8cd3..859da6c59f 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -67,21 +67,21 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st // Start all queries here for parallel execution pchan := make(chan store.StoreResult, 1) go func() { - post, err := a.Srv.Store.Post().GetSingle(postId) + post, err := a.Srv().Store.Post().GetSingle(postId) pchan <- store.StoreResult{Data: post, Err: err} close(pchan) }() cchan := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv.Store.Channel().GetForPost(postId) + channel, err := a.Srv().Store.Channel().GetForPost(postId) cchan <- store.StoreResult{Data: channel, Err: err} close(cchan) }() userChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(upstreamRequest.UserId) + user, err := a.Srv().Store.User().Get(upstreamRequest.UserId) userChan <- store.StoreResult{Data: user, Err: err} close(userChan) }() @@ -99,7 +99,7 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st return "", model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "postId doesn't match", http.StatusBadRequest) } - channel, err := a.Srv.Store.Channel().Get(cookie.ChannelId, true) + channel, err := a.Srv().Store.Channel().Get(cookie.ChannelId, true) if err != nil { return "", err } @@ -168,7 +168,7 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st return } - team, err := a.Srv.Store.Team().Get(upstreamRequest.TeamId) + team, err := a.Srv().Store.Team().Get(upstreamRequest.TeamId) teamChan <- store.StoreResult{Data: team, Err: err} }() @@ -279,10 +279,10 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode subpath, _ := utils.GetSubpathFromConfig(a.Config()) siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL) if (inURL.Hostname() == "localhost" || inURL.Hostname() == "127.0.0.1" || inURL.Hostname() == siteURL.Hostname()) && strings.HasPrefix(inURL.Path, path.Join(subpath, "plugins")) { - req.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session.Token) - httpClient = a.HTTPService.MakeClient(true) + req.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session().Token) + httpClient = a.HTTPService().MakeClient(true) } else { - httpClient = a.HTTPService.MakeClient(false) + httpClient = a.HTTPService().MakeClient(false) } resp, httpErr := httpClient.Do(req) @@ -342,8 +342,8 @@ func (a *App) DoLocalRequest(rawURL string, body []byte) (*http.Response, *model if err != nil { return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) } - r.Header.Set("Mattermost-User-Id", a.Session.UserId) - r.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session.Token) + r.Header.Set("Mattermost-User-Id", a.Session().UserId) + r.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session().Token) params := make(map[string]string) params["plugin_id"] = pluginId r = mux.SetURLVars(r, params) diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 9c8feb7f66..c96237beac 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -417,7 +417,7 @@ func TestPostActionProps(t *testing.T) { require.Nil(t, err) assert.True(t, len(clientTriggerId) == 26) - newPost, err := th.App.Srv.Store.Post().GetSingle(post.Id) + newPost, err := th.App.Srv().Store.Post().GetSingle(post.Id) require.Nil(t, err) assert.True(t, newPost.IsPinned) diff --git a/app/job.go b/app/job.go index c38e6f6239..3b73a05d91 100644 --- a/app/job.go +++ b/app/job.go @@ -8,7 +8,7 @@ import ( ) func (a *App) GetJob(id string) (*model.Job, *model.AppError) { - return a.Srv.Store.Job().Get(id) + return a.Srv().Store.Job().Get(id) } func (a *App) GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) { @@ -16,7 +16,7 @@ func (a *App) GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) } func (a *App) GetJobs(offset int, limit int) ([]*model.Job, *model.AppError) { - return a.Srv.Store.Job().GetAllPage(offset, limit) + return a.Srv().Store.Job().GetAllPage(offset, limit) } func (a *App) GetJobsByTypePage(jobType string, page int, perPage int) ([]*model.Job, *model.AppError) { @@ -24,13 +24,13 @@ func (a *App) GetJobsByTypePage(jobType string, page int, perPage int) ([]*model } func (a *App) GetJobsByType(jobType string, offset int, limit int) ([]*model.Job, *model.AppError) { - return a.Srv.Store.Job().GetAllByTypePage(jobType, offset, limit) + return a.Srv().Store.Job().GetAllByTypePage(jobType, offset, limit) } func (a *App) CreateJob(job *model.Job) (*model.Job, *model.AppError) { - return a.Srv.Jobs.CreateJob(job.Type, job.Data) + return a.Srv().Jobs.CreateJob(job.Type, job.Data) } func (a *App) CancelJob(jobId string) *model.AppError { - return a.Srv.Jobs.RequestCancellation(jobId) + return a.Srv().Jobs.RequestCancellation(jobId) } diff --git a/app/job_test.go b/app/job_test.go index c8a5a57ae5..90687d29a4 100644 --- a/app/job_test.go +++ b/app/job_test.go @@ -18,10 +18,10 @@ func TestGetJob(t *testing.T) { Id: model.NewId(), Status: model.NewId(), } - _, err := th.App.Srv.Store.Job().Save(status) + _, err := th.App.Srv().Store.Job().Save(status) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(status.Id) + defer th.App.Srv().Store.Job().Delete(status.Id) received, err := th.App.GetJob(status.Id) require.Nil(t, err) @@ -53,9 +53,9 @@ func TestGetJobByType(t *testing.T) { } for _, status := range statuses { - _, err := th.App.Srv.Store.Job().Save(status) + _, err := th.App.Srv().Store.Job().Save(status) require.Nil(t, err) - defer th.App.Srv.Store.Job().Delete(status.Id) + defer th.App.Srv().Store.Job().Delete(status.Id) } received, err := th.App.GetJobsByType(jobType, 0, 2) diff --git a/app/layer_generators/app_iface.go.tmpl b/app/layer_generators/app_iface.go.tmpl new file mode 100644 index 0000000000..a0f6e73cdc --- /dev/null +++ b/app/layer_generators/app_iface.go.tmpl @@ -0,0 +1,12 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +// Code generated by "make store-layers" +// DO NOT EDIT + +package app + +// AppIface is extracted from App struct and contains all it's exported methods. It's provided to allow partial interface passing and app layers creation. +type AppIface interface { + {{.Content}} +} diff --git a/app/ldap.go b/app/ldap.go index 6579190929..bd92a6ff86 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -12,10 +12,10 @@ import ( ) func (a *App) SyncLdap() { - a.Srv.Go(func() { + a.Srv().Go(func() { if license := a.License(); license != nil && *license.Features.LDAP && *a.Config().LdapSettings.EnableSync { - if ldapI := a.Ldap; ldapI != nil { + if ldapI := a.Ldap(); ldapI != nil { ldapI.StartSynchronizeJob(false) } else { mlog.Error("Not executing ldap sync because ldap is not available") @@ -26,7 +26,7 @@ func (a *App) SyncLdap() { func (a *App) TestLdap() *model.AppError { license := a.License() - if ldapI := a.Ldap; ldapI != nil && license != nil && *license.Features.LDAP && (*a.Config().LdapSettings.Enable || *a.Config().LdapSettings.EnableSync) { + if ldapI := a.Ldap(); ldapI != nil && license != nil && *license.Features.LDAP && (*a.Config().LdapSettings.Enable || *a.Config().LdapSettings.EnableSync) { if err := ldapI.RunTest(); err != nil { err.StatusCode = 500 return err @@ -43,9 +43,9 @@ func (a *App) TestLdap() *model.AppError { func (a *App) GetLdapGroup(ldapGroupID string) (*model.Group, *model.AppError) { var group *model.Group - if a.Ldap != nil { + if a.Ldap() != nil { var err *model.AppError - group, err = a.Ldap.GetGroup(ldapGroupID) + group, err = a.Ldap().GetGroup(ldapGroupID) if err != nil { return nil, err } @@ -64,9 +64,9 @@ func (a *App) GetAllLdapGroupsPage(page int, perPage int, opts model.LdapGroupSe var groups []*model.Group var total int - if a.Ldap != nil { + if a.Ldap() != nil { var err *model.AppError - groups, total, err = a.Ldap.GetAllGroupsPage(page, perPage, opts) + groups, total, err = a.Ldap().GetAllGroupsPage(page, perPage, opts) if err != nil { return nil, 0, err } @@ -97,7 +97,7 @@ func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword return "", err } - ldapInterface := a.Ldap + ldapInterface := a.Ldap() if ldapInterface == nil { return "", model.NewAppError("SwitchEmailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusNotImplemented) } @@ -106,7 +106,7 @@ func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword return "", err } - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendSignInChangeEmail(user.Email, "AD/LDAP", user.Locale, a.GetSiteURL()); err != nil { mlog.Error(err.Error()) } @@ -129,7 +129,7 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) ( return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_ldap_account.app_error", nil, "", http.StatusBadRequest) } - ldapInterface := a.Ldap + ldapInterface := a.Ldap() if ldapInterface == nil || user.AuthData == nil { return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusNotImplemented) } @@ -152,7 +152,7 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) ( T := utils.GetUserTranslations(user.Locale) - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendSignInChangeEmail(user.Email, T("api.templates.signin_change_email.body.method_email"), user.Locale, a.GetSiteURL()); err != nil { mlog.Error(err.Error()) } diff --git a/app/license.go b/app/license.go index f2a53315b8..2d0b1c38aa 100644 --- a/app/license.go +++ b/app/license.go @@ -16,7 +16,7 @@ func (a *App) LoadLicense() { a.SetLicense(nil) licenseId := "" - props, err := a.Srv.Store.System().Get() + props, err := a.Srv().Store.System().Get() if err == nil { licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID] } @@ -34,7 +34,7 @@ func (a *App) LoadLicense() { } } - record, err := a.Srv.Store.License().Get(licenseId) + record, err := a.Srv().Store.License().Get(licenseId) if err != nil { mlog.Info("License key from https://mattermost.com required to unlock enterprise features.") return @@ -51,7 +51,7 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) } license := model.LicenseFromJson(strings.NewReader(licenseStr)) - uniqueUserCount, err := a.Srv.Store.User().Count(model.UserCountOptions{}) + uniqueUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) if err != nil { return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -72,7 +72,7 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) record.Id = license.Id record.Bytes = string(licenseBytes) - _, err = a.Srv.Store.License().Save(record) + _, err = a.Srv().Store.License().Save(record) if err != nil { a.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+err.Error(), http.StatusInternalServerError) @@ -81,7 +81,7 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) sysVar := &model.System{} sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = license.Id - if err := a.Srv.Store.System().SaveOrUpdate(sysVar); err != nil { + if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { a.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) } @@ -92,11 +92,11 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) // start job server if necessary - this handles the edge case where a license file is uploaded, but the job server // doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from // functioning as expected - if *a.Config().JobSettings.RunJobs && a.Srv.Jobs != nil && a.Srv.Jobs.Workers != nil { - a.Srv.Jobs.StartWorkers() + if *a.Config().JobSettings.RunJobs && a.Srv().Jobs != nil && a.Srv().Jobs.Workers != nil { + a.Srv().Jobs.StartWorkers() } - if *a.Config().JobSettings.RunScheduler && a.Srv.Jobs != nil && a.Srv.Jobs.Schedulers != nil { - a.Srv.Jobs.StartSchedulers() + if *a.Config().JobSettings.RunScheduler && a.Srv().Jobs != nil && a.Srv().Jobs.Schedulers != nil { + a.Srv().Jobs.StartSchedulers() } return license, nil @@ -104,12 +104,12 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) // License returns the currently active license or nil if the application is unlicensed. func (a *App) License() *model.License { - return a.Srv.License() + return a.Srv().License() } func (a *App) SetLicense(license *model.License) bool { defer func() { - for _, listener := range a.Srv.licenseListeners { + for _, listener := range a.Srv().licenseListeners { listener() } }() @@ -117,13 +117,13 @@ func (a *App) SetLicense(license *model.License) bool { if license != nil { license.Features.SetDefaults() - a.Srv.licenseValue.Store(license) - a.Srv.clientLicenseValue.Store(utils.GetClientLicense(license)) + a.Srv().licenseValue.Store(license) + a.Srv().clientLicenseValue.Store(utils.GetClientLicense(license)) return true } - a.Srv.licenseValue.Store((*model.License)(nil)) - a.Srv.clientLicenseValue.Store(map[string]string(nil)) + a.Srv().licenseValue.Store((*model.License)(nil)) + a.Srv().clientLicenseValue.Store(map[string]string(nil)) return false } @@ -138,18 +138,18 @@ func (a *App) ValidateAndSetLicenseBytes(b []byte) { } func (a *App) SetClientLicense(m map[string]string) { - a.Srv.clientLicenseValue.Store(m) + a.Srv().clientLicenseValue.Store(m) } func (a *App) ClientLicense() map[string]string { - if clientLicense, _ := a.Srv.clientLicenseValue.Load().(map[string]string); clientLicense != nil { + if clientLicense, _ := a.Srv().clientLicenseValue.Load().(map[string]string); clientLicense != nil { return clientLicense } return map[string]string{"IsLicensed": "false"} } func (a *App) RemoveLicense() *model.AppError { - if license, _ := a.Srv.licenseValue.Load().(*model.License); license == nil { + if license, _ := a.Srv().licenseValue.Load().(*model.License); license == nil { return nil } @@ -157,7 +157,7 @@ func (a *App) RemoveLicense() *model.AppError { sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = "" - if err := a.Srv.Store.System().SaveOrUpdate(sysVar); err != nil { + if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { return err } @@ -177,7 +177,7 @@ func (s *Server) AddLicenseListener(listener func()) string { func (a *App) AddLicenseListener(listener func()) string { id := model.NewId() - a.Srv.licenseListeners[id] = listener + a.Srv().licenseListeners[id] = listener return id } @@ -186,7 +186,7 @@ func (s *Server) RemoveLicenseListener(id string) { } func (a *App) RemoveLicenseListener(id string) { - delete(a.Srv.licenseListeners, id) + delete(a.Srv().licenseListeners, id) } func (a *App) GetSanitizedClientLicense() map[string]string { diff --git a/app/login.go b/app/login.go index 5993c2bf26..94c6d60986 100644 --- a/app/login.go +++ b/app/login.go @@ -36,11 +36,11 @@ func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) { func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken string, ldapOnly bool) (user *model.User, err *model.AppError) { // Do statistics defer func() { - if a.Metrics != nil { + if a.Metrics() != nil { if user == nil || err != nil { - a.Metrics.IncrementLoginFail() + a.Metrics().IncrementLoginFail() } else { - a.Metrics.IncrementLogin() + a.Metrics().IncrementLogin() } } }() @@ -93,13 +93,13 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) } // Try to get the user by username/email - if user, err := a.Srv.Store.User().GetForLogin(loginId, enableUsername, enableEmail); err == nil { + if user, err := a.Srv().Store.User().GetForLogin(loginId, enableUsername, enableEmail); err == nil { return user, nil } // Try to get the user with LDAP if enabled - if *a.Config().LdapSettings.Enable && a.Ldap != nil { - if ldapUser, err := a.Ldap.GetUser(loginId); err == nil { + if *a.Config().LdapSettings.Enable && a.Ldap() != nil { + if ldapUser, err := a.Ldap().GetUser(loginId); err == nil { if user, err := a.GetUserByAuth(ldapUser.AuthData, model.USER_AUTH_SERVICE_LDAP); err == nil { return user, nil } @@ -163,10 +163,10 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, w.Header().Set(model.HEADER_TOKEN, session.Token) - a.Session = *session + a.SetSession(session) if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLoggedIn(pluginContext, user) @@ -191,7 +191,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0) sessionCookie := &http.Cookie{ Name: model.SESSION_COOKIE_TOKEN, - Value: a.Session.Token, + Value: a.Session().Token, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -202,7 +202,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { userCookie := &http.Cookie{ Name: model.SESSION_COOKIE_USER, - Value: a.Session.UserId, + Value: a.Session().UserId, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -212,7 +212,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { csrfCookie := &http.Cookie{ Name: model.SESSION_COOKIE_CSRF, - Value: a.Session.GetCSRF(), + Value: a.Session().GetCSRF(), Path: subpath, MaxAge: maxAge, Expires: expiresAt, diff --git a/app/migrations.go b/app/migrations.go index 067e194f81..61da16e07c 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -19,7 +19,7 @@ const GUEST_ROLES_CREATION_MIGRATION_KEY = "GuestRolesCreationMigrationComplete" // This function migrates the default built in roles from code/config to the database. func (a *App) DoAdvancedPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv.Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { return } @@ -30,13 +30,13 @@ func (a *App) DoAdvancedPermissionsMigration() { allSucceeded := true for _, role := range roles { - _, err := a.Srv.Store.Role().Save(role) + _, err := a.Srv().Store.Role().Save(role) if err == nil { continue } // If this failed for reasons other than the role already existing, don't mark the migration as done. - fetchedRole, err := a.Srv.Store.Role().GetByName(role.Name) + fetchedRole, err := a.Srv().Store.Role().GetByName(role.Name) if err != nil { mlog.Critical("Failed to migrate role to database.", mlog.Err(err)) allSucceeded = false @@ -49,7 +49,7 @@ func (a *App) DoAdvancedPermissionsMigration() { fetchedRole.Description != role.Description || fetchedRole.SchemeManaged != role.SchemeManaged { role.Id = fetchedRole.Id - if _, err = a.Srv.Store.Role().Save(role); err != nil { + if _, err = a.Srv().Store.Role().Save(role); err != nil { // Role is not the same, but failed to update. mlog.Critical("Failed to migrate role to database.", mlog.Err(err)) allSucceeded = false @@ -74,24 +74,24 @@ func (a *App) DoAdvancedPermissionsMigration() { Value: "true", } - if err := a.Srv.Store.System().Save(&system); err != nil { + if err := a.Srv().Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark advanced permissions migration as completed.", mlog.Err(err)) } } func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error { if !isComplete { - if _, err := a.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { return err } } - a.Srv.phase2PermissionsMigrationComplete = isComplete + a.Srv().phase2PermissionsMigrationComplete = isComplete return nil } func (a *App) DoEmojisPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv.Store.System().GetByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err == nil { return } @@ -122,7 +122,7 @@ func (a *App) DoEmojisPermissionsMigration() { if role != nil { role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id) - if _, err = a.Srv.Store.Role().Save(role); err != nil { + if _, err = a.Srv().Store.Role().Save(role); err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } @@ -136,7 +136,7 @@ func (a *App) DoEmojisPermissionsMigration() { systemAdminRole.Permissions = append(systemAdminRole.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id) systemAdminRole.Permissions = append(systemAdminRole.Permissions, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id) - if _, err := a.Srv.Store.Role().Save(systemAdminRole); err != nil { + if _, err := a.Srv().Store.Role().Save(systemAdminRole); err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } @@ -146,40 +146,40 @@ func (a *App) DoEmojisPermissionsMigration() { Value: "true", } - if err := a.Srv.Store.System().Save(&system); err != nil { + if err := a.Srv().Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark emojis permissions migration as completed.", mlog.Err(err)) } } func (a *App) DoGuestRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv.Store.System().GetByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := a.Srv.Store.Role().GetByName(model.CHANNEL_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv.Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil { + if _, err := a.Srv().Store.Role().GetByName(model.CHANNEL_GUEST_ROLE_ID); err != nil { + if _, err := a.Srv().Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := a.Srv.Store.Role().GetByName(model.TEAM_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv.Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil { + if _, err := a.Srv().Store.Role().GetByName(model.TEAM_GUEST_ROLE_ID); err != nil { + if _, err := a.Srv().Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := a.Srv.Store.Role().GetByName(model.SYSTEM_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv.Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil { + if _, err := a.Srv().Store.Role().GetByName(model.SYSTEM_GUEST_ROLE_ID); err != nil { + if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - schemes, err := a.Srv.Store.Scheme().GetAllPage("", 0, 1000000) + schemes, err := a.Srv().Store.Scheme().GetAllPage("", 0, 1000000) if err != nil { mlog.Critical("Failed to get all schemes.", mlog.Err(err)) allSucceeded = false @@ -194,7 +194,7 @@ func (a *App) DoGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := a.Srv.Store.Role().Save(teamGuestRole); err != nil { + if savedRole, err := a.Srv().Store.Role().Save(teamGuestRole); err != nil { mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -209,14 +209,14 @@ func (a *App) DoGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := a.Srv.Store.Role().Save(channelGuestRole); err != nil { + if savedRole, err := a.Srv().Store.Role().Save(channelGuestRole); err != nil { mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err)) allSucceeded = false } else { scheme.DefaultChannelGuestRole = savedRole.Name } - _, err := a.Srv.Store.Scheme().Save(scheme) + _, err := a.Srv().Store.Scheme().Save(scheme) if err != nil { mlog.Critical("Failed to update custom scheme.", mlog.Err(err)) allSucceeded = false @@ -233,7 +233,7 @@ func (a *App) DoGuestRolesCreationMigration() { Value: "true", } - if err := a.Srv.Store.System().Save(&system); err != nil { + if err := a.Srv().Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark guest roles creation migration as completed.", mlog.Err(err)) } } diff --git a/app/notification.go b/app/notification.go index 267b4f0652..194a7d9068 100644 --- a/app/notification.go +++ b/app/notification.go @@ -24,14 +24,14 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod pchan := make(chan store.StoreResult, 1) go func() { - props, err := a.Srv.Store.User().GetAllProfilesInChannel(channel.Id, true) + props, err := a.Srv().Store.User().GetAllProfilesInChannel(channel.Id, true) pchan <- store.StoreResult{Data: props, Err: err} close(pchan) }() cmnchan := make(chan store.StoreResult, 1) go func() { - props, err := a.Srv.Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) + props, err := a.Srv().Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) cmnchan <- store.StoreResult{Data: props, Err: err} close(cmnchan) }() @@ -40,7 +40,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if len(post.FileIds) != 0 { fchan = make(chan store.StoreResult, 1) go func() { - fileInfos, err := a.Srv.Store.FileInfo().GetForPost(post.Id, true, false, true) + fileInfos, err := a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, true) fchan <- store.StoreResult{Data: fileInfos, Err: err} close(fchan) }() @@ -133,7 +133,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod umc := make(chan *model.AppError, 1) go func(userId string) { - umc <- a.Srv.Store.Channel().IncrementMentionCount(post.ChannelId, userId) + umc <- a.Srv().Store.Channel().IncrementMentionCount(post.ChannelId, userId) close(umc) }(id) updateMentionChans = append(updateMentionChans, umc) @@ -258,7 +258,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod ) } else { // register that a notification was not sent - a.NotificationsLog.Warn("Notification not sent", + a.NotificationsLog().Warn("Notification not sent", mlog.String("ackId", ""), mlog.String("type", model.PUSH_TYPE_MESSAGE), mlog.String("userId", id), @@ -290,7 +290,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod ) } else { // register that a notification was not sent - a.NotificationsLog.Warn("Notification not sent", + a.NotificationsLog().Warn("Notification not sent", mlog.String("ackId", ""), mlog.String("type", model.PUSH_TYPE_MESSAGE), mlog.String("userId", id), @@ -403,7 +403,7 @@ func (a *App) filterOutOfChannelMentions(sender *model.User, post *model.Post, c return nil, nil, nil } - users, err := a.Srv.Store.User().GetProfilesByUsernames(potentialMentions, &model.ViewUsersRestrictions{Teams: []string{channel.TeamId}}) + users, err := a.Srv().Store.User().GetProfilesByUsernames(potentialMentions, &model.ViewUsersRestrictions{Teams: []string{channel.TeamId}}) if err != nil { return nil, nil, err } @@ -857,7 +857,7 @@ func (a *App) GetNotificationNameFormat(user *model.User) string { return model.SHOW_USERNAME } - data, err := a.Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_NAME_FORMAT) + data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_NAME_FORMAT) if err != nil { return *a.Config().TeamSettings.TeammateNameDisplay } diff --git a/app/notification_email.go b/app/notification_email.go index fa40a6dd02..b2fc44e764 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -23,7 +23,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. post := notification.Post if channel.IsGroupOrDirect() { - teams, err := a.Srv.Store.Team().GetTeamsByUserId(user.Id) + teams, err := a.Srv().Store.Team().GetTeamsByUserId(user.Id) if err != nil { return err } @@ -48,7 +48,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. if *a.Config().EmailSettings.EnableEmailBatching { var sendBatched bool - if data, err := a.Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); err != nil { + if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); err != nil { // if the call fails, assume that the interval has not been explicitly set and batch the notifications sendBatched = true } else { @@ -68,7 +68,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. translateFunc := utils.GetUserTranslations(user.Locale) var useMilitaryTime bool - if data, err := a.Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME); err != nil { + if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME); err != nil { useMilitaryTime = true } else { useMilitaryTime = data.Value == "true" @@ -98,14 +98,14 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. landingURL := a.GetSiteURL() + "/landing#/" + team.Name var bodyText = a.getNotificationEmailBody(user, post, channel, channelName, senderName, team.Name, landingURL, emailNotificationContentsType, useMilitaryTime, translateFunc) - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendNotificationMail(user.Email, html.UnescapeString(subjectText), bodyText); err != nil { mlog.Error("Error while sending the email", mlog.String("user_email", user.Email), mlog.Err(err)) } }) - if a.Metrics != nil { - a.Metrics.IncrementPostSentEmail() + if a.Metrics() != nil { + a.Metrics().IncrementPostSentEmail() } return nil @@ -318,7 +318,7 @@ func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.Tra } // extract the filenames from their paths and determine what type of files are attached - infos, err := a.Srv.Store.FileInfo().GetForPost(post.Id, true, false, true) + infos, err := a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, true) if err != nil { mlog.Warn("Encountered error when getting files for notification message", mlog.String("post_id", post.Id), mlog.Err(err)) } diff --git a/app/notification_push.go b/app/notification_push.go index 71a6581722..03738daff9 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -22,8 +22,8 @@ const NOTIFICATION_TYPE_CLEAR NotificationType = "clear" const NOTIFICATION_TYPE_MESSAGE NotificationType = "message" const NOTIFICATION_TYPE_UPDATE_BADGE NotificationType = "update_badge" -const PUSH_NOTIFICATION_HUB_WORKERS = 1000 -const PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER = 50 +const PUSH_NOTIFICATION_HUB_WORKERS = 1 +const PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER = 1 type PushNotificationsHub struct { Channels []chan PushNotification @@ -112,7 +112,7 @@ func (a *App) sendPushNotificationToAllSessions(msg *model.PushNotification, use err := a.sendToPushProxy(*tmpMessage, session) if err != nil { - a.NotificationsLog.Error("Notification error", + a.NotificationsLog().Error("Notification error", mlog.String("ackId", tmpMessage.AckId), mlog.String("type", tmpMessage.Type), mlog.String("userId", session.UserId), @@ -125,7 +125,7 @@ func (a *App) sendPushNotificationToAllSessions(msg *model.PushNotification, use continue } - a.NotificationsLog.Info("Notification sent", + a.NotificationsLog().Info("Notification sent", mlog.String("ackId", tmpMessage.AckId), mlog.String("type", tmpMessage.Type), mlog.String("userId", session.UserId), @@ -135,8 +135,8 @@ func (a *App) sendPushNotificationToAllSessions(msg *model.PushNotification, use mlog.String("status", model.PUSH_SEND_SUCCESS), ) - if a.Metrics != nil { - a.Metrics.IncrementPostSentPush() + if a.Metrics() != nil { + a.Metrics().IncrementPostSentPush() } } @@ -153,7 +153,7 @@ func (a *App) sendPushNotification(notification *PostNotification, user *model.U channelName := notification.GetChannelName(nameFormat, user.Id) senderName := notification.GetSenderName(nameFormat, *cfg.ServiceSettings.EnablePostUsernameOverride) - c := a.Srv.PushNotificationsHub.GetGoChannelFromUserId(user.Id) + c := a.Srv().PushNotificationsHub.GetGoChannelFromUserId(user.Id) c <- PushNotification{ notificationType: NOTIFICATION_TYPE_MESSAGE, post: post, @@ -216,7 +216,7 @@ func (a *App) ClearPushNotificationSync(currentSessionId, userId, channelId stri ContentAvailable: 1, } - unreadCount, err := a.Srv.Store.User().GetUnreadCount(userId) + unreadCount, err := a.Srv().Store.User().GetUnreadCount(userId) if err != nil { return err } @@ -227,7 +227,7 @@ func (a *App) ClearPushNotificationSync(currentSessionId, userId, channelId stri } func (a *App) ClearPushNotification(currentSessionId, userId, channelId string) { - channel := a.Srv.PushNotificationsHub.GetGoChannelFromUserId(userId) + channel := a.Srv().PushNotificationsHub.GetGoChannelFromUserId(userId) channel <- PushNotification{ notificationType: NOTIFICATION_TYPE_CLEAR, currentSessionId: currentSessionId, @@ -244,7 +244,7 @@ func (a *App) UpdateMobileAppBadgeSync(userId string) *model.AppError { ContentAvailable: 1, } - unreadCount, err := a.Srv.Store.User().GetUnreadCount(userId) + unreadCount, err := a.Srv().Store.User().GetUnreadCount(userId) if err != nil { return err } @@ -255,7 +255,7 @@ func (a *App) UpdateMobileAppBadgeSync(userId string) *model.AppError { } func (a *App) UpdateMobileAppBadge(userId string) { - channel := a.Srv.PushNotificationsHub.GetGoChannelFromUserId(userId) + channel := a.Srv().PushNotificationsHub.GetGoChannelFromUserId(userId) channel <- PushNotification{ notificationType: NOTIFICATION_TYPE_UPDATE_BADGE, userId: userId, @@ -269,7 +269,7 @@ func (a *App) CreatePushNotificationsHub() { for x := 0; x < PUSH_NOTIFICATION_HUB_WORKERS; x++ { hub.Channels = append(hub.Channels, make(chan PushNotification, PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER)) } - a.Srv.PushNotificationsHub = hub + a.Srv().PushNotificationsHub = hub } func (a *App) pushNotificationWorker(notifications chan PushNotification) { @@ -304,13 +304,13 @@ func (a *App) pushNotificationWorker(notifications chan PushNotification) { func (a *App) StartPushNotificationsHubWorkers() { for x := 0; x < PUSH_NOTIFICATION_HUB_WORKERS; x++ { - channel := a.Srv.PushNotificationsHub.Channels[x] - a.Srv.Go(func() { a.pushNotificationWorker(channel) }) + channel := a.Srv().PushNotificationsHub.Channels[x] + a.Srv().Go(func() { a.pushNotificationWorker(channel) }) } } func (a *App) StopPushNotificationsHubWorkers() { - for _, channel := range a.Srv.PushNotificationsHub.Channels { + for _, channel := range a.Srv().PushNotificationsHub.Channels { close(channel) } } @@ -318,7 +318,7 @@ func (a *App) StopPushNotificationsHubWorkers() { func (a *App) sendToPushProxy(msg model.PushNotification, session *model.Session) error { msg.ServerId = a.DiagnosticId() - a.NotificationsLog.Info("Notification will be sent", + a.NotificationsLog().Info("Notification will be sent", mlog.String("ackId", msg.AckId), mlog.String("type", msg.Type), mlog.String("userId", session.UserId), @@ -331,7 +331,7 @@ func (a *App) sendToPushProxy(msg model.PushNotification, session *model.Session return err } - resp, err := a.HTTPService.MakeClient(true).Do(request) + resp, err := a.HTTPService().MakeClient(true).Do(request) if err != nil { return err } @@ -358,7 +358,7 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { return nil } - a.NotificationsLog.Info("Notification received", + a.NotificationsLog().Info("Notification received", mlog.String("ackId", ack.Id), mlog.String("type", ack.NotificationType), mlog.String("deviceType", ack.ClientPlatform), @@ -376,7 +376,7 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { return err } - resp, err := a.HTTPService.MakeClient(true).Do(request) + resp, err := a.HTTPService().MakeClient(true).Do(request) if err != nil { return err } @@ -387,7 +387,7 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { } func (a *App) getMobileAppSessions(userId string) ([]*model.Session, *model.AppError) { - return a.Srv.Store.Session().GetSessionsWithActiveDeviceIds(userId) + return a.Srv().Store.Session().GetSessionsWithActiveDeviceIds(userId) } func ShouldSendPushNotification(user *model.User, channelNotifyProps model.StringMap, wasMentioned bool, status *model.Status, post *model.Post) bool { @@ -464,7 +464,7 @@ func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Po var msg *model.PushNotification - notificationInterface := a.Srv.Notification + notificationInterface := a.Srv().Notification if (notificationInterface == nil || notificationInterface.CheckLicense() != nil) && contentsConfig == model.ID_LOADED_NOTIFICATION { contentsConfig = model.GENERIC_NOTIFICATION } @@ -475,7 +475,7 @@ func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Po msg = a.buildFullPushNotificationMessage(contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) } - unreadCount, err := a.Srv.Store.User().GetUnreadCount(user.Id) + unreadCount, err := a.Srv().Store.User().GetUnreadCount(user.Id) if err != nil { return nil, err } diff --git a/app/oauth.go b/app/oauth.go index 6f4c1ce9a7..dab15ae198 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -34,14 +34,14 @@ func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppEr app.ClientSecret = model.NewId() - return a.Srv.Store.OAuth().SaveApp(app) + return a.Srv().Store.OAuth().SaveApp(app) } func (a *App) GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) { if !*a.Config().ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.OAuth().GetApp(appId) + return a.Srv().Store.OAuth().GetApp(appId) } func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) { @@ -54,7 +54,7 @@ func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthAp updatedApp.CreateAt = oldApp.CreateAt updatedApp.ClientSecret = oldApp.ClientSecret - return a.Srv.Store.OAuth().UpdateApp(updatedApp) + return a.Srv().Store.OAuth().UpdateApp(updatedApp) } func (a *App) DeleteOAuthApp(appId string) *model.AppError { @@ -62,7 +62,7 @@ func (a *App) DeleteOAuthApp(appId string) *model.AppError { return model.NewAppError("DeleteOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if err := a.Srv.Store.OAuth().DeleteApp(appId); err != nil { + if err := a.Srv().Store.OAuth().DeleteApp(appId); err != nil { return err } @@ -78,7 +78,7 @@ func (a *App) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppErro return nil, model.NewAppError("GetOAuthApps", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.OAuth().GetApps(page*perPage, perPage) + return a.Srv().Store.OAuth().GetApps(page*perPage, perPage) } func (a *App) GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { @@ -86,7 +86,7 @@ func (a *App) GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model. return nil, model.NewAppError("GetOAuthAppsByUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.OAuth().GetAppByUser(userId, page*perPage, perPage) + return a.Srv().Store.OAuth().GetAppByUser(userId, page*perPage, perPage) } func (a *App) GetOAuthImplicitRedirect(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { @@ -109,7 +109,7 @@ func (a *App) GetOAuthCodeRedirect(userId string, authRequest *model.AuthorizeRe authData := &model.AuthData{UserId: userId, ClientId: authRequest.ClientId, CreateAt: model.GetMillis(), RedirectUri: authRequest.RedirectUri, State: authRequest.State, Scope: authRequest.Scope} authData.Code = model.NewId() + model.NewId() - if _, err := a.Srv.Store.OAuth().SaveAuthData(authData); err != nil { + if _, err := a.Srv().Store.OAuth().SaveAuthData(authData); err != nil { return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil } @@ -125,7 +125,7 @@ func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.Author authRequest.Scope = model.DEFAULT_SCOPE } - oauthApp, err := a.Srv.Store.OAuth().GetApp(authRequest.ClientId) + oauthApp, err := a.Srv().Store.OAuth().GetApp(authRequest.ClientId) if err != nil { return "", err } @@ -158,7 +158,7 @@ func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.Author Value: authRequest.Scope, } - if err = a.Srv.Store.Preference().Save(&model.Preferences{authorizedApp}); err != nil { + if err = a.Srv().Store.Preference().Save(&model.Preferences{authorizedApp}); err != nil { mlog.Error("error saving store prefrence", mlog.Err(err)) return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil } @@ -188,7 +188,7 @@ func (a *App) GetOAuthAccessTokenForImplicitFlow(userId string, authRequest *mod accessData := &model.AccessData{ClientId: authRequest.ClientId, UserId: user.Id, Token: session.Token, RefreshToken: "", RedirectUri: authRequest.RedirectUri, ExpiresAt: session.ExpiresAt, Scope: authRequest.Scope} - if _, err := a.Srv.Store.OAuth().SaveAccessData(accessData); err != nil { + if _, err := a.Srv().Store.OAuth().SaveAccessData(accessData); err != nil { mlog.Error("error saving oauth access data in implicit flow", mlog.Err(err)) return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -201,7 +201,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.disabled.app_error", nil, "", http.StatusNotImplemented) } - oauthApp, err := a.Srv.Store.OAuth().GetApp(clientId) + oauthApp, err := a.Srv().Store.OAuth().GetApp(clientId) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.credentials.app_error", nil, "", http.StatusNotFound) } @@ -215,13 +215,13 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c var accessRsp *model.AccessResponse if grantType == model.ACCESS_TOKEN_GRANT_TYPE { var authData *model.AuthData - authData, err = a.Srv.Store.OAuth().GetAuthData(code) + authData, err = a.Srv().Store.OAuth().GetAuthData(code) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusBadRequest) } if authData.IsExpired() { - a.Srv.Store.OAuth().RemoveAuthData(authData.Code) + a.Srv().Store.OAuth().RemoveAuthData(authData.Code) return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusForbidden) } @@ -229,12 +229,12 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.redirect_uri.app_error", nil, "", http.StatusBadRequest) } - user, err = a.Srv.Store.User().Get(authData.UserId) + user, err = a.Srv().Store.User().Get(authData.UserId) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } - accessData, err = a.Srv.Store.OAuth().GetPreviousAccessData(user.Id, clientId) + accessData, err = a.Srv().Store.OAuth().GetPreviousAccessData(user.Id, clientId) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal.app_error", nil, "", http.StatusBadRequest) } @@ -266,7 +266,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c accessData = &model.AccessData{ClientId: clientId, UserId: user.Id, Token: session.Token, RefreshToken: model.NewId(), RedirectUri: redirectUri, ExpiresAt: session.ExpiresAt, Scope: authData.Scope} - if _, err = a.Srv.Store.OAuth().SaveAccessData(accessData); err != nil { + if _, err = a.Srv().Store.OAuth().SaveAccessData(accessData); err != nil { mlog.Error("error saving oauth access data in token for code flow", mlog.Err(err)) return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -279,15 +279,15 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c } } - a.Srv.Store.OAuth().RemoveAuthData(authData.Code) + a.Srv().Store.OAuth().RemoveAuthData(authData.Code) } else { // When grantType is refresh_token - accessData, err = a.Srv.Store.OAuth().GetAccessDataByRefreshToken(refreshToken) + accessData, err = a.Srv().Store.OAuth().GetAccessDataByRefreshToken(refreshToken) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.refresh_token.app_error", nil, "", http.StatusNotFound) } - user, err := a.Srv.Store.User().Get(accessData.UserId) + user, err := a.Srv().Store.User().Get(accessData.UserId) if err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } @@ -311,7 +311,7 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod session.AddProp(model.SESSION_PROP_OS, "OAuth2") session.AddProp(model.SESSION_PROP_BROWSER, "OAuth2") - session, err := a.Srv.Store.Session().Save(session) + session, err := a.Srv().Store.Session().Save(session) if err != nil { return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError) } @@ -323,7 +323,7 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData, user *model.User) (*model.AccessResponse, *model.AppError) { // Remove the previous session - if err := a.Srv.Store.Session().Remove(accessData.Token); err != nil { + if err := a.Srv().Store.Session().Remove(accessData.Token); err != nil { mlog.Error("error removing access data token from session", mlog.Err(err)) } @@ -336,7 +336,7 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData accessData.RefreshToken = model.NewId() accessData.ExpiresAt = session.ExpiresAt - if _, err := a.Srv.Store.OAuth().UpdateAccessData(accessData); err != nil { + if _, err := a.Srv().Store.OAuth().UpdateAccessData(accessData); err != nil { mlog.Error("error updating oauth access data", mlog.Err(err)) return nil, model.NewAppError("newSessionUpdateToken", "web.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -389,7 +389,7 @@ func (a *App) GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*mod return nil, model.NewAppError("GetAuthorizedAppsForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - apps, err := a.Srv.Store.OAuth().GetAuthorizedApps(userId, page*perPage, perPage) + apps, err := a.Srv().Store.OAuth().GetAuthorizedApps(userId, page*perPage, perPage) if err != nil { return nil, err } @@ -408,7 +408,7 @@ func (a *App) DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { } // Revoke app sessions - accessData, err := a.Srv.Store.OAuth().GetAccessDataByUserForApp(userId, appId) + accessData, err := a.Srv().Store.OAuth().GetAccessDataByUserForApp(userId, appId) if err != nil { return err } @@ -418,13 +418,13 @@ func (a *App) DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { return err } - if err := a.Srv.Store.OAuth().RemoveAccessData(ad.Token); err != nil { + if err := a.Srv().Store.OAuth().RemoveAccessData(ad.Token); err != nil { return err } } // Deauthorize the app - if err := a.Srv.Store.Preference().Delete(userId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appId); err != nil { + if err := a.Srv().Store.Preference().Delete(userId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appId); err != nil { return err } @@ -437,7 +437,7 @@ func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *m } app.ClientSecret = model.NewId() - if _, err := a.Srv.Store.OAuth().UpdateApp(app); err != nil { + if _, err := a.Srv().Store.OAuth().UpdateApp(app); err != nil { return nil, err } @@ -449,15 +449,15 @@ func (a *App) RevokeAccessToken(token string) *model.AppError { schan := make(chan *model.AppError, 1) go func() { - schan <- a.Srv.Store.Session().Remove(token) + schan <- a.Srv().Store.Session().Remove(token) close(schan) }() - if _, err := a.Srv.Store.OAuth().GetAccessData(token); err != nil { + if _, err := a.Srv().Store.OAuth().GetAccessData(token); err != nil { return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.get.app_error", nil, "", http.StatusBadRequest) } - if err := a.Srv.Store.OAuth().RemoveAccessData(token); err != nil { + if err := a.Srv().Store.OAuth().RemoveAccessData(token); err != nil { return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.del_token.app_error", nil, "", http.StatusInternalServerError) } @@ -568,7 +568,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email return nil, model.NewAppError("CompleteSwitchWithOAuth", "api.user.complete_switch_with_oauth.blank_email.app_error", nil, "", http.StatusBadRequest) } - user, err := a.Srv.Store.User().GetByEmail(email) + user, err := a.Srv().Store.User().GetByEmail(email) if err != nil { return nil, err } @@ -577,11 +577,11 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email return nil, err } - if _, err = a.Srv.Store.User().UpdateAuthData(user.Id, service, &authData, ssoEmail, true); err != nil { + if _, err = a.Srv().Store.User().UpdateAuthData(user.Id, service, &authData, ssoEmail, true); err != nil { return nil, err } - a.Srv.Go(func() { + a.Srv().Go(func() { if err = a.SendSignInChangeEmail(user.Email, strings.Title(service)+" SSO", user.Locale, a.GetSiteURL()); err != nil { mlog.Error("error sending signin change email", mlog.Err(err)) } @@ -593,7 +593,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) { token := model.NewToken(model.TOKEN_TYPE_OAUTH, extra) - if err := a.Srv.Store.Token().Save(token); err != nil { + if err := a.Srv().Store.Token().Save(token); err != nil { return nil, err } @@ -601,7 +601,7 @@ func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError } func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) { - mToken, err := a.Srv.Store.Token().GetByToken(token) + mToken, err := a.Srv().Store.Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -743,7 +743,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") - resp, err := a.HTTPService.MakeClient(true).Do(req) + resp, err := a.HTTPService().MakeClient(true).Do(req) if err != nil { return nil, "", stateProps, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.token_failed.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -776,7 +776,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer "+ar.AccessToken) - resp, err = a.HTTPService.MakeClient(true).Do(req) + resp, err = a.HTTPService().MakeClient(true).Do(req) if err != nil { return nil, "", stateProps, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.service.app_error", map[string]interface{}{"Service": service}, err.Error(), http.StatusInternalServerError) } else if resp.StatusCode != http.StatusOK { @@ -850,7 +850,7 @@ func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, * T := utils.GetUserTranslations(user.Locale) - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendSignInChangeEmail(user.Email, T("api.templates.signin_change_email.body.method_email"), user.Locale, a.GetSiteURL()); err != nil { mlog.Error("error sending signin change email", mlog.Err(err)) } diff --git a/app/oauth_test.go b/app/oauth_test.go index 94e2ace89e..5e4fc5e6dd 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -90,7 +90,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) { accessData.ClientId = model.NewId() accessData.ExpiresAt = session.ExpiresAt - _, err = th.App.Srv.Store.OAuth().SaveAccessData(accessData) + _, err = th.App.Srv().Store.OAuth().SaveAccessData(accessData) require.Nil(t, err) err = th.App.RevokeAccessToken(accessData.Token) @@ -130,7 +130,7 @@ func TestOAuthDeleteApp(t *testing.T) { accessData.ClientId = a1.Id accessData.ExpiresAt = session.ExpiresAt - _, err = th.App.Srv.Store.OAuth().SaveAccessData(accessData) + _, err = th.App.Srv().Store.OAuth().SaveAccessData(accessData) require.Nil(t, err) err = th.App.DeleteOAuthApp(a1.Id) @@ -226,7 +226,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { defer th.TearDown() token := model.NewToken("invalid", "") - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) state := makeState(token) diff --git a/app/opengraph.go b/app/opengraph.go index 1d62e9de26..dcce4d4294 100644 --- a/app/opengraph.go +++ b/app/opengraph.go @@ -17,7 +17,7 @@ import ( const MaxOpenGraphResponseSize = 1024 * 1024 * 50 func (a *App) GetOpenGraphMetadata(requestURL string) *opengraph.OpenGraph { - res, err := a.HTTPService.MakeClient(false).Get(requestURL) + res, err := a.HTTPService().MakeClient(false).Get(requestURL) if err != nil { mlog.Debug("GetOpenGraphMetadata request failed", mlog.String("requestURL", requestURL), mlog.Err(err)) return nil diff --git a/app/options.go b/app/options.go index 28a7f4bc71..eeb7818e76 100644 --- a/app/options.go +++ b/app/options.go @@ -16,7 +16,7 @@ type Option func(s *Server) error // By default, the app will use the store specified by the configuration. This allows you to // construct an app with a different store. // -// The override parameter must be either a store.Store or func(App) store.Store. +// The override parameter must be either a store.Store or func(App) store.Store(). func StoreOverride(override interface{}) Option { return func(s *Server) error { switch o := override.(type) { @@ -96,24 +96,23 @@ type AppOptionCreator func() []AppOption func ServerConnector(s *Server) AppOption { return func(a *App) { - a.Srv = s + a.srv = s + a.log = s.Log + a.notificationsLog = s.NotificationsLog - a.Log = s.Log - a.NotificationsLog = s.NotificationsLog + a.accountMigration = s.AccountMigration + a.cluster = s.Cluster + a.compliance = s.Compliance + a.dataRetention = s.DataRetention + a.elasticsearch = s.Elasticsearch + a.ldap = s.Ldap + a.messageExport = s.MessageExport + a.metrics = s.Metrics + a.notification = s.Notification + a.saml = s.Saml - a.AccountMigration = s.AccountMigration - a.Cluster = s.Cluster - a.Compliance = s.Compliance - a.DataRetention = s.DataRetention - a.Elasticsearch = s.Elasticsearch - a.Ldap = s.Ldap - a.MessageExport = s.MessageExport - a.Metrics = s.Metrics - a.Notification = s.Notification - a.Saml = s.Saml - - a.HTTPService = s.HTTPService - a.ImageProxy = s.ImageProxy - a.Timezones = s.timezones + a.httpService = s.HTTPService + a.imageProxy = s.ImageProxy + a.timezones = s.timezones } } diff --git a/app/permissions.go b/app/permissions.go index 5c16a26b18..cdee338da0 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -18,42 +18,42 @@ const systemSchemeName = "00000000-0000-0000-0000-000000000000" // Prevents coll func (a *App) ResetPermissionsSystem() *model.AppError { // Reset all Teams to not have a scheme. - if err := a.Srv.Store.Team().ResetAllTeamSchemes(); err != nil { + if err := a.Srv().Store.Team().ResetAllTeamSchemes(); err != nil { return err } // Reset all Channels to not have a scheme. - if err := a.Srv.Store.Channel().ResetAllChannelSchemes(); err != nil { + if err := a.Srv().Store.Channel().ResetAllChannelSchemes(); err != nil { return err } // Reset all Custom Role assignments to Users. - if err := a.Srv.Store.User().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store.User().ClearAllCustomRoleAssignments(); err != nil { return err } // Reset all Custom Role assignments to TeamMembers. - if err := a.Srv.Store.Team().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store.Team().ClearAllCustomRoleAssignments(); err != nil { return err } // Reset all Custom Role assignments to ChannelMembers. - if err := a.Srv.Store.Channel().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store.Channel().ClearAllCustomRoleAssignments(); err != nil { return err } // Purge all schemes from the database. - if err := a.Srv.Store.Scheme().PermanentDeleteAll(); err != nil { + if err := a.Srv().Store.Scheme().PermanentDeleteAll(); err != nil { return err } // Purge all roles from the database. - if err := a.Srv.Store.Role().PermanentDeleteAll(); err != nil { + if err := a.Srv().Store.Role().PermanentDeleteAll(); err != nil { return err } // Remove the "System" table entry that marks the advanced permissions migration as done. - if _, err := a.Srv.Store.System().PermanentDeleteByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err != nil { return err } diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 7cd9b2c7b0..ddff93c676 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -133,7 +133,7 @@ func applyPermissionsMap(roleName string, roleMap map[string]map[string]bool, mi } func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap) *model.AppError { - if _, err := a.Srv.Store.System().GetByName(key); err == nil { + if _, err := a.Srv().Store.System().GetByName(key); err == nil { return nil } @@ -152,12 +152,12 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap) *m for _, role := range roles { role.Permissions = applyPermissionsMap(role.Name, roleMap, migrationMap) - if _, err := a.Srv.Store.Role().Save(role); err != nil { + if _, err := a.Srv().Store.Role().Save(role); err != nil { return err } } - if err := a.Srv.Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil { + if err := a.Srv().Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil { return err } return nil diff --git a/app/permissions_test.go b/app/permissions_test.go index 6d0c818f19..0146b040ff 100644 --- a/app/permissions_test.go +++ b/app/permissions_test.go @@ -255,11 +255,11 @@ func TestImportPermissions_schemeDeletedOnRoleFailure(t *testing.T) { func withMigrationMarkedComplete(th *TestHelper, f func()) { // Mark the migration as done. - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) - th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"}) // Un-mark the migration at the end of the test. defer func() { - th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) + th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2) }() f() } diff --git a/app/plugin.go b/app/plugin.go index 7896d42e0d..ca66ad8349 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -44,24 +44,24 @@ func (a *App) GetPluginsEnvironment() *plugin.Environment { return nil } - a.Srv.PluginsLock.RLock() - defer a.Srv.PluginsLock.RUnlock() + a.Srv().PluginsLock.RLock() + defer a.Srv().PluginsLock.RUnlock() - return a.Srv.PluginsEnvironment + return a.Srv().PluginsEnvironment } func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) { - a.Srv.PluginsLock.Lock() - defer a.Srv.PluginsLock.Unlock() + a.Srv().PluginsLock.Lock() + defer a.Srv().PluginsLock.Unlock() - a.Srv.PluginsEnvironment = pluginsEnvironment + a.Srv().PluginsEnvironment = pluginsEnvironment } func (a *App) SyncPluginsActiveState() { // Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment. - a.Srv.PluginsLock.RLock() - pluginsEnvironment := a.Srv.PluginsEnvironment - a.Srv.PluginsLock.RUnlock() + a.Srv().PluginsLock.RLock() + pluginsEnvironment := a.Srv().PluginsEnvironment + a.Srv().PluginsLock.RUnlock() if pluginsEnvironment == nil { return @@ -72,7 +72,7 @@ func (a *App) SyncPluginsActiveState() { if *config.Enable { availablePlugins, err := pluginsEnvironment.Available() if err != nil { - a.Log.Error("Unable to get available plugins", mlog.Err(err)) + a.Log().Error("Unable to get available plugins", mlog.Err(err)) return } @@ -99,7 +99,7 @@ func (a *App) SyncPluginsActiveState() { // Activate any plugins that have been enabled for _, plugin := range availablePlugins { if plugin.Manifest == nil { - plugin.WrapLogger(a.Log).Error("Plugin manifest could not be loaded", mlog.Err(plugin.ManifestError)) + plugin.WrapLogger(a.Log()).Error("Plugin manifest could not be loaded", mlog.Err(plugin.ManifestError)) continue } @@ -114,14 +114,14 @@ func (a *App) SyncPluginsActiveState() { if pluginEnabled { updatedManifest, activated, err := pluginsEnvironment.Activate(pluginId) if err != nil { - plugin.WrapLogger(a.Log).Error("Unable to activate plugin", mlog.Err(err)) + plugin.WrapLogger(a.Log()).Error("Unable to activate plugin", mlog.Err(err)) continue } if activated { // Notify all cluster clients if ready if err := a.notifyPluginEnabled(updatedManifest); err != nil { - a.Log.Error("Failed to notify cluster on plugin enable", mlog.Err(err)) + a.Log().Error("Failed to notify cluster on plugin enable", mlog.Err(err)) } } } @@ -141,15 +141,15 @@ func (a *App) NewPluginAPI(manifest *model.Manifest) plugin.API { func (a *App) InitPlugins(pluginDir, webappPluginDir string) { // Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment. - a.Srv.PluginsLock.RLock() - pluginsEnvironment := a.Srv.PluginsEnvironment - a.Srv.PluginsLock.RUnlock() + a.Srv().PluginsLock.RLock() + pluginsEnvironment := a.Srv().PluginsEnvironment + a.Srv().PluginsLock.RUnlock() if pluginsEnvironment != nil || !*a.Config().PluginSettings.Enable { a.SyncPluginsActiveState() return } - a.Log.Info("Starting up plugins") + a.Log().Info("Starting up plugins") if err := os.Mkdir(pluginDir, 0744); err != nil && !os.IsExist(err) { mlog.Error("Failed to start up plugins", mlog.Err(err)) @@ -161,7 +161,7 @@ func (a *App) InitPlugins(pluginDir, webappPluginDir string) { return } - env, err := plugin.NewEnvironment(a.NewPluginAPI, pluginDir, webappPluginDir, a.Log) + env, err := plugin.NewEnvironment(a.NewPluginAPI, pluginDir, webappPluginDir, a.Log()) if err != nil { mlog.Error("Failed to start up plugins", mlog.Err(err)) return @@ -177,20 +177,20 @@ func (a *App) InitPlugins(pluginDir, webappPluginDir string) { pluginsEnvironment.SetPrepackagedPlugins(plugins) // Sync plugin active state when config changes. Also notify plugins. - a.Srv.PluginsLock.Lock() - a.RemoveConfigListener(a.Srv.PluginConfigListenerId) - a.Srv.PluginConfigListenerId = a.AddConfigListener(func(*model.Config, *model.Config) { + a.Srv().PluginsLock.Lock() + a.RemoveConfigListener(a.Srv().PluginConfigListenerId) + a.Srv().PluginConfigListenerId = a.AddConfigListener(func(*model.Config, *model.Config) { a.SyncPluginsActiveState() if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { if err := hooks.OnConfigurationChange(); err != nil { - a.Log.Error("Plugin OnConfigurationChange hook failed", mlog.Err(err)) + a.Log().Error("Plugin OnConfigurationChange hook failed", mlog.Err(err)) } return true }, plugin.OnConfigurationChangeId) } }) - a.Srv.PluginsLock.Unlock() + a.Srv().PluginsLock.Unlock() a.SyncPluginsActiveState() } @@ -269,14 +269,14 @@ func (a *App) ShutDownPlugins() { pluginsEnvironment.Shutdown() - a.RemoveConfigListener(a.Srv.PluginConfigListenerId) - a.Srv.PluginConfigListenerId = "" + a.RemoveConfigListener(a.Srv().PluginConfigListenerId) + a.Srv().PluginConfigListenerId = "" // Acquiring lock manually before cleaning up PluginsEnvironment. - a.Srv.PluginsLock.Lock() - defer a.Srv.PluginsLock.Unlock() - if a.Srv.PluginsEnvironment == pluginsEnvironment { - a.Srv.PluginsEnvironment = nil + a.Srv().PluginsLock.Lock() + defer a.Srv().PluginsLock.Unlock() + if a.Srv().PluginsEnvironment == pluginsEnvironment { + a.Srv().PluginsEnvironment = nil } else { mlog.Warn("Another PluginsEnvironment detected while shutting down plugins.") } @@ -471,7 +471,7 @@ func (a *App) getPrepackagedPlugin(pluginId, version string) (*plugin.Prepackage func (a *App) getRemoteMarketplacePlugin(pluginId, version string) (*model.BaseMarketplacePlugin, *model.AppError) { marketplaceClient, err := marketplace.NewClient( *a.Config().PluginSettings.MarketplaceUrl, - a.HTTPService, + a.HTTPService(), ) if err != nil { return nil, model.NewAppError("GetMarketplacePlugin", "app.plugin.marketplace_client.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -496,7 +496,7 @@ func (a *App) getRemotePlugins(filter *model.MarketplacePluginFilter) (map[strin marketplaceClient, err := marketplace.NewClient( *a.Config().PluginSettings.MarketplaceUrl, - a.HTTPService, + a.HTTPService(), ) if err != nil { return nil, model.NewAppError("getRemotePlugins", "app.plugin.marketplace_client.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -664,9 +664,9 @@ func (a *App) notifyPluginEnabled(manifest *model.Manifest) error { var statuses model.PluginStatuses - if a.Cluster != nil { + if a.Cluster() != nil { var err *model.AppError - statuses, err = a.Cluster.GetPluginStatuses() + statuses, err = a.Cluster().GetPluginStatuses() if err != nil { return err } diff --git a/app/plugin_api.go b/app/plugin_api.go index fa99755c62..090c2d5b35 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -30,7 +30,7 @@ func NewPluginAPI(a *App, manifest *model.Manifest) *PluginAPI { id: manifest.Id, manifest: manifest, app: a, - logger: a.Log.With(mlog.String("plugin_id", manifest.Id)).Sugar(), + logger: a.Log().With(mlog.String("plugin_id", manifest.Id)).Sugar(), } } @@ -292,7 +292,7 @@ func (api *PluginAPI) GetUsersInChannel(channelId, sortBy string, page, perPage } func (api *PluginAPI) GetLDAPUserAttributes(userId string, attributes []string) (map[string]string, *model.AppError) { - if api.app.Ldap == nil { + if api.app.Ldap() == nil { return nil, model.NewAppError("GetLdapUserAttributes", "ent.ldap.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -308,7 +308,7 @@ func (api *PluginAPI) GetLDAPUserAttributes(userId string, attributes []string) // Only bother running the query if the user's auth service is LDAP or it's SAML and sync is enabled. if user.AuthService == model.USER_AUTH_SERVICE_LDAP || (user.AuthService == model.USER_AUTH_SERVICE_SAML && *api.app.Config().SamlSettings.EnableSyncWithLdap) { - return api.app.Ldap.GetUserAttributes(*user.AuthData, attributes) + return api.app.Ldap().GetUserAttributes(*user.AuthData, attributes) } return map[string]string{}, nil diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index 72b4ec0b69..922496de2d 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -73,7 +73,7 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) - env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log) + env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log()) require.NoError(t, err) require.Equal(t, len(pluginCodes), len(pluginIds)) @@ -336,7 +336,7 @@ func TestPluginAPIGetFile(t *testing.T) { info, err := th.App.DoUploadFile(uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData) require.Nil(t, err) defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }() @@ -528,7 +528,7 @@ func TestPluginAPIGetPlugins(t *testing.T) { defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) - env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log) + env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log()) require.NoError(t, err) pluginIDs := []string{"pluginid1", "pluginid2", "pluginid3"} @@ -612,7 +612,7 @@ func TestInstallPlugin(t *testing.T) { *cfg.PluginSettings.ClientDirectory = webappPluginDir }) - env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log) + env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log()) require.NoError(t, err) app.SetPluginsEnvironment(env) @@ -1035,7 +1035,7 @@ func TestPluginCreatePostWithUploadedFile(t *testing.T) { fileInfo, err := api.UploadFile(data, channelId, filename) require.Nil(t, err) defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(fileInfo.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(fileInfo.Id) th.App.RemoveFile(fileInfo.Path) }() diff --git a/app/plugin_commands.go b/app/plugin_commands.go index 3dbc77924a..75df9a0aff 100644 --- a/app/plugin_commands.go +++ b/app/plugin_commands.go @@ -30,10 +30,10 @@ func (a *App) RegisterPluginCommand(pluginId string, command *model.Command) err DisplayName: command.DisplayName, } - a.Srv.pluginCommandsLock.Lock() - defer a.Srv.pluginCommandsLock.Unlock() + a.Srv().pluginCommandsLock.Lock() + defer a.Srv().pluginCommandsLock.Unlock() - for _, pc := range a.Srv.pluginCommands { + for _, pc := range a.Srv().pluginCommands { if pc.Command.Trigger == command.Trigger && pc.Command.TeamId == command.TeamId { if pc.PluginId == pluginId { pc.Command = command @@ -42,7 +42,7 @@ func (a *App) RegisterPluginCommand(pluginId string, command *model.Command) err } } - a.Srv.pluginCommands = append(a.Srv.pluginCommands, &PluginCommand{ + a.Srv().pluginCommands = append(a.Srv().pluginCommands, &PluginCommand{ Command: command, PluginId: pluginId, }) @@ -52,37 +52,37 @@ func (a *App) RegisterPluginCommand(pluginId string, command *model.Command) err func (a *App) UnregisterPluginCommand(pluginId, teamId, trigger string) { trigger = strings.ToLower(trigger) - a.Srv.pluginCommandsLock.Lock() - defer a.Srv.pluginCommandsLock.Unlock() + a.Srv().pluginCommandsLock.Lock() + defer a.Srv().pluginCommandsLock.Unlock() var remaining []*PluginCommand - for _, pc := range a.Srv.pluginCommands { + for _, pc := range a.Srv().pluginCommands { if pc.Command.TeamId != teamId || pc.Command.Trigger != trigger { remaining = append(remaining, pc) } } - a.Srv.pluginCommands = remaining + a.Srv().pluginCommands = remaining } func (a *App) UnregisterPluginCommands(pluginId string) { - a.Srv.pluginCommandsLock.Lock() - defer a.Srv.pluginCommandsLock.Unlock() + a.Srv().pluginCommandsLock.Lock() + defer a.Srv().pluginCommandsLock.Unlock() var remaining []*PluginCommand - for _, pc := range a.Srv.pluginCommands { + for _, pc := range a.Srv().pluginCommands { if pc.PluginId != pluginId { remaining = append(remaining, pc) } } - a.Srv.pluginCommands = remaining + a.Srv().pluginCommands = remaining } func (a *App) PluginCommandsForTeam(teamId string) []*model.Command { - a.Srv.pluginCommandsLock.RLock() - defer a.Srv.pluginCommandsLock.RUnlock() + a.Srv().pluginCommandsLock.RLock() + defer a.Srv().pluginCommandsLock.RUnlock() var commands []*model.Command - for _, pc := range a.Srv.pluginCommands { + for _, pc := range a.Srv().pluginCommands { if pc.Command.TeamId == "" || pc.Command.TeamId == teamId { commands = append(commands, pc.Command) } @@ -98,14 +98,14 @@ func (a *App) tryExecutePluginCommand(args *model.CommandArgs) (*model.Command, trigger = strings.ToLower(trigger) var matched *PluginCommand - a.Srv.pluginCommandsLock.RLock() - for _, pc := range a.Srv.pluginCommands { + a.Srv().pluginCommandsLock.RLock() + for _, pc := range a.Srv().pluginCommands { if (pc.Command.TeamId == "" || pc.Command.TeamId == args.TeamId) && pc.Command.Trigger == trigger { matched = pc break } } - a.Srv.pluginCommandsLock.RUnlock() + a.Srv().pluginCommandsLock.RUnlock() if matched == nil { return nil, nil, nil } diff --git a/app/plugin_context.go b/app/plugin_context.go index 1276fe10e5..fbf2de4cd2 100644 --- a/app/plugin_context.go +++ b/app/plugin_context.go @@ -7,11 +7,11 @@ import "github.com/mattermost/mattermost-server/v5/plugin" func (a *App) PluginContext() *plugin.Context { context := &plugin.Context{ - RequestId: a.RequestId, - SessionId: a.Session.Id, - IpAddress: a.IpAddress, - AcceptLanguage: a.AcceptLanguage, - UserAgent: a.UserAgent, + RequestId: a.RequestId(), + SessionId: a.Session().Id, + IpAddress: a.IpAddress(), + AcceptLanguage: a.AcceptLanguage(), + UserAgent: a.UserAgent(), } return context } diff --git a/app/plugin_event.go b/app/plugin_event.go index 24fdc44ee8..f2a307cfdb 100644 --- a/app/plugin_event.go +++ b/app/plugin_event.go @@ -9,8 +9,8 @@ import ( // notifyClusterPluginEvent publishes `event` to other clusters. func (a *App) notifyClusterPluginEvent(event string, data model.PluginEventData) { - if a.Cluster != nil { - a.Cluster.SendClusterMessage(&model.ClusterMessage{ + if a.Cluster() != nil { + a.Cluster().SendClusterMessage(&model.ClusterMessage{ Event: event, SendType: model.CLUSTER_SEND_RELIABLE, WaitForAllToSend: true, diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index 2cc1ced1b5..4eb98fd3aa 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -31,7 +31,7 @@ func SetAppEnvironmentWithPlugins(t *testing.T, pluginCode []string, app *App, a webappPluginDir, err := ioutil.TempDir("", "") require.NoError(t, err) - env, err := plugin.NewEnvironment(apiFunc, pluginDir, webappPluginDir, app.Log) + env, err := plugin.NewEnvironment(apiFunc, pluginDir, webappPluginDir, app.Log()) require.NoError(t, err) app.SetPluginsEnvironment(env) @@ -180,7 +180,7 @@ func TestHookMessageWillBePosted(t *testing.T) { require.Nil(t, err) assert.Equal(t, "message", post.Message) - retrievedPost, errSingle := th.App.Srv.Store.Post().GetSingle(post.Id) + retrievedPost, errSingle := th.App.Srv().Store.Post().GetSingle(post.Id) require.Nil(t, errSingle) assert.Equal(t, "message", retrievedPost.Message) }) @@ -224,7 +224,7 @@ func TestHookMessageWillBePosted(t *testing.T) { require.Nil(t, err) assert.Equal(t, "message_fromplugin", post.Message) - retrievedPost, errSingle := th.App.Srv.Store.Post().GetSingle(post.Id) + retrievedPost, errSingle := th.App.Srv().Store.Post().GetSingle(post.Id) require.Nil(t, errSingle) assert.Equal(t, "message_fromplugin", retrievedPost.Message) }) @@ -736,7 +736,7 @@ func TestUserWillLogInIn_Passed(t *testing.T) { err = th.App.DoLogin(w, r, th.BasicUser, "") assert.Nil(t, err, "Expected nil, got %s", err) - assert.Equal(t, th.App.Session.UserId, th.BasicUser.Id) + assert.Equal(t, th.App.Session().UserId, th.BasicUser.Id) } func TestUserHasLoggedIn(t *testing.T) { @@ -908,19 +908,19 @@ func TestHookContext(t *testing.T) { defer th.TearDown() // We don't actually have a session, we are faking it so just set something arbitrarily - th.App.Session.Id = model.NewId() - th.App.RequestId = model.NewId() - th.App.IpAddress = model.NewId() - th.App.AcceptLanguage = model.NewId() - th.App.UserAgent = model.NewId() + th.App.Session().Id = model.NewId() + th.App.requestId = model.NewId() + th.App.ipAddress = model.NewId() + th.App.acceptLanguage = model.NewId() + th.App.userAgent = model.NewId() var mockAPI plugintest.API mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil) - mockAPI.On("LogDebug", th.App.Session.Id).Return(nil) - mockAPI.On("LogInfo", th.App.RequestId).Return(nil) - mockAPI.On("LogError", th.App.IpAddress).Return(nil) - mockAPI.On("LogWarn", th.App.AcceptLanguage).Return(nil) - mockAPI.On("DeleteTeam", th.App.UserAgent).Return(nil) + mockAPI.On("LogDebug", th.App.Session().Id).Return(nil) + mockAPI.On("LogInfo", th.App.RequestId()).Return(nil) + mockAPI.On("LogError", th.App.IpAddress()).Return(nil) + mockAPI.On("LogWarn", th.App.AcceptLanguage()).Return(nil) + mockAPI.On("DeleteTeam", th.App.UserAgent()).Return(nil) tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{ diff --git a/app/plugin_key_value_store.go b/app/plugin_key_value_store.go index 4bff3f59be..2bde3a45ee 100644 --- a/app/plugin_key_value_store.go +++ b/app/plugin_key_value_store.go @@ -44,14 +44,14 @@ func (a *App) SetPluginKeyWithOptions(pluginId string, key string, value []byte, return false, err } - updated, err := a.Srv.Store.Plugin().SetWithOptions(pluginId, key, value, options) + updated, err := a.Srv().Store.Plugin().SetWithOptions(pluginId, key, value, options) if err != nil { mlog.Error("Failed to set plugin key value with options", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) return updated, err } // Clean up a previous entry using the hashed key, if it exists. - if err := a.Srv.Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { + if err := a.Srv().Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { mlog.Error("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) } @@ -64,14 +64,14 @@ func (a *App) CompareAndDeletePluginKey(pluginId string, key string, oldValue [] Key: key, } - deleted, err := a.Srv.Store.Plugin().CompareAndDelete(kv, oldValue) + deleted, err := a.Srv().Store.Plugin().CompareAndDelete(kv, oldValue) if err != nil { mlog.Error("Failed to compare and delete plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) return deleted, err } // Clean up a previous entry using the hashed key, if it exists. - if err := a.Srv.Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { + if err := a.Srv().Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { mlog.Error("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) } @@ -79,7 +79,7 @@ func (a *App) CompareAndDeletePluginKey(pluginId string, key string, oldValue [] } func (a *App) GetPluginKey(pluginId string, key string) ([]byte, *model.AppError) { - if kv, err := a.Srv.Store.Plugin().Get(pluginId, key); err == nil { + if kv, err := a.Srv().Store.Plugin().Get(pluginId, key); err == nil { return kv.Value, nil } else if err.StatusCode != http.StatusNotFound { mlog.Error("Failed to query plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) @@ -87,7 +87,7 @@ func (a *App) GetPluginKey(pluginId string, key string) ([]byte, *model.AppError } // Lookup using the hashed version of the key for keys written prior to v5.6. - if kv, err := a.Srv.Store.Plugin().Get(pluginId, getKeyHash(key)); err == nil { + if kv, err := a.Srv().Store.Plugin().Get(pluginId, getKeyHash(key)); err == nil { return kv.Value, nil } else if err.StatusCode != http.StatusNotFound { mlog.Error("Failed to query plugin key value using hashed key", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) @@ -98,13 +98,13 @@ func (a *App) GetPluginKey(pluginId string, key string) ([]byte, *model.AppError } func (a *App) DeletePluginKey(pluginId string, key string) *model.AppError { - if err := a.Srv.Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { + if err := a.Srv().Store.Plugin().Delete(pluginId, getKeyHash(key)); err != nil { mlog.Error("Failed to delete plugin key value", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) return err } // Also delete the key without hashing - if err := a.Srv.Store.Plugin().Delete(pluginId, key); err != nil { + if err := a.Srv().Store.Plugin().Delete(pluginId, key); err != nil { mlog.Error("Failed to delete plugin key value using hashed key", mlog.String("plugin_id", pluginId), mlog.String("key", key), mlog.Err(err)) return err } @@ -113,7 +113,7 @@ func (a *App) DeletePluginKey(pluginId string, key string) *model.AppError { } func (a *App) DeleteAllKeysForPlugin(pluginId string) *model.AppError { - if err := a.Srv.Store.Plugin().DeleteAllForPlugin(pluginId); err != nil { + if err := a.Srv().Store.Plugin().DeleteAllForPlugin(pluginId); err != nil { mlog.Error("Failed to delete all plugin key values", mlog.String("plugin_id", pluginId), mlog.Err(err)) return err } @@ -122,11 +122,11 @@ func (a *App) DeleteAllKeysForPlugin(pluginId string) *model.AppError { } func (a *App) DeleteAllExpiredPluginKeys() *model.AppError { - if a.Srv == nil { + if a.Srv() == nil { return nil } - if err := a.Srv.Store.Plugin().DeleteAllExpired(); err != nil { + if err := a.Srv().Store.Plugin().DeleteAllExpired(); err != nil { mlog.Error("Failed to delete all expired plugin key values", mlog.Err(err)) return err } @@ -135,7 +135,7 @@ func (a *App) DeleteAllExpiredPluginKeys() *model.AppError { } func (a *App) ListPluginKeys(pluginId string, page, perPage int) ([]string, *model.AppError) { - data, err := a.Srv.Store.Plugin().List(pluginId, page*perPage, perPage) + data, err := a.Srv().Store.Plugin().List(pluginId, page*perPage, perPage) if err != nil { mlog.Error("Failed to list plugin key values", mlog.Int("page", page), mlog.Int("perPage", perPage), mlog.Err(err)) diff --git a/app/plugin_requests.go b/app/plugin_requests.go index 69a1924057..b78673103e 100644 --- a/app/plugin_requests.go +++ b/app/plugin_requests.go @@ -24,7 +24,7 @@ func (a *App) ServePluginRequest(w http.ResponseWriter, r *http.Request) { pluginsEnvironment := a.GetPluginsEnvironment() if pluginsEnvironment == nil { err := model.NewAppError("ServePluginRequest", "app.plugin.disabled.app_error", nil, "Enable plugins to serve plugin requests", http.StatusNotImplemented) - a.Log.Error(err.Error()) + a.Log().Error(err.Error()) w.WriteHeader(err.StatusCode) w.Header().Set("Content-Type", "application/json") w.Write([]byte(err.ToJson())) @@ -34,7 +34,7 @@ func (a *App) ServePluginRequest(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) hooks, err := pluginsEnvironment.HooksForPlugin(params["plugin_id"]) if err != nil { - a.Log.Error("Access to route for non-existent plugin", mlog.String("missing_plugin_id", params["plugin_id"]), mlog.Err(err)) + a.Log().Error("Access to route for non-existent plugin", mlog.String("missing_plugin_id", params["plugin_id"]), mlog.Err(err)) http.NotFound(w, r) return } @@ -46,7 +46,7 @@ func (a *App) ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, so pluginsEnvironment := a.GetPluginsEnvironment() if pluginsEnvironment == nil { err := model.NewAppError("ServeInterPluginRequest", "app.plugin.disabled.app_error", nil, "Plugin enviroment not found.", http.StatusNotImplemented) - a.Log.Error(err.Error()) + a.Log().Error(err.Error()) w.WriteHeader(err.StatusCode) w.Header().Set("Content-Type", "application/json") w.Write([]byte(err.ToJson())) @@ -55,7 +55,7 @@ func (a *App) ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, so hooks, err := pluginsEnvironment.HooksForPlugin(destinationPluginId) if err != nil { - a.Log.Error("Access to route for non-existent plugin in inter plugin request", + a.Log().Error("Access to route for non-existent plugin in inter plugin request", mlog.String("source_plugin_id", sourcePluginId), mlog.String("destination_plugin_id", destinationPluginId), mlog.Err(err), @@ -166,9 +166,9 @@ func (a *App) servePluginRequest(w http.ResponseWriter, r *http.Request, handler } if *a.Config().ServiceSettings.ExperimentalStrictCSRFEnforcement { - a.Log.Warn(csrfErrorMessage, fields...) + a.Log().Warn(csrfErrorMessage, fields...) } else { - a.Log.Debug(csrfErrorMessage, fields...) + a.Log().Debug(csrfErrorMessage, fields...) csrfCheckPassed = true } } diff --git a/app/plugin_signature.go b/app/plugin_signature.go index d46cdca790..c3d1ef8062 100644 --- a/app/plugin_signature.go +++ b/app/plugin_signature.go @@ -25,7 +25,7 @@ func (a *App) GetPluginPublicKeyFiles() ([]string, *model.AppError) { // GetPublicKey will return the actual public key saved in the `name` file. func (a *App) GetPublicKey(name string) ([]byte, *model.AppError) { - data, err := a.Srv.configStore.GetFile(name) + data, err := a.Srv().configStore.GetFile(name) if err != nil { return nil, model.NewAppError("GetPublicKey", "app.plugin.get_public_key.get_file.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -41,7 +41,7 @@ func (a *App) AddPublicKey(name string, key io.Reader) *model.AppError { if err != nil { return model.NewAppError("AddPublicKey", "app.plugin.write_file.read.app_error", nil, err.Error(), http.StatusInternalServerError) } - err = a.Srv.configStore.SetFile(name, data) + err = a.Srv().configStore.SetFile(name, data) if err != nil { return model.NewAppError("AddPublicKey", "app.plugin.write_file.saving.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -61,7 +61,7 @@ func (a *App) DeletePublicKey(name string) *model.AppError { return model.NewAppError("AddPublicKey", "app.plugin.modify_saml.app_error", nil, "", http.StatusInternalServerError) } filename := filepath.Base(name) - if err := a.Srv.configStore.RemoveFile(filename); err != nil { + if err := a.Srv().configStore.RemoveFile(filename); err != nil { return model.NewAppError("DeletePublicKey", "app.plugin.delete_public_key.delete.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/plugin_statuses.go b/app/plugin_statuses.go index 05b37303b2..e6c2486315 100644 --- a/app/plugin_statuses.go +++ b/app/plugin_statuses.go @@ -58,8 +58,8 @@ func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) return nil, err } - if a.Cluster != nil && *a.Config().ClusterSettings.Enable { - clusterPluginStatuses, err := a.Cluster.GetPluginStatuses() + if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { + clusterPluginStatuses, err := a.Cluster().GetPluginStatuses() if err != nil { return nil, model.NewAppError("GetClusterPluginStatuses", "app.plugin.get_cluster_plugin_statuses.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/plugin_test.go b/app/plugin_test.go index 7a8922447c..0b0b573d14 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -73,7 +73,7 @@ func TestPluginKeyValueStore(t *testing.T) { ExpireAt: 0, } - _, err = th.App.Srv.Store.Plugin().SaveOrUpdate(kv) + _, err = th.App.Srv().Store.Plugin().SaveOrUpdate(kv) assert.Nil(t, err) // Test fetch by keyname (this key does not exist but hashed key will be used for lookup) diff --git a/app/post.go b/app/post.go index 07ed78b461..bf8028af9c 100644 --- a/app/post.go +++ b/app/post.go @@ -26,7 +26,7 @@ const ( func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string) (*model.Post, *model.AppError) { // Check that channel has not been deleted - channel, errCh := a.Srv.Store.Channel().Get(post.ChannelId, true) + channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) if errCh != nil { err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.channel_id"}, errCh.Error(), http.StatusBadRequest) return nil, err @@ -51,7 +51,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string) (*mode } if err.Id == "api.post.create_post.town_square_read_only" { - user, userErr := a.Srv.Store.User().Get(post.UserId) + user, userErr := a.Srv().Store.User().Get(post.UserId) if userErr != nil { return nil, userErr } @@ -88,7 +88,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string) (*mode } func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { - channel, err := a.Srv.Store.Channel().Get(post.ChannelId, true) + channel, err := a.Srv().Store.Channel().Get(post.ChannelId, true) if err != nil { return nil, err } @@ -108,7 +108,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er // Query the cache atomically for the given pending post id, saving a record if // it hasn't previously been seen. - value, loaded := a.Srv.seenPendingPostIdsCache.GetOrAdd(post.PendingPostId, unknownPostId, PENDING_POST_IDS_CACHE_TTL) + value, loaded := a.Srv().seenPendingPostIdsCache.GetOrAdd(post.PendingPostId, unknownPostId, PENDING_POST_IDS_CACHE_TTL) // If we were the first thread to save this pending post id into the cache, // proceed with create post normally. @@ -154,11 +154,11 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo } if err != nil { - a.Srv.seenPendingPostIdsCache.Remove(post.PendingPostId) + a.Srv().seenPendingPostIdsCache.Remove(post.PendingPostId) return } - a.Srv.seenPendingPostIdsCache.AddWithExpiresInSecs(post.PendingPostId, savedPost.Id, int64(PENDING_POST_IDS_CACHE_TTL.Seconds())) + a.Srv().seenPendingPostIdsCache.AddWithExpiresInSecs(post.PendingPostId, savedPost.Id, int64(PENDING_POST_IDS_CACHE_TTL.Seconds())) }() post.SanitizeProps() @@ -167,13 +167,13 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo if len(post.RootId) > 0 { pchan = make(chan store.StoreResult, 1) go func() { - r, pErr := a.Srv.Store.Post().Get(post.RootId, false) + r, pErr := a.Srv().Store.Post().Get(post.RootId, false) pchan <- store.StoreResult{Data: r, Err: pErr} close(pchan) }() } - user, err := a.Srv.Store.User().Get(post.UserId) + user, err := a.Srv().Store.User().Get(post.UserId) if err != nil { return nil, err } @@ -262,17 +262,17 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo } } - rpost, err := a.Srv.Store.Post().Save(post) + rpost, err := a.Srv().Store.Post().Save(post) if err != nil { return nil, err } // Update the mapping from pending post id to the actual post id, for any clients that // might be duplicating requests. - a.Srv.seenPendingPostIdsCache.AddWithExpiresInSecs(post.PendingPostId, rpost.Id, int64(PENDING_POST_IDS_CACHE_TTL.Seconds())) + a.Srv().seenPendingPostIdsCache.AddWithExpiresInSecs(post.PendingPostId, rpost.Id, int64(PENDING_POST_IDS_CACHE_TTL.Seconds())) if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.MessageHasBeenPosted(pluginContext, rpost) @@ -282,15 +282,15 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { - if err = a.Elasticsearch.IndexPost(rpost, channel.TeamId); err != nil { + a.Srv().Go(func() { + if err = a.Elasticsearch().IndexPost(rpost, channel.TeamId); err != nil { mlog.Error("Encountered error indexing post", mlog.String("post_id", post.Id), mlog.Err(err)) } }) } - if a.Metrics != nil { - a.Metrics.IncrementPostCreate() + if a.Metrics() != nil { + a.Metrics().IncrementPostCreate() } if len(post.FileIds) > 0 { @@ -298,8 +298,8 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo mlog.Error("Encountered error attaching files to post", mlog.String("post_id", post.Id), mlog.Any("file_ids", post.FileIds), mlog.Err(err)) } - if a.Metrics != nil { - a.Metrics.IncrementPostFileAttachment(len(post.FileIds)) + if a.Metrics() != nil { + a.Metrics().IncrementPostFileAttachment(len(post.FileIds)) } } @@ -317,7 +317,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo func (a *App) attachFilesToPost(post *model.Post) *model.AppError { var attachedIds []string for _, fileId := range post.FileIds { - err := a.Srv.Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId) + err := a.Srv().Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId) if err != nil { mlog.Warn("Failed to attach file to post", mlog.String("file_id", fileId), mlog.String("post_id", post.Id), mlog.Err(err)) continue @@ -330,7 +330,7 @@ func (a *App) attachFilesToPost(post *model.Post) *model.AppError { // We couldn't attach all files to the post, so ensure that post.FileIds reflects what was actually attached post.FileIds = attachedIds - if _, err := a.Srv.Store.Post().Overwrite(post); err != nil { + if _, err := a.Srv().Store.Post().Overwrite(post); err != nil { return err } } @@ -348,7 +348,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A if len(channelMentions) > 0 { if channel == nil { - postChannel, err := a.Srv.Store.Channel().GetForPost(post.Id) + postChannel, err := a.Srv().Store.Channel().GetForPost(post.Id) if err != nil { return model.NewAppError("FillInPostProps", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.channel_id"}, err.Error(), http.StatusBadRequest) } @@ -381,7 +381,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList) error { var team *model.Team if len(channel.TeamId) > 0 { - t, err := a.Srv.Store.Team().Get(channel.TeamId) + t, err := a.Srv().Store.Team().Get(channel.TeamId) if err != nil { return err } @@ -398,7 +398,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode return err } - a.Srv.Go(func() { + a.Srv().Go(func() { _, err := a.SendAutoResponseIfNecessary(channel, user) if err != nil { mlog.Error("Failed to send auto response", mlog.String("user_id", user.Id), mlog.String("post_id", post.Id), mlog.Err(err)) @@ -406,7 +406,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode }) if triggerWebhooks { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.handleWebhookEvents(post, team, channel, user); err != nil { mlog.Error(err.Error()) } @@ -475,7 +475,7 @@ func (a *App) DeleteEphemeralPost(userId, postId string) { func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { post.SanitizeProps() - postLists, err := a.Srv.Store.Post().Get(post.Id, false) + postLists, err := a.Srv().Store.Post().Get(post.Id, false) if err != nil { return nil, err } @@ -549,13 +549,13 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model } } - rpost, err := a.Srv.Store.Post().Update(newPost, oldPost) + rpost, err := a.Srv().Store.Post().Update(newPost, oldPost) if err != nil { return nil, err } if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.MessageHasBeenUpdated(pluginContext, newPost, oldPost) @@ -565,13 +565,13 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { - channel, chanErr := a.Srv.Store.Channel().GetForPost(rpost.Id) + a.Srv().Go(func() { + channel, chanErr := a.Srv().Store.Channel().GetForPost(rpost.Id) if chanErr != nil { mlog.Error("Couldn't get channel for post for Elasticsearch indexing.", mlog.String("channel_id", rpost.ChannelId), mlog.String("post_id", rpost.Id)) return } - if err := a.Elasticsearch.IndexPost(rpost, channel.TeamId); err != nil { + if err := a.Elasticsearch().IndexPost(rpost, channel.TeamId); err != nil { mlog.Error("Encountered error indexing post", mlog.String("post_id", post.Id), mlog.Err(err)) } }) @@ -615,43 +615,43 @@ func (a *App) PatchPost(postId string, patch *model.PostPatch) (*model.Post, *mo } func (a *App) GetPostsPage(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetPosts(options, false) + return a.Srv().Store.Post().GetPosts(options, false) } func (a *App) GetPosts(channelId string, offset int, limit int) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channelId, Page: offset, PerPage: limit}, true) + return a.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channelId, Page: offset, PerPage: limit}, true) } func (a *App) GetPostsEtag(channelId string) string { - return a.Srv.Store.Post().GetEtag(channelId, true) + return a.Srv().Store.Post().GetEtag(channelId, true) } func (a *App) GetPostsSince(options model.GetPostsSinceOptions) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetPostsSince(options, true) + return a.Srv().Store.Post().GetPostsSince(options, true) } func (a *App) GetSinglePost(postId string) (*model.Post, *model.AppError) { - return a.Srv.Store.Post().GetSingle(postId) + return a.Srv().Store.Post().GetSingle(postId) } func (a *App) GetPostThread(postId string, skipFetchThreads bool) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().Get(postId, skipFetchThreads) + return a.Srv().Store.Post().Get(postId, skipFetchThreads) } func (a *App) GetFlaggedPosts(userId string, offset int, limit int) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetFlaggedPosts(userId, offset, limit) + return a.Srv().Store.Post().GetFlaggedPosts(userId, offset, limit) } func (a *App) GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetFlaggedPostsForTeam(userId, teamId, offset, limit) + return a.Srv().Store.Post().GetFlaggedPostsForTeam(userId, teamId, offset, limit) } func (a *App) GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetFlaggedPostsForChannel(userId, channelId, offset, limit) + return a.Srv().Store.Post().GetFlaggedPostsForChannel(userId, channelId, offset, limit) } func (a *App) GetPermalinkPost(postId string, userId string) (*model.PostList, *model.AppError) { - list, err := a.Srv.Store.Post().Get(postId, false) + list, err := a.Srv().Store.Post().Get(postId, false) if err != nil { return nil, err } @@ -674,30 +674,30 @@ func (a *App) GetPermalinkPost(postId string, userId string) (*model.PostList, * } func (a *App) GetPostsBeforePost(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetPostsBefore(options) + return a.Srv().Store.Post().GetPostsBefore(options) } func (a *App) GetPostsAfterPost(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - return a.Srv.Store.Post().GetPostsAfter(options) + return a.Srv().Store.Post().GetPostsAfter(options) } func (a *App) GetPostsAroundPost(before bool, options model.GetPostsOptions) (*model.PostList, *model.AppError) { if before { - return a.Srv.Store.Post().GetPostsBefore(options) + return a.Srv().Store.Post().GetPostsBefore(options) } - return a.Srv.Store.Post().GetPostsAfter(options) + return a.Srv().Store.Post().GetPostsAfter(options) } func (a *App) GetPostAfterTime(channelId string, time int64) (*model.Post, *model.AppError) { - return a.Srv.Store.Post().GetPostAfterTime(channelId, time) + return a.Srv().Store.Post().GetPostAfterTime(channelId, time) } func (a *App) GetPostIdAfterTime(channelId string, time int64) (string, *model.AppError) { - return a.Srv.Store.Post().GetPostIdAfterTime(channelId, time) + return a.Srv().Store.Post().GetPostIdAfterTime(channelId, time) } func (a *App) GetPostIdBeforeTime(channelId string, time int64) (string, *model.AppError) { - return a.Srv.Store.Post().GetPostIdBeforeTime(channelId, time) + return a.Srv().Store.Post().GetPostIdBeforeTime(channelId, time) } func (a *App) GetNextPostIdFromPostList(postList *model.PostList) string { @@ -814,7 +814,7 @@ func (a *App) GetPostsForChannelAroundLastUnread(channelId, userId string, limit } func (a *App) DeletePost(postId, deleteByID string) (*model.Post, *model.AppError) { - post, err := a.Srv.Store.Post().GetSingle(postId) + post, err := a.Srv().Store.Post().GetSingle(postId) if err != nil { err.StatusCode = http.StatusBadRequest return nil, err @@ -830,7 +830,7 @@ func (a *App) DeletePost(postId, deleteByID string) (*model.Post, *model.AppErro return nil, err } - if err := a.Srv.Store.Post().Delete(postId, model.GetMillis(), deleteByID); err != nil { + if err := a.Srv().Store.Post().Delete(postId, model.GetMillis(), deleteByID); err != nil { return nil, err } @@ -838,16 +838,16 @@ func (a *App) DeletePost(postId, deleteByID string) (*model.Post, *model.AppErro message.Add("post", a.PreparePostForClient(post, false, false).ToJson()) a.Publish(message) - a.Srv.Go(func() { + a.Srv().Go(func() { a.DeletePostFiles(post) }) - a.Srv.Go(func() { + a.Srv().Go(func() { a.DeleteFlaggedPosts(post.Id) }) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { - if err := a.Elasticsearch.DeletePost(post); err != nil { + a.Srv().Go(func() { + if err := a.Elasticsearch().DeletePost(post); err != nil { mlog.Error("Encountered error deleting post", mlog.String("post_id", post.Id), mlog.Err(err)) } }) @@ -859,7 +859,7 @@ func (a *App) DeletePost(postId, deleteByID string) (*model.Post, *model.AppErro } func (a *App) DeleteFlaggedPosts(postId string) { - if err := a.Srv.Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postId); err != nil { + if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postId); err != nil { mlog.Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err)) return } @@ -870,7 +870,7 @@ func (a *App) DeletePostFiles(post *model.Post) { return } - if _, err := a.Srv.Store.FileInfo().DeleteForPost(post.Id); err != nil { + if _, err := a.Srv().Store.FileInfo().DeleteForPost(post.Id); err != nil { mlog.Warn("Encountered error when deleting files for post", mlog.String("post_id", post.Id), mlog.Err(err)) } } @@ -927,7 +927,7 @@ func (a *App) searchPostsInTeam(teamId string, userId string, paramsList []*mode go func(params *model.SearchParams) { defer wg.Done() - postList, err := a.Srv.Store.Post().Search(teamId, userId, params) + postList, err := a.Srv().Store.Post().Search(teamId, userId, params) pchan <- store.StoreResult{Data: postList, Err: err} }(params) } @@ -1013,7 +1013,7 @@ func (a *App) esSearchPostsInTeamForUser(paramsList []*model.SearchParams, userI return nil, err } - postIds, matches, err := a.Elasticsearch.SearchPosts(userChannels, finalParamsList, page, perPage) + postIds, matches, err := a.Elasticsearch().SearchPosts(userChannels, finalParamsList, page, perPage) if err != nil { return nil, err } @@ -1021,7 +1021,7 @@ func (a *App) esSearchPostsInTeamForUser(paramsList []*model.SearchParams, userI // Get the posts postList := model.NewPostList() if len(postIds) > 0 { - posts, err := a.Srv.Store.Post().GetPostsByIds(postIds) + posts, err := a.Srv().Store.Post().GetPostsByIds(postIds) if err != nil { return nil, err } @@ -1097,7 +1097,7 @@ func (a *App) GetFileInfosForPostWithMigration(postId string) ([]*model.FileInfo pchan := make(chan store.StoreResult, 1) go func() { - post, err := a.Srv.Store.Post().GetSingle(postId) + post, err := a.Srv().Store.Post().GetSingle(postId) pchan <- store.StoreResult{Data: post, Err: err} close(pchan) }() @@ -1116,7 +1116,7 @@ func (a *App) GetFileInfosForPostWithMigration(postId string) ([]*model.FileInfo post := result.Data.(*model.Post) if len(post.Filenames) > 0 { - a.Srv.Store.FileInfo().InvalidateFileInfosForPostCache(postId) + a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(postId) // The post has Filenames that need to be replaced with FileInfos infos = a.MigrateFilenamesToFileInfos(post) } @@ -1126,7 +1126,7 @@ func (a *App) GetFileInfosForPostWithMigration(postId string) ([]*model.FileInfo } func (a *App) GetFileInfosForPost(postId string, fromMaster bool) ([]*model.FileInfo, *model.AppError) { - return a.Srv.Store.FileInfo().GetForPost(postId, fromMaster, false, true) + return a.Srv().Store.FileInfo().GetForPost(postId, fromMaster, false, true) } func (a *App) PostWithProxyAddedToImageURLs(post *model.Post) *model.Post { @@ -1156,7 +1156,7 @@ func (a *App) ImageProxyAdder() func(string) string { } return func(url string) string { - return a.Srv.ImageProxy.GetProxiedImageURL(url) + return a.Srv().ImageProxy.GetProxiedImageURL(url) } } @@ -1166,12 +1166,12 @@ func (a *App) ImageProxyRemover() (f func(string) string) { } return func(url string) string { - return a.Srv.ImageProxy.GetUnproxiedImageURL(url) + return a.Srv().ImageProxy.GetUnproxiedImageURL(url) } } func (a *App) MaxPostSize() int { - maxPostSize := a.Srv.Store.Post().GetMaxPostSize() + maxPostSize := a.Srv().Store.Post().GetMaxPostSize() if maxPostSize == 0 { return model.POST_MESSAGE_MAX_RUNES_V1 } @@ -1189,7 +1189,7 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, *m if channel.Type == model.CHANNEL_DIRECT { // In a DM channel, every post made by the other user is a mention - count, countErr := a.Srv.Store.Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id)) + count, countErr := a.Srv().Store.Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id)) if countErr != nil { return 0, countErr } diff --git a/app/post_metadata.go b/app/post_metadata.go index 6680db99d4..3610d75ebe 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -384,12 +384,12 @@ func (a *App) getLinkMetadata(requestURL string, timestamp int64, isNewPost bool if (request.URL.Scheme+"://"+request.URL.Host) == a.GetSiteURL() && request.URL.Path == "/api/v4/image" { // /api/v4/image requires authentication, so bypass the API by hitting the proxy directly - body, contentType, err = a.ImageProxy.GetImageDirect(a.ImageProxy.GetUnproxiedImageURL(request.URL.String())) + body, contentType, err = a.ImageProxy().GetImageDirect(a.ImageProxy().GetUnproxiedImageURL(request.URL.String())) } else { request.Header.Add("Accept", "image/*") request.Header.Add("Accept", "text/html;q=0.8") - client := a.HTTPService.MakeClient(false) + client := a.HTTPService().MakeClient(false) client.Timeout = time.Duration(*a.Config().ExperimentalSettings.LinkMetadataTimeoutMilliseconds) * time.Millisecond var res *http.Response @@ -451,7 +451,7 @@ func getLinkMetadataFromCache(requestURL string, timestamp int64) (*opengraph.Op } func (a *App) getLinkMetadataFromDatabase(requestURL string, timestamp int64) (*opengraph.OpenGraph, *model.PostImage, bool) { - linkMetadata, err := a.Srv.Store.LinkMetadata().Get(requestURL, timestamp) + linkMetadata, err := a.Srv().Store.LinkMetadata().Get(requestURL, timestamp) if err != nil { return nil, nil, false } @@ -484,7 +484,7 @@ func (a *App) saveLinkMetadataToDatabase(requestURL string, timestamp int64, og metadata.Type = model.LINK_METADATA_TYPE_NONE } - _, err := a.Srv.Store.LinkMetadata().Save(metadata) + _, err := a.Srv().Store.LinkMetadata().Save(metadata) if err != nil { mlog.Warn("Failed to write link metadata", mlog.String("request_url", requestURL), mlog.Err(err)) } diff --git a/app/post_test.go b/app/post_test.go index e8b1645d9b..72cffa820f 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -192,13 +192,13 @@ func TestAttachFilesToPost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - info1, err := th.App.Srv.Store.FileInfo().Save(&model.FileInfo{ + info1, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) require.Nil(t, err) - info2, err := th.App.Srv.Store.FileInfo().Save(&model.FileInfo{ + info2, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) @@ -219,14 +219,14 @@ func TestAttachFilesToPost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - info1, err := th.App.Srv.Store.FileInfo().Save(&model.FileInfo{ + info1, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", PostId: model.NewId(), }) require.Nil(t, err) - info2, err := th.App.Srv.Store.FileInfo().Save(&model.FileInfo{ + info2, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) @@ -577,7 +577,7 @@ func TestMaxPostSize(t *testing.T) { mockStore.PostStore.On("GetMaxPostSize").Return(testCase.StoreMaxPostSize) app := App{ - Srv: &Server{ + srv: &Server{ Store: mockStore, }, } @@ -601,7 +601,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) { info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) require.Nil(t, err) defer func() { - th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -837,7 +837,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { es := &mocks.ElasticsearchInterface{} es.On("SearchPosts", mock.Anything, mock.Anything, page, perPage).Return(resultsPage, nil, nil) - th.App.Elasticsearch = es + th.App.elasticsearch = es results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) @@ -858,7 +858,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { es := &mocks.ElasticsearchInterface{} es.On("SearchPosts", mock.Anything, mock.Anything, page, perPage).Return(resultsPage, nil, nil) - th.App.Elasticsearch = es + th.App.elasticsearch = es results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) @@ -875,7 +875,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { es := &mocks.ElasticsearchInterface{} es.On("SearchPosts", mock.Anything, mock.Anything, page, perPage).Return(nil, nil, &model.AppError{}) - th.App.Elasticsearch = es + th.App.elasticsearch = es results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) @@ -900,7 +900,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { es := &mocks.ElasticsearchInterface{} es.On("SearchPosts", mock.Anything, mock.Anything, page, perPage).Return(nil, nil, &model.AppError{}) - th.App.Elasticsearch = es + th.App.elasticsearch = es results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) diff --git a/app/preference.go b/app/preference.go index 8f7acfb05f..6c85f90e0d 100644 --- a/app/preference.go +++ b/app/preference.go @@ -10,7 +10,7 @@ import ( ) func (a *App) GetPreferencesForUser(userId string) (model.Preferences, *model.AppError) { - preferences, err := a.Srv.Store.Preference().GetAll(userId) + preferences, err := a.Srv().Store.Preference().GetAll(userId) if err != nil { err.StatusCode = http.StatusBadRequest return nil, err @@ -19,7 +19,7 @@ func (a *App) GetPreferencesForUser(userId string) (model.Preferences, *model.Ap } func (a *App) GetPreferenceByCategoryForUser(userId string, category string) (model.Preferences, *model.AppError) { - preferences, err := a.Srv.Store.Preference().GetCategory(userId, category) + preferences, err := a.Srv().Store.Preference().GetCategory(userId, category) if err != nil { err.StatusCode = http.StatusBadRequest return nil, err @@ -32,7 +32,7 @@ func (a *App) GetPreferenceByCategoryForUser(userId string, category string) (mo } func (a *App) GetPreferenceByCategoryAndNameForUser(userId string, category string, preferenceName string) (*model.Preference, *model.AppError) { - res, err := a.Srv.Store.Preference().Get(userId, category, preferenceName) + res, err := a.Srv().Store.Preference().Get(userId, category, preferenceName) if err != nil { err.StatusCode = http.StatusBadRequest return nil, err @@ -48,7 +48,7 @@ func (a *App) UpdatePreferences(userId string, preferences model.Preferences) *m } } - if err := a.Srv.Store.Preference().Save(&preferences); err != nil { + if err := a.Srv().Store.Preference().Save(&preferences); err != nil { err.StatusCode = http.StatusBadRequest return err } @@ -70,7 +70,7 @@ func (a *App) DeletePreferences(userId string, preferences model.Preferences) *m } for _, preference := range preferences { - if err := a.Srv.Store.Preference().Delete(userId, preference.Category, preference.Name); err != nil { + if err := a.Srv().Store.Preference().Delete(userId, preference.Category, preference.Name); err != nil { err.StatusCode = http.StatusBadRequest return err } diff --git a/app/reaction.go b/app/reaction.go index dd614c6114..bf45de77ff 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -36,7 +36,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m } } - reaction, err = a.Srv.Store.Reaction().Save(reaction) + reaction, err = a.Srv().Store.Reaction().Save(reaction) if err != nil { return nil, err } @@ -44,7 +44,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m // The post is always modified since the UpdateAt always changes a.InvalidateCacheForChannelPosts(post.ChannelId) - a.Srv.Go(func() { + a.Srv().Go(func() { a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, reaction, post, true) }) @@ -52,13 +52,13 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m } func (a *App) GetReactionsForPost(postId string) ([]*model.Reaction, *model.AppError) { - return a.Srv.Store.Reaction().GetForPost(postId, true) + return a.Srv().Store.Reaction().GetForPost(postId, true) } func (a *App) GetBulkReactionsForPosts(postIds []string) (map[string][]*model.Reaction, *model.AppError) { reactions := make(map[string][]*model.Reaction) - allReactions, err := a.Srv.Store.Reaction().BulkGetForPosts(postIds) + allReactions, err := a.Srv().Store.Reaction().BulkGetForPosts(postIds) if err != nil { return nil, err } @@ -114,14 +114,14 @@ func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { hasReactions = false } - if _, err := a.Srv.Store.Reaction().Delete(reaction); err != nil { + if _, err := a.Srv().Store.Reaction().Delete(reaction); err != nil { return err } // The post is always modified since the UpdateAt always changes a.InvalidateCacheForChannelPosts(post.ChannelId) - a.Srv.Go(func() { + a.Srv().Go(func() { a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, reaction, post, hasReactions) }) diff --git a/app/role.go b/app/role.go index cfa8994466..d05773d985 100644 --- a/app/role.go +++ b/app/role.go @@ -12,19 +12,19 @@ import ( ) func (a *App) GetRole(id string) (*model.Role, *model.AppError) { - return a.Srv.Store.Role().Get(id) + return a.Srv().Store.Role().Get(id) } func (a *App) GetAllRoles() ([]*model.Role, *model.AppError) { - return a.Srv.Store.Role().GetAll() + return a.Srv().Store.Role().GetAll() } func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) { - return a.Srv.Store.Role().GetByName(name) + return a.Srv().Store.Role().GetByName(name) } func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) { - return a.Srv.Store.Role().GetByNames(names) + return a.Srv().Store.Role().GetByNames(names) } func (a *App) PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError) { @@ -50,12 +50,12 @@ func (a *App) CreateRole(role *model.Role) (*model.Role, *model.AppError) { role.BuiltIn = false role.SchemeManaged = false - return a.Srv.Store.Role().Save(role) + return a.Srv().Store.Role().Save(role) } func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) { - savedRole, err := a.Srv.Store.Role().Save(role) + savedRole, err := a.Srv().Store.Role().Save(role) if err != nil { return nil, err } @@ -91,7 +91,7 @@ func (a *App) sendUpdatedRoleEvent(role *model.Role) { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ROLE_UPDATED, "", "", "", nil) message.Add("role", role.ToJson()) - a.Srv.Go(func() { + a.Srv().Go(func() { a.Publish(message) }) } diff --git a/app/saml.go b/app/saml.go index 5f2245de7c..53d93357f5 100644 --- a/app/saml.go +++ b/app/saml.go @@ -23,12 +23,12 @@ const ( ) func (a *App) GetSamlMetadata() (string, *model.AppError) { - if a.Saml == nil { + if a.Saml() == nil { err := model.NewAppError("GetSamlMetadata", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return "", err } - result, err := a.Saml.GetMetadata() + result, err := a.Saml().GetMetadata() if err != nil { return "", model.NewAppError("GetSamlMetadata", "api.admin.saml.metadata.app_error", nil, "err="+err.Message, err.StatusCode) } @@ -47,7 +47,7 @@ func (a *App) writeSamlFile(filename string, fileData *multipart.FileHeader) *mo return model.NewAppError("AddSamlCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError) } - err = a.Srv.configStore.SetFile(filename, data) + err = a.Srv().configStore.SetFile(filename, data) if err != nil { return model.NewAppError("AddSamlCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -107,7 +107,7 @@ func (a *App) AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppEr } func (a *App) removeSamlFile(filename string) *model.AppError { - if err := a.Srv.configStore.RemoveFile(filename); err != nil { + if err := a.Srv().configStore.RemoveFile(filename); err != nil { return model.NewAppError("RemoveSamlFile", "api.admin.remove_certificate.delete.app_error", map[string]interface{}{"Filename": filename}, err.Error(), http.StatusInternalServerError) } @@ -171,15 +171,15 @@ func (a *App) RemoveSamlIdpCertificate() *model.AppError { func (a *App) GetSamlCertificateStatus() *model.SamlCertificateStatus { status := &model.SamlCertificateStatus{} - status.IdpCertificateFile, _ = a.Srv.configStore.HasFile(*a.Config().SamlSettings.IdpCertificateFile) - status.PrivateKeyFile, _ = a.Srv.configStore.HasFile(*a.Config().SamlSettings.PrivateKeyFile) - status.PublicCertificateFile, _ = a.Srv.configStore.HasFile(*a.Config().SamlSettings.PublicCertificateFile) + status.IdpCertificateFile, _ = a.Srv().configStore.HasFile(*a.Config().SamlSettings.IdpCertificateFile) + status.PrivateKeyFile, _ = a.Srv().configStore.HasFile(*a.Config().SamlSettings.PrivateKeyFile) + status.PublicCertificateFile, _ = a.Srv().configStore.HasFile(*a.Config().SamlSettings.PublicCertificateFile) return status } func (a *App) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) { - if a.Saml == nil { + if a.Saml() == nil { err := model.NewAppError("GetSamlMetadataFromIdp", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return nil, err } @@ -202,7 +202,7 @@ func (a *App) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadata } func (a *App) FetchSamlMetadataFromIdp(url string) ([]byte, *model.AppError) { - resp, err := a.HTTPService.MakeClient(false).Get(url) + resp, err := a.HTTPService().MakeClient(false).Get(url) if err != nil { return nil, model.NewAppError("FetchSamlMetadataFromIdp", "app.admin.saml.invalid_response_from_idp.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -267,7 +267,7 @@ func (a *App) SetSamlIdpCertificateFromMetadata(data []byte) *model.AppError { Bytes: block.Bytes, }) - if err := a.Srv.configStore.SetFile(SamlIdpCertificateName, data); err != nil { + if err := a.Srv().configStore.SetFile(SamlIdpCertificateName, data); err != nil { return model.NewAppError("SetSamlIdpCertificateFromMetadata", "api.admin.saml.failure_save_idp_certificate_file.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/scheme.go b/app/scheme.go index 75d3f3dcb0..d4f29c48b1 100644 --- a/app/scheme.go +++ b/app/scheme.go @@ -14,7 +14,7 @@ func (a *App) GetScheme(id string) (*model.Scheme, *model.AppError) { return nil, err } - return a.Srv.Store.Scheme().Get(id) + return a.Srv().Store.Scheme().Get(id) } func (a *App) GetSchemeByName(name string) (*model.Scheme, *model.AppError) { @@ -22,7 +22,7 @@ func (a *App) GetSchemeByName(name string) (*model.Scheme, *model.AppError) { return nil, err } - return a.Srv.Store.Scheme().GetByName(name) + return a.Srv().Store.Scheme().GetByName(name) } func (a *App) GetSchemesPage(scope string, page int, perPage int) ([]*model.Scheme, *model.AppError) { @@ -38,7 +38,7 @@ func (a *App) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, return nil, err } - return a.Srv.Store.Scheme().GetAllPage(scope, offset, limit) + return a.Srv().Store.Scheme().GetAllPage(scope, offset, limit) } func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) { @@ -57,7 +57,7 @@ func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError scheme.UpdateAt = 0 scheme.DeleteAt = 0 - return a.Srv.Store.Scheme().Save(scheme) + return a.Srv().Store.Scheme().Save(scheme) } func (a *App) PatchScheme(scheme *model.Scheme, patch *model.SchemePatch) (*model.Scheme, *model.AppError) { @@ -79,7 +79,7 @@ func (a *App) UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError return nil, err } - return a.Srv.Store.Scheme().Save(scheme) + return a.Srv().Store.Scheme().Save(scheme) } func (a *App) DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) { @@ -87,7 +87,7 @@ func (a *App) DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) { return nil, err } - return a.Srv.Store.Scheme().Delete(schemeId) + return a.Srv().Store.Scheme().Delete(schemeId) } func (a *App) GetTeamsForSchemePage(scheme *model.Scheme, page int, perPage int) ([]*model.Team, *model.AppError) { @@ -103,7 +103,7 @@ func (a *App) GetTeamsForScheme(scheme *model.Scheme, offset int, limit int) ([] return nil, err } - teams, err := a.Srv.Store.Team().GetTeamsByScheme(scheme.Id, offset, limit) + teams, err := a.Srv().Store.Team().GetTeamsByScheme(scheme.Id, offset, limit) if err != nil { return nil, err } @@ -122,19 +122,19 @@ func (a *App) GetChannelsForScheme(scheme *model.Scheme, offset int, limit int) if err := a.IsPhase2MigrationCompleted(); err != nil { return nil, err } - return a.Srv.Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit) + return a.Srv().Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit) } func (a *App) IsPhase2MigrationCompleted() *model.AppError { - if a.Srv.phase2PermissionsMigrationComplete { + if a.Srv().phase2PermissionsMigrationComplete { return nil } - if _, err := a.Srv.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { + if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented) } - a.Srv.phase2PermissionsMigrationComplete = true + a.Srv().phase2PermissionsMigrationComplete = true return nil } @@ -142,7 +142,7 @@ func (a *App) IsPhase2MigrationCompleted() *model.AppError { func (a *App) SchemesIterator(batchSize int) func() []*model.Scheme { offset := 0 return func() []*model.Scheme { - schemes, err := a.Srv.Store.Scheme().GetAllPage("", offset, batchSize) + schemes, err := a.Srv().Store.Scheme().GetAllPage("", offset, batchSize) if err != nil { return []*model.Scheme{} } diff --git a/app/server.go b/app/server.go index 3e93e9c69b..353ad2732c 100644 --- a/app/server.go +++ b/app/server.go @@ -145,6 +145,7 @@ func NewServer(options ...Option) (*Server, error) { licenseListeners: map[string]func(){}, clientConfig: make(map[string]string), } + for _, option := range options { if err := option(s); err != nil { return nil, errors.Wrap(err, "failed to apply option") @@ -209,7 +210,6 @@ func NewServer(options ...Option) (*Server, error) { model.AppErrorInit(utils.T) s.timezones = timezones.New() - // Start email batching because it's not like the other jobs s.InitEmailBatching() s.AddConfigListener(func(_, _ *model.Config) { diff --git a/app/server_app_adapters.go b/app/server_app_adapters.go index 6e29d6fc1c..470f56b6e2 100644 --- a/app/server_app_adapters.go +++ b/app/server_app_adapters.go @@ -24,13 +24,12 @@ import ( // performed in the NewServer function. func (s *Server) RunOldAppInitialization() error { s.FakeApp().CreatePushNotificationsHub() - s.FakeApp().StartPushNotificationsHubWorkers() if err := utils.InitTranslations(s.FakeApp().Config().LocalizationSettings); err != nil { return errors.Wrapf(err, "unable to load Mattermost translation files") } - s.FakeApp().Srv.configListenerId = s.FakeApp().AddConfigListener(func(_, _ *model.Config) { + s.FakeApp().Srv().configListenerId = s.FakeApp().AddConfigListener(func(_, _ *model.Config) { s.FakeApp().configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil) @@ -40,7 +39,7 @@ func (s *Server) RunOldAppInitialization() error { s.FakeApp().Publish(message) }) }) - s.FakeApp().Srv.licenseListenerId = s.FakeApp().AddLicenseListener(func() { + s.FakeApp().Srv().licenseListenerId = s.FakeApp().AddLicenseListener(func() { s.FakeApp().configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil) @@ -57,10 +56,8 @@ func (s *Server) RunOldAppInitialization() error { mlog.Info("Server is initializing...") - s.initEnterprise() - - if s.FakeApp().Srv.newStore == nil { - s.FakeApp().Srv.newStore = func() store.Store { + if s.FakeApp().Srv().newStore == nil { + s.FakeApp().Srv().newStore = func() store.Store { return store.NewTimerLayer( localcachelayer.NewLocalCacheLayer( sqlstore.NewSqlSupplier(s.FakeApp().Config().SqlSettings, s.Metrics), @@ -72,10 +69,13 @@ func (s *Server) RunOldAppInitialization() error { if htmlTemplateWatcher, err := utils.NewHTMLTemplateWatcher("templates"); err != nil { mlog.Error("Failed to parse server templates", mlog.Err(err)) } else { - s.FakeApp().Srv.htmlTemplateWatcher = htmlTemplateWatcher + s.FakeApp().Srv().htmlTemplateWatcher = htmlTemplateWatcher } - s.FakeApp().Srv.Store = s.FakeApp().Srv.newStore() + s.FakeApp().Srv().Store = s.FakeApp().Srv().newStore() + s.FakeApp().StartPushNotificationsHubWorkers() + + s.initEnterprise() if err := s.FakeApp().ensureAsymmetricSigningKey(); err != nil { return errors.Wrapf(err, "unable to ensure asymmetric signing key") @@ -92,10 +92,10 @@ func (s *Server) RunOldAppInitialization() error { s.FakeApp().EnsureDiagnosticId() s.FakeApp().regenerateClientConfig() - s.FakeApp().Srv.clusterLeaderListenerId = s.FakeApp().Srv.AddClusterLeaderChangedListener(func() { + s.FakeApp().Srv().clusterLeaderListenerId = s.FakeApp().Srv().AddClusterLeaderChangedListener(func() { mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.FakeApp().IsLeader())) - if s.FakeApp().Srv.Jobs != nil { - s.FakeApp().Srv.Jobs.Schedulers.HandleClusterLeaderChange(s.FakeApp().IsLeader()) + if s.FakeApp().Srv().Jobs != nil { + s.FakeApp().Srv().Jobs.Schedulers.HandleClusterLeaderChange(s.FakeApp().IsLeader()) } }) @@ -103,22 +103,22 @@ func (s *Server) RunOldAppInitialization() error { if err != nil { return errors.Wrap(err, "failed to parse SiteURL subpath") } - s.FakeApp().Srv.Router = s.FakeApp().Srv.RootRouter.PathPrefix(subpath).Subrouter() - pluginsRoute := s.FakeApp().Srv.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() + s.FakeApp().Srv().Router = s.FakeApp().Srv().RootRouter.PathPrefix(subpath).Subrouter() + pluginsRoute := s.FakeApp().Srv().Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() pluginsRoute.HandleFunc("", s.FakeApp().ServePluginRequest) pluginsRoute.HandleFunc("/public/{public_file:.*}", s.FakeApp().ServePluginPublicRequest) pluginsRoute.HandleFunc("/{anything:.*}", s.FakeApp().ServePluginRequest) // If configured with a subpath, redirect 404s at the root back into the subpath. if subpath != "/" { - s.FakeApp().Srv.RootRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.FakeApp().Srv().RootRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.URL.Path = path.Join(subpath, r.URL.Path) http.Redirect(w, r, r.URL.String(), http.StatusFound) }) } - s.FakeApp().Srv.Router.NotFoundHandler = http.HandlerFunc(s.FakeApp().Handle404) + s.FakeApp().Srv().Router.NotFoundHandler = http.HandlerFunc(s.FakeApp().Handle404) - s.FakeApp().Srv.WebSocketRouter = &WebSocketRouter{ + s.FakeApp().Srv().WebSocketRouter = &WebSocketRouter{ app: s.FakeApp(), handlers: make(map[string]webSocketHandler), } diff --git a/app/session.go b/app/session.go index 511e71a3b1..41a5ad1a6f 100644 --- a/app/session.go +++ b/app/session.go @@ -13,7 +13,7 @@ import ( func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) { session.Token = "" - session, err := a.Srv.Store.Session().Save(session) + session, err := a.Srv().Store.Session().Save(session) if err != nil { return nil, err } @@ -24,11 +24,11 @@ func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppE } func (a *App) GetSession(token string) (*model.Session, *model.AppError) { - metrics := a.Metrics + metrics := a.Metrics() var session *model.Session var err *model.AppError - if ts, ok := a.Srv.sessionCache.Get(token); ok { + if ts, ok := a.Srv().sessionCache.Get(token); ok { session = ts.(*model.Session) if metrics != nil { metrics.IncrementMemCacheHitCounterSession() @@ -40,7 +40,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { } if session == nil { - if session, err = a.Srv.Store.Session().Get(token); err == nil { + if session, err = a.Srv().Store.Session().Get(token); err == nil { if session != nil { if session.Token != token { return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "", http.StatusUnauthorized) @@ -88,11 +88,11 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { func (a *App) GetSessions(userId string) ([]*model.Session, *model.AppError) { - return a.Srv.Store.Session().GetSessions(userId) + return a.Srv().Store.Session().GetSessions(userId) } func (a *App) UpdateSessionsIsGuest(userId string, isGuest bool) { - sessions, err := a.Srv.Store.Session().GetSessions(userId) + sessions, err := a.Srv().Store.Session().GetSessions(userId) if err != nil { mlog.Error("Unable to get user sessions", mlog.String("user_id", userId), mlog.Err(err)) } @@ -103,7 +103,7 @@ func (a *App) UpdateSessionsIsGuest(userId string, isGuest bool) { } else { session.AddProp(model.SESSION_PROP_IS_GUEST, "false") } - err := a.Srv.Store.Session().UpdateProps(session) + err := a.Srv().Store.Session().UpdateProps(session) if err != nil { mlog.Error("Unable to update isGuest session", mlog.Err(err)) continue @@ -113,7 +113,7 @@ func (a *App) UpdateSessionsIsGuest(userId string, isGuest bool) { } func (a *App) RevokeAllSessions(userId string) *model.AppError { - sessions, err := a.Srv.Store.Session().GetSessions(userId) + sessions, err := a.Srv().Store.Session().GetSessions(userId) if err != nil { return err } @@ -121,7 +121,7 @@ func (a *App) RevokeAllSessions(userId string) *model.AppError { if session.IsOAuth { a.RevokeAccessToken(session.Token) } else { - if err := a.Srv.Store.Session().Remove(session.Id); err != nil { + if err := a.Srv().Store.Session().Remove(session.Id); err != nil { return err } } @@ -136,11 +136,11 @@ func (a *App) RevokeAllSessions(userId string) *model.AppError { // in the server and revoke them func (a *App) RevokeSessionsFromAllUsers() *model.AppError { // revoke tokens before sessions so they can't be used to relogin - tErr := a.Srv.Store.OAuth().RemoveAllAccessData() + tErr := a.Srv().Store.OAuth().RemoveAllAccessData() if tErr != nil { return tErr } - err := a.Srv.Store.Session().RemoveAllSessions() + err := a.Srv().Store.Session().RemoveAllSessions() if err != nil { return err } @@ -152,38 +152,38 @@ func (a *App) RevokeSessionsFromAllUsers() *model.AppError { func (a *App) ClearSessionCacheForUser(userId string) { a.ClearSessionCacheForUserSkipClusterSend(userId) - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, SendType: model.CLUSTER_SEND_RELIABLE, Data: userId, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } func (a *App) ClearSessionCacheForAllUsers() { a.ClearSessionCacheForAllUsersSkipClusterSend() - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, SendType: model.CLUSTER_SEND_RELIABLE, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } func (a *App) ClearSessionCacheForUserSkipClusterSend(userId string) { - keys := a.Srv.sessionCache.Keys() + keys := a.Srv().sessionCache.Keys() for _, key := range keys { - if ts, ok := a.Srv.sessionCache.Get(key); ok { + if ts, ok := a.Srv().sessionCache.Get(key); ok { session := ts.(*model.Session) if session.UserId == userId { - a.Srv.sessionCache.Remove(key) - if a.Metrics != nil { - a.Metrics.IncrementMemCacheInvalidationCounterSession() + a.Srv().sessionCache.Remove(key) + if a.Metrics() != nil { + a.Metrics().IncrementMemCacheInvalidationCounterSession() } } } @@ -194,19 +194,19 @@ func (a *App) ClearSessionCacheForUserSkipClusterSend(userId string) { func (a *App) ClearSessionCacheForAllUsersSkipClusterSend() { mlog.Info("Purging sessions cache") - a.Srv.sessionCache.Purge() + a.Srv().sessionCache.Purge() } func (a *App) AddSessionToCache(session *model.Session) { - a.Srv.sessionCache.AddWithExpiresInSecs(session.Token, session, int64(*a.Config().ServiceSettings.SessionCacheInMinutes*60)) + a.Srv().sessionCache.AddWithExpiresInSecs(session.Token, session, int64(*a.Config().ServiceSettings.SessionCacheInMinutes*60)) } func (a *App) SessionCacheLength() int { - return a.Srv.sessionCache.Len() + return a.Srv().sessionCache.Len() } func (a *App) RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError { - sessions, err := a.Srv.Store.Session().GetSessions(userId) + sessions, err := a.Srv().Store.Session().GetSessions(userId) if err != nil { return err } @@ -224,7 +224,7 @@ func (a *App) RevokeSessionsForDeviceId(userId string, deviceId string, currentS } func (a *App) GetSessionById(sessionId string) (*model.Session, *model.AppError) { - session, err := a.Srv.Store.Session().Get(sessionId) + session, err := a.Srv().Store.Session().Get(sessionId) if err != nil { err.StatusCode = http.StatusBadRequest return nil, err @@ -233,7 +233,7 @@ func (a *App) GetSessionById(sessionId string) (*model.Session, *model.AppError) } func (a *App) RevokeSessionById(sessionId string) *model.AppError { - session, err := a.Srv.Store.Session().Get(sessionId) + session, err := a.Srv().Store.Session().Get(sessionId) if err != nil { err.StatusCode = http.StatusBadRequest return err @@ -248,7 +248,7 @@ func (a *App) RevokeSession(session *model.Session) *model.AppError { return err } } else { - if err := a.Srv.Store.Session().Remove(session.Id); err != nil { + if err := a.Srv().Store.Session().Remove(session.Id); err != nil { return err } } @@ -259,7 +259,7 @@ func (a *App) RevokeSession(session *model.Session) *model.AppError { } func (a *App) AttachDeviceId(sessionId string, deviceId string, expiresAt int64) *model.AppError { - _, err := a.Srv.Store.Session().UpdateDeviceId(sessionId, deviceId, expiresAt) + _, err := a.Srv().Store.Session().UpdateDeviceId(sessionId, deviceId, expiresAt) if err != nil { return err } @@ -276,7 +276,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { return } - if err := a.Srv.Store.Session().UpdateLastActivityAt(session.Id, now); err != nil { + if err := a.Srv().Store.Session().UpdateLastActivityAt(session.Id, now); err != nil { mlog.Error("Failed to update LastActivityAt", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Err(err)) } @@ -286,7 +286,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { - user, err := a.Srv.Store.User().Get(token.UserId) + user, err := a.Srv().Store.User().Get(token.UserId) if err != nil { return nil, err } @@ -297,7 +297,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc token.Token = model.NewId() - token, err = a.Srv.Store.UserAccessToken().Save(token) + token, err = a.Srv().Store.UserAccessToken().Save(token) if err != nil { return nil, err } @@ -305,7 +305,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc // Don't send emails to bot users. if !user.IsBot { if err := a.SendUserAccessTokenAddedEmail(user.Email, user.Locale, a.GetSiteURL()); err != nil { - a.Log.Error("Unable to send user access token added email", mlog.Err(err), mlog.String("user_id", user.Id)) + a.Log().Error("Unable to send user access token added email", mlog.Err(err), mlog.String("user_id", user.Id)) } } @@ -314,7 +314,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc } func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) { - token, err := a.Srv.Store.UserAccessToken().GetByToken(tokenString) + token, err := a.Srv().Store.UserAccessToken().GetByToken(tokenString) if err != nil { return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, err.Error(), http.StatusUnauthorized) } @@ -323,7 +323,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "inactive_token", http.StatusUnauthorized) } - user, err := a.Srv.Store.User().Get(token.UserId) + user, err := a.Srv().Store.User().Get(token.UserId) if err != nil { return nil, err } @@ -355,7 +355,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio } session.SetExpireInDays(model.SESSION_USER_ACCESS_TOKEN_EXPIRY) - session, err = a.Srv.Store.Session().Save(session) + session, err = a.Srv().Store.Session().Save(session) if err != nil { return nil, err } @@ -368,9 +368,9 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.Srv.Store.Session().Get(token.Token) + session, _ = a.Srv().Store.Session().Get(token.Token) - if err := a.Srv.Store.UserAccessToken().Delete(token.Id); err != nil { + if err := a.Srv().Store.UserAccessToken().Delete(token.Id); err != nil { return err } @@ -383,9 +383,9 @@ func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppErro func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.Srv.Store.Session().Get(token.Token) + session, _ = a.Srv().Store.Session().Get(token.Token) - if err := a.Srv.Store.UserAccessToken().UpdateTokenDisable(token.Id); err != nil { + if err := a.Srv().Store.UserAccessToken().UpdateTokenDisable(token.Id); err != nil { return err } @@ -398,9 +398,9 @@ func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppErr func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.Srv.Store.Session().Get(token.Token) + session, _ = a.Srv().Store.Session().Get(token.Token) - err := a.Srv.Store.UserAccessToken().UpdateTokenEnable(token.Id) + err := a.Srv().Store.UserAccessToken().UpdateTokenEnable(token.Id) if err != nil { return err } @@ -413,7 +413,7 @@ func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppErro } func (a *App) GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv.Store.UserAccessToken().GetAll(page*perPage, perPage) + tokens, err := a.Srv().Store.UserAccessToken().GetAll(page*perPage, perPage) if err != nil { return nil, err } @@ -426,7 +426,7 @@ func (a *App) GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, } func (a *App) GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv.Store.UserAccessToken().GetByUser(userId, page*perPage, perPage) + tokens, err := a.Srv().Store.UserAccessToken().GetByUser(userId, page*perPage, perPage) if err != nil { return nil, err } @@ -439,7 +439,7 @@ func (a *App) GetUserAccessTokensForUser(userId string, page, perPage int) ([]*m } func (a *App) GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAccessToken, *model.AppError) { - token, err := a.Srv.Store.UserAccessToken().Get(tokenId) + token, err := a.Srv().Store.UserAccessToken().Get(tokenId) if err != nil { return nil, err } @@ -451,7 +451,7 @@ func (a *App) GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAcce } func (a *App) SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv.Store.UserAccessToken().Search(term) + tokens, err := a.Srv().Store.UserAccessToken().Search(term) if err != nil { return nil, err } diff --git a/app/session_test.go b/app/session_test.go index 645605db3d..62f129f1d2 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -28,21 +28,21 @@ func TestCache(t *testing.T) { UserId: model.NewId(), } - th.App.Srv.sessionCache.AddWithExpiresInSecs(session.Token, session, 5*60) - th.App.Srv.sessionCache.AddWithExpiresInSecs(session2.Token, session2, 5*60) + th.App.Srv().sessionCache.AddWithExpiresInSecs(session.Token, session, 5*60) + th.App.Srv().sessionCache.AddWithExpiresInSecs(session2.Token, session2, 5*60) - keys := th.App.Srv.sessionCache.Keys() + keys := th.App.Srv().sessionCache.Keys() require.NotEmpty(t, keys) th.App.ClearSessionCacheForUser(session.UserId) - rkeys := th.App.Srv.sessionCache.Keys() + rkeys := th.App.Srv().sessionCache.Keys() require.Lenf(t, rkeys, len(keys)-1, "should have one less: %d - %d != 1", len(keys), len(rkeys)) require.NotEmpty(t, rkeys) th.App.ClearSessionCacheForAllUsers() - rkeys = th.App.Srv.sessionCache.Keys() + rkeys = th.App.Srv().sessionCache.Keys() require.Empty(t, rkeys) } @@ -65,7 +65,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { // Test regular session, should timeout time := session.LastActivityAt - (1000 * 60 * 6) - err = th.App.Srv.Store.Session().UpdateLastActivityAt(session.Id, time) + err = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) require.Nil(t, err) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -83,7 +83,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - err = th.App.Srv.Store.Session().UpdateLastActivityAt(session.Id, time) + err = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) require.Nil(t, err) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -98,7 +98,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - err = th.App.Srv.Store.Session().UpdateLastActivityAt(session.Id, time) + err = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) require.Nil(t, err) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -116,7 +116,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - err = th.App.Srv.Store.Session().UpdateLastActivityAt(session.Id, time) + err = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) require.Nil(t, err) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) diff --git a/app/slack.go b/app/slack.go index 61878c414b..d6b2d3948d 100644 --- a/app/slack.go +++ b/app/slack.go @@ -15,7 +15,7 @@ import ( func (a *App) ProcessSlackText(text string) string { text = expandAnnouncement(text) - text = replaceUserIds(a.Srv.Store.User(), text) + text = replaceUserIds(a.Srv().Store.User(), text) return text } diff --git a/app/slackimport.go b/app/slackimport.go index a8fb13d264..996aad4bd7 100644 --- a/app/slackimport.go +++ b/app/slackimport.go @@ -156,7 +156,7 @@ func (a *App) SlackAddUsers(teamId string, slackusers []SlackUser, importerLog * addedUsers := make(map[string]*model.User) // Need the team - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) if err != nil { importerLog.WriteString(utils.T("api.slackimport.slack_import.team_fail")) return addedUsers @@ -175,7 +175,7 @@ func (a *App) SlackAddUsers(teamId string, slackusers []SlackUser, importerLog * password := model.NewId() // Check for email conflict and use existing user if found - if existingUser, err := a.Srv.Store.User().GetByEmail(email); err == nil { + if existingUser, err := a.Srv().Store.User().GetByEmail(email); err == nil { addedUsers[sUser.Id] = existingUser if err := a.JoinUserToTeam(team, addedUsers[sUser.Id], ""); err != nil { importerLog.WriteString(utils.T("api.slackimport.slack_add_users.merge_existing_failed", map[string]interface{}{"Email": existingUser.Email, "Username": existingUser.Username})) @@ -207,7 +207,7 @@ func (a *App) SlackAddUsers(teamId string, slackusers []SlackUser, importerLog * } func (a *App) SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) if err != nil { log.WriteString(utils.T("api.slackimport.slack_import.team_fail")) return nil @@ -533,10 +533,10 @@ func (a *App) SlackAddChannels(teamId string, slackchannels []SlackChannel, post var mChannel *model.Channel var err *model.AppError - if mChannel, err = a.Srv.Store.Channel().GetByName(teamId, sChannel.Name, true); err == nil { + if mChannel, err = a.Srv().Store.Channel().GetByName(teamId, sChannel.Name, true); err == nil { // The channel already exists as an active channel. Merge with the existing one. importerLog.WriteString(utils.T("api.slackimport.slack_add_channels.merge", map[string]interface{}{"DisplayName": newChannel.DisplayName})) - } else if _, err := a.Srv.Store.Channel().GetDeletedByName(teamId, sChannel.Name); err == nil { + } else if _, err := a.Srv().Store.Channel().GetDeletedByName(teamId, sChannel.Name); err == nil { // The channel already exists but has been deleted. Generate a random string for the handle instead. newChannel.Name = model.NewId() newChannel = SlackSanitiseChannelProperties(newChannel) @@ -791,7 +791,7 @@ func (a *App) OldImportPost(post *model.Post) string { post.RootId = firstPostId post.ParentId = firstPostId - _, err := a.Srv.Store.Post().Save(post) + _, err := a.Srv().Store.Post().Save(post) if err != nil { mlog.Debug("Error saving post.", mlog.String("user_id", post.UserId), mlog.String("message", post.Message)) } @@ -801,7 +801,7 @@ func (a *App) OldImportPost(post *model.Post) string { firstPostId = post.Id } for _, fileId := range post.FileIds { - if err := a.Srv.Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId); err != nil { + if err := a.Srv().Store.FileInfo().AttachToPost(fileId, post.Id, post.UserId); err != nil { mlog.Error( "Error attaching files to post.", mlog.String("post_id", post.Id), @@ -827,13 +827,13 @@ func (a *App) OldImportUser(team *model.Team, user *model.User) *model.User { user.Roles = model.SYSTEM_USER_ROLE_ID - ruser, err := a.Srv.Store.User().Save(user) + ruser, err := a.Srv().Store.User().Save(user) if err != nil { mlog.Error("Error saving user.", mlog.Err(err)) return nil } - if _, err = a.Srv.Store.User().VerifyEmail(ruser.Id, ruser.Email); err != nil { + if _, err = a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email); err != nil { mlog.Error("Failed to set email verified.", mlog.Err(err)) } @@ -878,7 +878,7 @@ func (a *App) OldImportChannel(channel *model.Channel, sChannel SlackChannel, us return sc } - sc, err := a.Srv.Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) + sc, err := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) if err != nil { return nil } diff --git a/app/status.go b/app/status.go index bacd63cf80..c768523a0f 100644 --- a/app/status.go +++ b/app/status.go @@ -9,19 +9,19 @@ import ( ) func (a *App) AddStatusCacheSkipClusterSend(status *model.Status) { - a.Srv.statusCache.Add(status.UserId, status) + a.Srv().statusCache.Add(status.UserId, status) } func (a *App) AddStatusCache(status *model.Status) { a.AddStatusCacheSkipClusterSend(status) - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_UPDATE_STATUS, SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: status.ToClusterJson(), } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } @@ -30,7 +30,7 @@ func (a *App) GetAllStatuses() map[string]*model.Status { return map[string]*model.Status{} } - userIds := a.Srv.statusCache.Keys() + userIds := a.Srv().statusCache.Keys() statusMap := map[string]*model.Status{} for _, userId := range userIds { @@ -49,11 +49,11 @@ func (a *App) GetStatusesByIds(userIds []string) (map[string]interface{}, *model } statusMap := map[string]interface{}{} - metrics := a.Metrics + metrics := a.Metrics() missingUserIds := []string{} for _, userId := range userIds { - if result, ok := a.Srv.statusCache.Get(userId); ok { + if result, ok := a.Srv().statusCache.Get(userId); ok { statusMap[userId] = result.(*model.Status).Status if metrics != nil { metrics.IncrementMemCacheHitCounter("Status") @@ -67,7 +67,7 @@ func (a *App) GetStatusesByIds(userIds []string) (map[string]interface{}, *model } if len(missingUserIds) > 0 { - statuses, err := a.Srv.Store.Status().GetByIds(missingUserIds) + statuses, err := a.Srv().Store.Status().GetByIds(missingUserIds) if err != nil { return nil, err } @@ -96,11 +96,11 @@ func (a *App) GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.Ap } var statusMap []*model.Status - metrics := a.Metrics + metrics := a.Metrics() missingUserIds := []string{} for _, userId := range userIds { - if result, ok := a.Srv.statusCache.Get(userId); ok { + if result, ok := a.Srv().statusCache.Get(userId); ok { statusMap = append(statusMap, result.(*model.Status)) if metrics != nil { metrics.IncrementMemCacheHitCounter("Status") @@ -114,7 +114,7 @@ func (a *App) GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.Ap } if len(missingUserIds) > 0 { - statuses, err := a.Srv.Store.Status().GetByIds(missingUserIds) + statuses, err := a.Srv().Store.Status().GetByIds(missingUserIds) if err != nil { return nil, err } @@ -203,11 +203,11 @@ func (a *App) SetStatusOnline(userId string, manual bool) { // or enough time has passed since the previous action if status.Status != oldStatus || status.Manual != oldManual || status.LastActivityAt-oldTime > model.STATUS_MIN_UPDATE_TIME { if broadcast { - if err := a.Srv.Store.Status().SaveOrUpdate(status); err != nil { + if err := a.Srv().Store.Status().SaveOrUpdate(status); err != nil { mlog.Error("Failed to save status", mlog.String("user_id", userId), mlog.Err(err), mlog.String("user_id", userId)) } } else { - if err := a.Srv.Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt); err != nil { + if err := a.Srv().Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt); err != nil { mlog.Error("Failed to save status", mlog.String("user_id", userId), mlog.Err(err), mlog.String("user_id", userId)) } } @@ -219,7 +219,7 @@ func (a *App) SetStatusOnline(userId string, manual bool) { } func (a *App) BroadcastStatus(status *model.Status) { - if a.Srv.Busy.IsBusy() { + if a.Srv().Busy.IsBusy() { // this is considered a non-critical service and will be disabled when server busy. return } @@ -296,7 +296,7 @@ func (a *App) SetStatusDoNotDisturb(userId string) { func (a *App) SaveAndBroadcastStatus(status *model.Status) { a.AddStatusCache(status) - if err := a.Srv.Store.Status().SaveOrUpdate(status); err != nil { + if err := a.Srv().Store.Status().SaveOrUpdate(status); err != nil { mlog.Error("Failed to save status", mlog.String("user_id", status.UserId), mlog.Err(err)) } @@ -321,7 +321,7 @@ func (a *App) SetStatusOutOfOffice(userId string) { } func (a *App) GetStatusFromCache(userId string) *model.Status { - if result, ok := a.Srv.statusCache.Get(userId); ok { + if result, ok := a.Srv().statusCache.Get(userId); ok { status := result.(*model.Status) statusCopy := &model.Status{} *statusCopy = *status @@ -341,7 +341,7 @@ func (a *App) GetStatus(userId string) (*model.Status, *model.AppError) { return status, nil } - return a.Srv.Store.Status().Get(userId) + return a.Srv().Store.Status().Get(userId) } func (a *App) IsUserAway(lastActivityAt int64) bool { diff --git a/app/syncables.go b/app/syncables.go index 53a21e37f4..631e92a722 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -38,7 +38,7 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string) er if err != nil { return err } - a.Log.Info("added teammember", + a.Log().Info("added teammember", mlog.String("user_id", userChannel.UserID), mlog.String("team_id", channel.TeamId), ) @@ -47,7 +47,7 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string) er _, err = a.AddChannelMember(userChannel.UserID, channel, "", "") if err != nil { if err.Id == "api.channel.add_user.to.channel.failed.deleted.app_error" { - a.Log.Info("Not adding user to channel because they have already left the team", + a.Log().Info("Not adding user to channel because they have already left the team", mlog.String("user_id", userChannel.UserID), mlog.String("channel_id", userChannel.ChannelID), ) @@ -56,7 +56,7 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string) er } } - a.Log.Info("added channelmember", + a.Log().Info("added channelmember", mlog.String("user_id", userChannel.UserID), mlog.String("channel_id", userChannel.ChannelID), ) @@ -80,7 +80,7 @@ func (a *App) createDefaultTeamMemberships(since int64, teamID *string) error { return err } - a.Log.Info("added teammember", + a.Log().Info("added teammember", mlog.String("user_id", userTeam.UserID), mlog.String("team_id", userTeam.TeamID), ) @@ -136,7 +136,7 @@ func (a *App) deleteGroupConstrainedTeamMemberships(teamID *string) error { return err } - a.Log.Info("removed teammember", + a.Log().Info("removed teammember", mlog.String("user_id", userTeam.UserId), mlog.String("team_id", userTeam.TeamId), ) @@ -165,7 +165,7 @@ func (a *App) deleteGroupConstrainedChannelMemberships(channelID *string) error return err } - a.Log.Info("removed channelmember", + a.Log().Info("removed channelmember", mlog.String("user_id", userChannel.UserId), mlog.String("channel_id", channel.Id), ) @@ -178,12 +178,12 @@ func (a *App) deleteGroupConstrainedChannelMemberships(channelID *string) error // the member's group memberships and the configuration of those groups to the syncable. This method should only // be invoked on group-synced (aka group-constrained) syncables. func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSyncableType) *model.AppError { - permittedAdmins, err := a.Srv.Store.Group().PermittedSyncableAdmins(syncableID, syncableType) + permittedAdmins, err := a.Srv().Store.Group().PermittedSyncableAdmins(syncableID, syncableType) if err != nil { return err } - a.Log.Info( + a.Log().Info( fmt.Sprintf("Permitted admins for %s", syncableType), mlog.String(strings.ToLower(fmt.Sprintf("%s_id", syncableType)), syncableID), mlog.Any("permitted_admins", permittedAdmins), @@ -193,9 +193,9 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca switch syncableType { case model.GroupSyncableTypeTeam: - updateFunc = a.Srv.Store.Team().UpdateMembersRole + updateFunc = a.Srv().Store.Team().UpdateMembersRole case model.GroupSyncableTypeChannel: - updateFunc = a.Srv.Store.Channel().UpdateMembersRole + updateFunc = a.Srv().Store.Channel().UpdateMembersRole default: return model.NewAppError("App.SyncSyncableRoles", "groups.unsupported_syncable_type", map[string]interface{}{"Value": syncableType}, "", http.StatusInternalServerError) } @@ -213,7 +213,7 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca func (a *App) SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType) { a.SyncSyncableRoles(syncableID, syncableType) - lastJob, _ := a.Srv.Store.Job().GetNewestJobByStatusAndType(model.JOB_STATUS_SUCCESS, model.JOB_TYPE_LDAP_SYNC) + lastJob, _ := a.Srv().Store.Job().GetNewestJobByStatusAndType(model.JOB_STATUS_SUCCESS, model.JOB_TYPE_LDAP_SYNC) var since int64 if lastJob != nil { since = lastJob.StartAt diff --git a/app/syncables_test.go b/app/syncables_test.go index 69522726c6..ca177efbc8 100644 --- a/app/syncables_test.go +++ b/app/syncables_test.go @@ -297,7 +297,7 @@ func TestCreateDefaultMemberships(t *testing.T) { timeAfterLeaving := model.GetMillis() // Purging channelmemberhistory doesn't re-add user to channel - _, err = th.App.Srv.Store.ChannelMemberHistory().PermanentDeleteBatch(timeBeforeLeaving, 1000) + _, err = th.App.Srv().Store.ChannelMemberHistory().PermanentDeleteBatch(timeBeforeLeaving, 1000) if err != nil { t.Errorf("error permanently deleting channelmemberhistory: %s", err.Error()) } @@ -313,7 +313,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Purging channelmemberhistory doesn't re-add user to channel - _, err = th.App.Srv.Jobs.Store.ChannelMemberHistory().PermanentDeleteBatch(timeAfterLeaving, 1000) + _, err = th.App.Srv().Jobs.Store.ChannelMemberHistory().PermanentDeleteBatch(timeAfterLeaving, 1000) if err != nil { t.Errorf("error permanently deleting channelmemberhistory: %s", err.Error()) } diff --git a/app/team.go b/app/team.go index cacbf0a57d..d19faad8ba 100644 --- a/app/team.go +++ b/app/team.go @@ -24,7 +24,7 @@ import ( func (a *App) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { team.InviteId = "" - rteam, err := a.Srv.Store.Team().Save(team) + rteam, err := a.Srv().Store.Team().Save(team) if err != nil { return nil, err } @@ -145,7 +145,7 @@ func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { } func (a *App) updateTeamUnsanitized(team *model.Team) (*model.Team, *model.AppError) { - return a.Srv.Store.Team().Update(team) + return a.Srv().Store.Team().Update(team) } // RenameTeam is used to rename the team Name and the DisplayName fields @@ -184,7 +184,7 @@ func (a *App) UpdateTeamScheme(team *model.Team) (*model.Team, *model.AppError) oldTeam.SchemeId = team.SchemeId - if oldTeam, err = a.Srv.Store.Team().Update(oldTeam); err != nil { + if oldTeam, err = a.Srv().Store.Team().Update(oldTeam); err != nil { return nil, err } @@ -202,7 +202,7 @@ func (a *App) UpdateTeamPrivacy(teamId string, teamType string, allowOpenInvite oldTeam.Type = teamType oldTeam.AllowOpenInvite = allowOpenInvite - if oldTeam, err = a.Srv.Store.Team().Update(oldTeam); err != nil { + if oldTeam, err = a.Srv().Store.Team().Update(oldTeam); err != nil { return err } @@ -237,7 +237,7 @@ func (a *App) RegenerateTeamInviteId(teamId string) (*model.Team, *model.AppErro team.InviteId = model.NewId() - updatedTeam, err := a.Srv.Store.Team().Update(team) + updatedTeam, err := a.Srv().Store.Team().Update(team) if err != nil { return nil, err } @@ -280,7 +280,7 @@ func (a *App) GetSchemeRolesForTeam(teamId string) (string, string, string, *mod } func (a *App) UpdateTeamMemberRoles(teamId string, userId string, newRoles string) (*model.TeamMember, *model.AppError) { - member, err := a.Srv.Store.Team().GetMember(teamId, userId) + member, err := a.Srv().Store.Team().GetMember(teamId, userId) if err != nil { return nil, err } @@ -338,7 +338,7 @@ func (a *App) UpdateTeamMemberRoles(teamId string, userId string, newRoles strin member.ExplicitRoles = strings.Join(newExplicitRoles, " ") - member, err = a.Srv.Store.Team().UpdateMember(member) + member, err = a.Srv().Store.Team().UpdateMember(member) if err != nil { return nil, err } @@ -369,7 +369,7 @@ func (a *App) UpdateTeamMemberSchemeRoles(teamId string, userId string, isScheme member.ExplicitRoles = RemoveRoles([]string{model.TEAM_GUEST_ROLE_ID, model.TEAM_USER_ROLE_ID, model.TEAM_ADMIN_ROLE_ID}, member.ExplicitRoles) } - member, err = a.Srv.Store.Team().UpdateMember(member) + member, err = a.Srv().Store.Team().UpdateMember(member) if err != nil { return nil, err } @@ -390,14 +390,14 @@ func (a *App) sendUpdatedMemberRoleEvent(userId string, member *model.TeamMember func (a *App) AddUserToTeam(teamId string, userId string, userRequestorId string) (*model.Team, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -422,7 +422,7 @@ func (a *App) AddUserToTeam(teamId string, userId string, userRequestorId string } func (a *App) AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) if err != nil { return err } @@ -431,7 +431,7 @@ func (a *App) AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppE } func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, *model.AppError) { - token, err := a.Srv.Store.Token().GetByToken(tokenId) + token, err := a.Srv().Store.Token().GetByToken(tokenId) if err != nil { return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -449,14 +449,14 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(tokenData["teamId"]) + team, err := a.Srv().Store.Team().Get(tokenData["teamId"]) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -489,7 +489,7 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, } if token.Type == TOKEN_TYPE_GUEST_INVITATION { - channels, err := a.Srv.Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " ")) + channels, err := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " ")) if err != nil { return nil, err } @@ -512,14 +512,14 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, func (a *App) AddUserToTeamByInviteId(inviteId string, userId string) (*model.Team, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store.Team().GetByInviteId(inviteId) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -567,11 +567,11 @@ func (a *App) joinUserToTeam(team *model.Team, user *model.User) (*model.TeamMem tm.SchemeAdmin = true } - rtm, err := a.Srv.Store.Team().GetMember(team.Id, user.Id) + rtm, err := a.Srv().Store.Team().GetMember(team.Id, user.Id) if err != nil { // Membership appears to be missing. Lets try to add. var tmr *model.TeamMember - tmr, err = a.Srv.Store.Team().SaveMember(tm, *a.Config().TeamSettings.MaxUsersPerTeam) + tmr, err = a.Srv().Store.Team().SaveMember(tm, *a.Config().TeamSettings.MaxUsersPerTeam) if err != nil { return nil, false, err } @@ -584,7 +584,7 @@ func (a *App) joinUserToTeam(team *model.Team, user *model.User) (*model.TeamMem return rtm, true, nil } - membersCount, err := a.Srv.Store.Team().GetActiveMemberCount(tm.TeamId, nil) + membersCount, err := a.Srv().Store.Team().GetActiveMemberCount(tm.TeamId, nil) if err != nil { return nil, false, err } @@ -593,7 +593,7 @@ func (a *App) joinUserToTeam(team *model.Team, user *model.User) (*model.TeamMem return nil, false, model.NewAppError("joinUserToTeam", "app.team.join_user_to_team.max_accounts.app_error", nil, "teamId="+tm.TeamId, http.StatusBadRequest) } - member, err := a.Srv.Store.Team().UpdateMember(tm) + member, err := a.Srv().Store.Team().UpdateMember(tm) if err != nil { return nil, false, err } @@ -619,7 +619,7 @@ func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId actor, _ = a.GetUser(userRequestorId) } - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedTeam(pluginContext, tm, actor) @@ -628,7 +628,7 @@ func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId }) } - if _, err := a.Srv.Store.User().UpdateUpdateAt(user.Id); err != nil { + if _, err := a.Srv().Store.User().UpdateUpdateAt(user.Id); err != nil { return err } @@ -659,31 +659,31 @@ func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId } func (a *App) GetTeam(teamId string) (*model.Team, *model.AppError) { - return a.Srv.Store.Team().Get(teamId) + return a.Srv().Store.Team().Get(teamId) } func (a *App) GetTeamByName(name string) (*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetByName(name) + return a.Srv().Store.Team().GetByName(name) } func (a *App) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetByInviteId(inviteId) + return a.Srv().Store.Team().GetByInviteId(inviteId) } func (a *App) GetAllTeams() ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAll() + return a.Srv().Store.Team().GetAll() } func (a *App) GetAllTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAllPage(offset, limit) + return a.Srv().Store.Team().GetAllPage(offset, limit) } func (a *App) GetAllTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) { - totalCount, err := a.Srv.Store.Team().AnalyticsTeamCount(true) + totalCount, err := a.Srv().Store.Team().AnalyticsTeamCount(true) if err != nil { return nil, err } - teams, err := a.Srv.Store.Team().GetAllPage(offset, limit) + teams, err := a.Srv().Store.Team().GetAllPage(offset, limit) if err != nil { return nil, err } @@ -691,19 +691,19 @@ func (a *App) GetAllTeamsPageWithCount(offset int, limit int) (*model.TeamsWithC } func (a *App) GetAllPrivateTeams() ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAllPrivateTeamListing() + return a.Srv().Store.Team().GetAllPrivateTeamListing() } func (a *App) GetAllPrivateTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAllPrivateTeamPageListing(offset, limit) + return a.Srv().Store.Team().GetAllPrivateTeamPageListing(offset, limit) } func (a *App) GetAllPrivateTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) { - totalCount, err := a.Srv.Store.Team().AnalyticsPrivateTeamCount() + totalCount, err := a.Srv().Store.Team().AnalyticsPrivateTeamCount() if err != nil { return nil, err } - teams, err := a.Srv.Store.Team().GetAllPrivateTeamPageListing(offset, limit) + teams, err := a.Srv().Store.Team().GetAllPrivateTeamPageListing(offset, limit) if err != nil { return nil, err } @@ -711,19 +711,19 @@ func (a *App) GetAllPrivateTeamsPageWithCount(offset int, limit int) (*model.Tea } func (a *App) GetAllPublicTeams() ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAllTeamListing() + return a.Srv().Store.Team().GetAllTeamListing() } func (a *App) GetAllPublicTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetAllTeamPageListing(offset, limit) + return a.Srv().Store.Team().GetAllTeamPageListing(offset, limit) } func (a *App) GetAllPublicTeamsPageWithCount(offset int, limit int) (*model.TeamsWithCount, *model.AppError) { - totalCount, err := a.Srv.Store.Team().AnalyticsPublicTeamCount() + totalCount, err := a.Srv().Store.Team().AnalyticsPublicTeamCount() if err != nil { return nil, err } - teams, err := a.Srv.Store.Team().GetAllPublicTeamPageListing(offset, limit) + teams, err := a.Srv().Store.Team().GetAllPublicTeamPageListing(offset, limit) if err != nil { return nil, err } @@ -733,42 +733,42 @@ func (a *App) GetAllPublicTeamsPageWithCount(offset int, limit int) (*model.Team // SearchAllTeams returns a team list and the total count of the results func (a *App) SearchAllTeams(searchOpts *model.TeamSearch) ([]*model.Team, int64, *model.AppError) { if searchOpts.IsPaginated() { - return a.Srv.Store.Team().SearchAllPaged(searchOpts.Term, *searchOpts.Page, *searchOpts.PerPage) + return a.Srv().Store.Team().SearchAllPaged(searchOpts.Term, *searchOpts.Page, *searchOpts.PerPage) } - results, err := a.Srv.Store.Team().SearchAll(searchOpts.Term) + results, err := a.Srv().Store.Team().SearchAll(searchOpts.Term) return results, int64(len(results)), err } func (a *App) SearchPublicTeams(term string) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().SearchOpen(term) + return a.Srv().Store.Team().SearchOpen(term) } func (a *App) SearchPrivateTeams(term string) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().SearchPrivate(term) + return a.Srv().Store.Team().SearchPrivate(term) } func (a *App) GetTeamsForUser(userId string) ([]*model.Team, *model.AppError) { - return a.Srv.Store.Team().GetTeamsByUserId(userId) + return a.Srv().Store.Team().GetTeamsByUserId(userId) } func (a *App) GetTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { - return a.Srv.Store.Team().GetMember(teamId, userId) + return a.Srv().Store.Team().GetMember(teamId, userId) } func (a *App) GetTeamMembersForUser(userId string) ([]*model.TeamMember, *model.AppError) { - return a.Srv.Store.Team().GetTeamsForUser(userId) + return a.Srv().Store.Team().GetTeamsForUser(userId) } func (a *App) GetTeamMembersForUserWithPagination(userId string, page, perPage int) ([]*model.TeamMember, *model.AppError) { - return a.Srv.Store.Team().GetTeamsForUserWithPagination(userId, page, perPage) + return a.Srv().Store.Team().GetTeamsForUserWithPagination(userId, page, perPage) } func (a *App) GetTeamMembers(teamId string, offset int, limit int, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, *model.AppError) { - return a.Srv.Store.Team().GetMembers(teamId, offset, limit, restrictions) + return a.Srv().Store.Team().GetMembers(teamId, offset, limit, restrictions) } func (a *App) GetTeamMembersByIds(teamId string, userIds []string, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, *model.AppError) { - return a.Srv.Store.Team().GetMembersByIds(teamId, userIds, restrictions) + return a.Srv().Store.Team().GetMembersByIds(teamId, userIds, restrictions) } func (a *App) AddTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { @@ -854,7 +854,7 @@ func (a *App) AddTeamMemberByInviteId(inviteId, userId string) (*model.TeamMembe } func (a *App) GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.AppError) { - channelUnreads, err := a.Srv.Store.Team().GetChannelUnreadsForTeam(teamId, userId) + channelUnreads, err := a.Srv().Store.Team().GetChannelUnreadsForTeam(teamId, userId) if err != nil { return nil, err } @@ -879,14 +879,14 @@ func (a *App) GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.Ap func (a *App) RemoveUserFromTeam(teamId string, userId string, requestorId string) *model.AppError { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -917,7 +917,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId message.Add("team_id", teamMember.TeamId) a.Publish(message) - user, err := a.Srv.Store.User().Get(teamMember.UserId) + user, err := a.Srv().Store.User().Get(teamMember.UserId) if err != nil { return err } @@ -925,7 +925,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId teamMember.Roles = "" teamMember.DeleteAt = model.GetMillis() - if _, err := a.Srv.Store.Team().UpdateMember(teamMember); err != nil { + if _, err := a.Srv().Store.Team().UpdateMember(teamMember); err != nil { return err } @@ -935,7 +935,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId actor, _ = a.GetUser(requestorId) } - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLeftTeam(pluginContext, teamMember, actor) @@ -944,21 +944,21 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId }) } - esInterface := a.Elasticsearch + esInterface := a.Elasticsearch() if esInterface != nil && *a.Config().ElasticsearchSettings.EnableIndexing { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } }) } - if _, err := a.Srv.Store.User().UpdateUpdateAt(user.Id); err != nil { + if _, err := a.Srv().Store.User().UpdateUpdateAt(user.Id); err != nil { return err } // delete the preferences that set the last channel used in the team and other team specific preferences - if err := a.Srv.Store.Preference().DeleteCategory(user.Id, teamMember.TeamId); err != nil { + if err := a.Srv().Store.Preference().DeleteCategory(user.Id, teamMember.TeamId); err != nil { return err } @@ -977,7 +977,7 @@ func (a *App) LeaveTeam(team *model.Team, user *model.User, requestorId string) var channelList *model.ChannelList - if channelList, err = a.Srv.Store.Channel().GetChannels(team.Id, user.Id, true); err != nil { + if channelList, err = a.Srv().Store.Channel().GetChannels(team.Id, user.Id, true); err != nil { if err.Id == "store.sql_channel.get_channels.not_found.app_error" { channelList = &model.ChannelList{} } else { @@ -988,13 +988,13 @@ func (a *App) LeaveTeam(team *model.Team, user *model.User, requestorId string) for _, channel := range *channelList { if !channel.IsGroupOrDirect() { a.InvalidateCacheForChannelMembers(channel.Id) - if err = a.Srv.Store.Channel().RemoveMember(channel.Id, user.Id); err != nil { + if err = a.Srv().Store.Channel().RemoveMember(channel.Id, user.Id); err != nil { return err } } } - channel, err := a.Srv.Store.Channel().GetByName(team.Id, model.DEFAULT_CHANNEL, false) + channel, err := a.Srv().Store.Channel().GetByName(team.Id, model.DEFAULT_CHANNEL, false) if err != nil { return err } @@ -1058,14 +1058,14 @@ func (a *App) postRemoveFromTeamMessage(user *model.User, channel *model.Channel func (a *App) prepareInviteNewUsersToTeam(teamId, senderId string) (*model.User, *model.Team, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(senderId) + user, err := a.Srv().Store.User().Get(senderId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -1129,19 +1129,19 @@ func (a *App) prepareInviteGuestsToChannels(teamId string, guestsInvite *model.G tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv.Store.Team().Get(teamId) + team, err := a.Srv().Store.Team().Get(teamId) tchan <- store.StoreResult{Data: team, Err: err} close(tchan) }() cchan := make(chan store.StoreResult, 1) go func() { - channels, err := a.Srv.Store.Channel().GetChannelsByIds(guestsInvite.Channels) + channels, err := a.Srv().Store.Channel().GetChannelsByIds(guestsInvite.Channels) cchan <- store.StoreResult{Data: channels, Err: err} close(cchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(senderId) + user, err := a.Srv().Store.User().Get(senderId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -1271,14 +1271,14 @@ func (a *App) InviteGuestsToChannels(teamId string, guestsInvite *model.GuestsIn } func (a *App) FindTeamByName(name string) bool { - if _, err := a.Srv.Store.Team().GetByName(name); err != nil { + if _, err := a.Srv().Store.Team().GetByName(name); err != nil { return false } return true } func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userId string) ([]*model.TeamUnread, *model.AppError) { - data, err := a.Srv.Store.Team().GetChannelUnreadsForAllTeams(excludeTeamId, userId) + data, err := a.Srv().Store.Team().GetChannelUnreadsForAllTeams(excludeTeamId, userId) if err != nil { return nil, err } @@ -1326,11 +1326,11 @@ func (a *App) PermanentDeleteTeamId(teamId string) *model.AppError { func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { team.DeleteAt = model.GetMillis() - if _, err := a.Srv.Store.Team().Update(team); err != nil { + if _, err := a.Srv().Store.Team().Update(team); err != nil { return err } - if channels, err := a.Srv.Store.Channel().GetTeamChannels(team.Id); err != nil { + if channels, err := a.Srv().Store.Channel().GetTeamChannels(team.Id); err != nil { if err.Id != "store.sql_channel.get_channels.not_found.app_error" { return err } @@ -1340,15 +1340,15 @@ func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { } } - if err := a.Srv.Store.Team().RemoveAllMembersByTeam(team.Id); err != nil { + if err := a.Srv().Store.Team().RemoveAllMembersByTeam(team.Id); err != nil { return err } - if err := a.Srv.Store.Command().PermanentDeleteByTeam(team.Id); err != nil { + if err := a.Srv().Store.Command().PermanentDeleteByTeam(team.Id); err != nil { return err } - if err := a.Srv.Store.Team().PermanentDelete(team.Id); err != nil { + if err := a.Srv().Store.Team().PermanentDelete(team.Id); err != nil { return err } @@ -1364,7 +1364,7 @@ func (a *App) SoftDeleteTeam(teamId string) *model.AppError { } team.DeleteAt = model.GetMillis() - if team, err = a.Srv.Store.Team().Update(team); err != nil { + if team, err = a.Srv().Store.Team().Update(team); err != nil { return err } @@ -1380,7 +1380,7 @@ func (a *App) RestoreTeam(teamId string) *model.AppError { } team.DeleteAt = 0 - if team, err = a.Srv.Store.Team().Update(team); err != nil { + if team, err = a.Srv().Store.Team().Update(team); err != nil { return err } @@ -1391,13 +1391,13 @@ func (a *App) RestoreTeam(teamId string) *model.AppError { func (a *App) GetTeamStats(teamId string, restrictions *model.ViewUsersRestrictions) (*model.TeamStats, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - totalMemberCount, err := a.Srv.Store.Team().GetTotalMemberCount(teamId, restrictions) + totalMemberCount, err := a.Srv().Store.Team().GetTotalMemberCount(teamId, restrictions) tchan <- store.StoreResult{Data: totalMemberCount, Err: err} close(tchan) }() achan := make(chan store.StoreResult, 1) go func() { - memberCount, err := a.Srv.Store.Team().GetActiveMemberCount(teamId, restrictions) + memberCount, err := a.Srv().Store.Team().GetActiveMemberCount(teamId, restrictions) achan <- store.StoreResult{Data: memberCount, Err: err} close(achan) }() @@ -1425,7 +1425,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { inviteId := query.Get("id") if len(tokenId) > 0 { - token, err := a.Srv.Store.Token().GetByToken(tokenId) + token, err := a.Srv().Store.Token().GetByToken(tokenId) if err != nil { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) } @@ -1444,7 +1444,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { return tokenData["teamId"], nil } if len(inviteId) > 0 { - team, err := a.Srv.Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store.Team().GetByInviteId(inviteId) if err == nil { return team.Id, nil } @@ -1556,7 +1556,7 @@ func (a *App) SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppEr curTime := model.GetMillis() - if err := a.Srv.Store.Team().UpdateLastTeamIconUpdate(team.Id, curTime); err != nil { + if err := a.Srv().Store.Team().UpdateLastTeamIconUpdate(team.Id, curTime); err != nil { return model.NewAppError("SetTeamIcon", "api.team.team_icon.update.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -1574,7 +1574,7 @@ func (a *App) RemoveTeamIcon(teamId string) *model.AppError { return model.NewAppError("RemoveTeamIcon", "api.team.remove_team_icon.get_team.app_error", nil, err.Error(), http.StatusBadRequest) } - if err := a.Srv.Store.Team().UpdateLastTeamIconUpdate(teamId, 0); err != nil { + if err := a.Srv().Store.Team().UpdateLastTeamIconUpdate(teamId, 0); err != nil { return model.NewAppError("RemoveTeamIcon", "api.team.team_icon.update.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -1586,10 +1586,10 @@ func (a *App) RemoveTeamIcon(teamId string) *model.AppError { } func (a *App) InvalidateAllEmailInvites() *model.AppError { - if err := a.Srv.Store.Token().RemoveAllTokensByType(TOKEN_TYPE_TEAM_INVITATION); err != nil { + if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_TEAM_INVITATION); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest) } - if err := a.Srv.Store.Token().RemoveAllTokensByType(TOKEN_TYPE_GUEST_INVITATION); err != nil { + if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_GUEST_INVITATION); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest) } return nil @@ -1600,9 +1600,9 @@ func (a *App) ClearTeamMembersCache(teamID string) { page := 0 for { - teamMembers, err := a.Srv.Store.Team().GetMembers(teamID, page, perPage, &model.ViewUsersRestrictions{}) + teamMembers, err := a.Srv().Store.Team().GetMembers(teamID, page, perPage, &model.ViewUsersRestrictions{}) if err != nil { - a.Log.Warn("error clearing cache for team members", mlog.String("team_id", teamID)) + a.Log().Warn("error clearing cache for team members", mlog.String("team_id", teamID)) break } diff --git a/app/team_test.go b/app/team_test.go index f7d2de833e..1ee25c0f78 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -187,7 +187,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) @@ -201,7 +201,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1 - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) @@ -213,7 +213,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": model.NewId()}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) @@ -225,7 +225,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.AddUserToTeamByToken(model.NewId(), token.Token) @@ -237,11 +237,11 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) require.Nil(t, err, "Should add user to the team") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, ruser.Id) @@ -254,7 +254,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) assert.NotNil(t, err) }) @@ -264,7 +264,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) assert.NotNil(t, err) }) @@ -279,7 +279,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) require.NotNil(t, err) assert.Equal(t, "api.team.join_user_to_team.allowed_domains.app_error", err.Id) @@ -297,13 +297,13 @@ func TestAddUserToTeamByToken(t *testing.T) { ) guestEmail := rguest.Email rguest.Email = "test@restricted.com" - _, err := th.App.Srv.Store.User().Update(rguest, false) + _, err := th.App.Srv().Store.User().Update(rguest, false) require.Nil(t, err) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err = th.App.AddUserToTeamByToken(rguest.Id, token.Token) require.Nil(t, err) rguest.Email = guestEmail - _, err = th.App.Srv.Store.User().Update(rguest, false) + _, err = th.App.Srv().Store.User().Update(rguest, false) require.Nil(t, err) }) @@ -320,9 +320,9 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - _, err = th.App.Srv.Store.User().Update(rguest, false) + _, err = th.App.Srv().Store.User().Update(rguest, false) require.Nil(t, err) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err = th.App.AddUserToTeamByToken(rguest.Id, token.Token) require.Nil(t, err) th.BasicTeam.AllowedDomains = "" @@ -335,12 +335,12 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) require.Nil(t, err, "Should add user to the team") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, rguest.Id) @@ -358,7 +358,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err = th.App.AddUserToTeamByToken(ruser.Id, token.Token) require.NotNil(t, err, "Should return an error when trying to join a group-constrained team.") @@ -382,7 +382,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) _, err = th.App.AddUserToTeamByToken(ruser.Id, token.Token) require.NotNil(t, err, "Should not add restricted user") @@ -1000,7 +1000,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: TOKEN_TYPE_GUEST_INVITATION, Extra: "", } - err := th.App.Srv.Store.Token().Save(&t1) + err := th.App.Srv().Store.Token().Save(&t1) require.Nil(t, err) t2 := model.Token{ @@ -1009,7 +1009,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: TOKEN_TYPE_TEAM_INVITATION, Extra: "", } - err = th.App.Srv.Store.Token().Save(&t2) + err = th.App.Srv().Store.Token().Save(&t2) require.Nil(t, err) t3 := model.Token{ @@ -1018,18 +1018,18 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: "other", Extra: "", } - err = th.App.Srv.Store.Token().Save(&t3) + err = th.App.Srv().Store.Token().Save(&t3) require.Nil(t, err) err = th.App.InvalidateAllEmailInvites() require.Nil(t, err) - _, err = th.App.Srv.Store.Token().GetByToken(t1.Token) + _, err = th.App.Srv().Store.Token().GetByToken(t1.Token) require.NotNil(t, err) - _, err = th.App.Srv.Store.Token().GetByToken(t2.Token) + _, err = th.App.Srv().Store.Token().GetByToken(t2.Token) require.NotNil(t, err) - _, err = th.App.Srv.Store.Token().GetByToken(t3.Token) + _, err = th.App.Srv().Store.Token().GetByToken(t3.Token) require.Nil(t, err) } diff --git a/app/terms_of_service.go b/app/terms_of_service.go index 0dcf4c3365..529dd03c43 100644 --- a/app/terms_of_service.go +++ b/app/terms_of_service.go @@ -17,13 +17,13 @@ func (a *App) CreateTermsOfService(text, userId string) (*model.TermsOfService, return nil, err } - return a.Srv.Store.TermsOfService().Save(termsOfService) + return a.Srv().Store.TermsOfService().Save(termsOfService) } func (a *App) GetLatestTermsOfService() (*model.TermsOfService, *model.AppError) { - return a.Srv.Store.TermsOfService().GetLatest(true) + return a.Srv().Store.TermsOfService().GetLatest(true) } func (a *App) GetTermsOfService(id string) (*model.TermsOfService, *model.AppError) { - return a.Srv.Store.TermsOfService().Get(id, true) + return a.Srv().Store.TermsOfService().Get(id, true) } diff --git a/app/user.go b/app/user.go index b483e3705d..4a2f6ff338 100644 --- a/app/user.go +++ b/app/user.go @@ -62,12 +62,12 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. tokenData := model.MapFromJson(strings.NewReader(token.Extra)) - team, err := a.Srv.Store.Team().Get(tokenData["teamId"]) + team, err := a.Srv().Store.Team().Get(tokenData["teamId"]) if err != nil { return nil, err } - channels, err := a.Srv.Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " ")) + channels, err := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " ")) if err != nil { return nil, err } @@ -112,7 +112,7 @@ func (a *App) CreateUserWithInviteId(user *model.User, inviteId string) (*model. return nil, err } - team, err := a.Srv.Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store.Team().GetByInviteId(inviteId) if err != nil { return nil, err } @@ -188,7 +188,7 @@ func (a *App) IsUserSignUpAllowed() *model.AppError { func (a *App) IsFirstUserAccount() bool { if a.SessionCacheLength() == 0 { - count, err := a.Srv.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) + count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) if err != nil { mlog.Error("There was a error fetching if first user account", mlog.Err(err)) return false @@ -204,7 +204,7 @@ func (a *App) IsFirstUserAccount() bool { // indexUser fetches the required information to index a user from the database and // calls the elasticsearch interface method func (a *App) indexUser(user *model.User) *model.AppError { - userTeams, err := a.Srv.Store.Team().GetTeamsByUserId(user.Id) + userTeams, err := a.Srv().Store.Team().GetTeamsByUserId(user.Id) if err != nil { return err } @@ -214,7 +214,7 @@ func (a *App) indexUser(user *model.User) *model.AppError { userTeamsIds = append(userTeamsIds, team.Id) } - userChannelMembers, err := a.Srv.Store.Channel().GetAllChannelMembersForUser(user.Id, false, true) + userChannelMembers, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(user.Id, false, true) if err != nil { return err } @@ -224,7 +224,7 @@ func (a *App) indexUser(user *model.User) *model.AppError { userChannelsIds = append(userChannelsIds, channelId) } - return a.Elasticsearch.IndexUser(user, userTeamsIds, userChannelsIds) + return a.Elasticsearch().IndexUser(user, userTeamsIds, userChannelsIds) } func (a *App) indexUserFromId(userId string) *model.AppError { @@ -263,7 +263,7 @@ func (a *App) createUserOrGuest(user *model.User, guest bool) (*model.User, *mod // Below is a special case where the first user in the entire // system is granted the system_admin role - count, err := a.Srv.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) + count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) if err != nil { return nil, err } @@ -285,7 +285,7 @@ func (a *App) createUserOrGuest(user *model.User, guest bool) (*model.User, *mod a.Publish(message) if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { - a.Srv.Go(func() { + a.Srv().Go(func() { pluginContext := a.PluginContext() pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasBeenCreated(pluginContext, user) @@ -295,7 +295,7 @@ func (a *App) createUserOrGuest(user *model.User, guest bool) (*model.User, *mod } if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -312,7 +312,7 @@ func (a *App) createUser(user *model.User) (*model.User, *model.AppError) { return nil, err } - ruser, err := a.Srv.Store.User().Save(user) + ruser, err := a.Srv().Store.User().Save(user) if err != nil { mlog.Error("Couldn't save the user", mlog.Err(err)) return nil, err @@ -325,7 +325,7 @@ func (a *App) createUser(user *model.User) (*model.User, *model.AppError) { } pref := model.Preference{UserId: ruser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: ruser.Id, Value: "0"} - if err := a.Srv.Store.Preference().Save(&model.Preferences{pref}); err != nil { + if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil { mlog.Error("Encountered error saving tutorial preference", mlog.Err(err)) } @@ -351,12 +351,12 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string) suchan := make(chan store.StoreResult, 1) euchan := make(chan store.StoreResult, 1) go func() { - userByAuth, err := a.Srv.Store.User().GetByAuth(user.AuthData, service) + userByAuth, err := a.Srv().Store.User().GetByAuth(user.AuthData, service) suchan <- store.StoreResult{Data: userByAuth, Err: err} close(suchan) }() go func() { - userByEmail, err := a.Srv.Store.User().GetByEmail(user.Email) + userByEmail, err := a.Srv().Store.User().GetByEmail(user.Email) euchan <- store.StoreResult{Data: userByEmail, Err: err} close(euchan) }() @@ -432,7 +432,7 @@ func (a *App) IsUsernameTaken(name string) bool { return false } - if _, err := a.Srv.Store.User().GetByUsername(name); err != nil { + if _, err := a.Srv().Store.User().GetByUsername(name); err != nil { return false } @@ -440,11 +440,11 @@ func (a *App) IsUsernameTaken(name string) bool { } func (a *App) GetUser(userId string) (*model.User, *model.AppError) { - return a.Srv.Store.User().Get(userId) + return a.Srv().Store.User().Get(userId) } func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) { - result, err := a.Srv.Store.User().GetByUsername(username) + result, err := a.Srv().Store.User().GetByUsername(username) if err != nil && err.Id == "store.sql_user.get_by_username.app_error" { err.StatusCode = http.StatusNotFound return nil, err @@ -453,7 +453,7 @@ func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) } func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) { - user, err := a.Srv.Store.User().GetByEmail(email) + user, err := a.Srv().Store.User().GetByEmail(email) if err != nil { if err.Id == "store.sql_user.missing_account.const" { err.StatusCode = http.StatusNotFound @@ -466,11 +466,11 @@ func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) { } func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) { - return a.Srv.Store.User().GetByAuth(authData, authService) + return a.Srv().Store.User().GetByAuth(authData, authService) } func (a *App) GetUsers(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetAllProfiles(options) + return a.Srv().Store.User().GetAllProfiles(options) } func (a *App) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) { @@ -483,15 +483,15 @@ func (a *App) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*mode } func (a *App) GetUsersEtag(restrictionsHash string) string { - return fmt.Sprintf("%v.%v.%v.%v", a.Srv.Store.User().GetEtagForAllProfiles(), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) + return fmt.Sprintf("%v.%v.%v.%v", a.Srv().Store.User().GetEtagForAllProfiles(), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) } func (a *App) GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfiles(options) + return a.Srv().Store.User().GetProfiles(options) } func (a *App) GetUsersNotInTeam(teamId string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfilesNotInTeam(teamId, groupConstrained, offset, limit, viewRestrictions) + return a.Srv().Store.User().GetProfilesNotInTeam(teamId, groupConstrained, offset, limit, viewRestrictions) } func (a *App) GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) { @@ -513,19 +513,19 @@ func (a *App) GetUsersNotInTeamPage(teamId string, groupConstrained bool, page i } func (a *App) GetUsersInTeamEtag(teamId string, restrictionsHash string) string { - return fmt.Sprintf("%v.%v.%v.%v", a.Srv.Store.User().GetEtagForProfiles(teamId), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) + return fmt.Sprintf("%v.%v.%v.%v", a.Srv().Store.User().GetEtagForProfiles(teamId), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) } func (a *App) GetUsersNotInTeamEtag(teamId string, restrictionsHash string) string { - return fmt.Sprintf("%v.%v.%v.%v", a.Srv.Store.User().GetEtagForProfilesNotInTeam(teamId), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) + return fmt.Sprintf("%v.%v.%v.%v", a.Srv().Store.User().GetEtagForProfilesNotInTeam(teamId), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress, restrictionsHash) } func (a *App) GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfilesInChannel(channelId, offset, limit) + return a.Srv().Store.User().GetProfilesInChannel(channelId, offset, limit) } func (a *App) GetUsersInChannelByStatus(channelId string, offset int, limit int) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfilesInChannelByStatus(channelId, offset, limit) + return a.Srv().Store.User().GetProfilesInChannelByStatus(channelId, offset, limit) } func (a *App) GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { @@ -561,7 +561,7 @@ func (a *App) GetUsersInChannelPageByStatus(channelId string, page int, perPage } func (a *App) GetUsersNotInChannel(teamId string, channelId string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfilesNotInChannel(teamId, channelId, groupConstrained, offset, limit, viewRestrictions) + return a.Srv().Store.User().GetProfilesNotInChannel(teamId, channelId, groupConstrained, offset, limit, viewRestrictions) } func (a *App) GetUsersNotInChannelMap(teamId string, channelId string, groupConstrained bool, offset int, limit int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) (map[string]*model.User, *model.AppError) { @@ -599,23 +599,23 @@ func (a *App) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin boo } func (a *App) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetProfilesWithoutTeam(options) + return a.Srv().Store.User().GetProfilesWithoutTeam(options) } // GetTeamGroupUsers returns the users who are associated to the team via GroupTeams and GroupMembers. func (a *App) GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetTeamGroupUsers(teamID) + return a.Srv().Store.User().GetTeamGroupUsers(teamID) } // GetChannelGroupUsers returns the users who are associated to the channel via GroupChannels and GroupMembers. func (a *App) GetChannelGroupUsers(channelID string) ([]*model.User, *model.AppError) { - return a.Srv.Store.User().GetChannelGroupUsers(channelID) + return a.Srv().Store.User().GetChannelGroupUsers(channelID) } func (a *App) GetUsersByIds(userIds []string, options *store.UserGetByIdsOpts) ([]*model.User, *model.AppError) { allowFromCache := options.ViewRestrictions == nil - users, err := a.Srv.Store.User().GetProfileByIds(userIds, options, allowFromCache) + users, err := a.Srv().Store.User().GetProfileByIds(userIds, options, allowFromCache) if err != nil { return nil, err } @@ -624,7 +624,7 @@ func (a *App) GetUsersByIds(userIds []string, options *store.UserGetByIdsOpts) ( } func (a *App) GetUsersByGroupChannelIds(channelIds []string, asAdmin bool) (map[string][]*model.User, *model.AppError) { - usersByChannelId, err := a.Srv.Store.User().GetProfileByGroupChannelIdsForUser(a.Session.UserId, channelIds) + usersByChannelId, err := a.Srv().Store.User().GetProfileByGroupChannelIdsForUser(a.Session().UserId, channelIds) if err != nil { return nil, err } @@ -636,7 +636,7 @@ func (a *App) GetUsersByGroupChannelIds(channelIds []string, asAdmin bool) (map[ } func (a *App) GetUsersByUsernames(usernames []string, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv.Store.User().GetProfilesByUsernames(usernames, viewRestrictions) + users, err := a.Srv().Store.User().GetProfilesByUsernames(usernames, viewRestrictions) if err != nil { return nil, err } @@ -657,7 +657,7 @@ func (a *App) GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppErro return nil, err } - mfaService := mfa.New(a, a.Srv.Store) + mfaService := mfa.New(a, a.Srv().Store) secret, img, err := mfaService.GenerateSecret(user) if err != nil { return nil, err @@ -668,7 +668,7 @@ func (a *App) GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppErro } func (a *App) ActivateMfa(userId, token string) *model.AppError { - user, err := a.Srv.Store.User().Get(userId) + user, err := a.Srv().Store.User().Get(userId) if err != nil { return err } @@ -677,7 +677,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError { return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest) } - mfaService := mfa.New(a, a.Srv.Store) + mfaService := mfa.New(a, a.Srv().Store) if err := mfaService.Activate(user, token); err != nil { return err } @@ -686,7 +686,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError { } func (a *App) DeactivateMfa(userId string) *model.AppError { - mfaService := mfa.New(a, a.Srv.Store) + mfaService := mfa.New(a, a.Srv().Store) if err := mfaService.Deactivate(userId); err != nil { return err } @@ -834,7 +834,7 @@ func (a *App) SetDefaultProfileImage(user *model.User) *model.AppError { return err } - if err := a.Srv.Store.User().ResetLastPictureUpdate(user.Id); err != nil { + if err := a.Srv().Store.User().ResetLastPictureUpdate(user.Id); err != nil { mlog.Error("Failed to reset last picture update", mlog.Err(err)) } @@ -907,7 +907,7 @@ func (a *App) SetProfileImageFromFile(userId string, file io.Reader) *model.AppE return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.upload_profile.app_error", nil, "", http.StatusInternalServerError) } - if err := a.Srv.Store.User().UpdateLastPictureUpdate(userId); err != nil { + if err := a.Srv().Store.User().UpdateLastPictureUpdate(userId); err != nil { mlog.Error("Error with updating last picture update", mlog.Err(err)) } a.invalidateUserCacheAndPublish(userId) @@ -997,7 +997,7 @@ func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.A user.DeleteAt = user.UpdateAt } - userUpdate, err := a.Srv.Store.User().Update(user, true) + userUpdate, err := a.Srv().Store.User().Update(user, true) if err != nil { return nil, err } @@ -1018,7 +1018,7 @@ func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.A } func (a *App) DeactivateGuests() *model.AppError { - userIds, err := a.Srv.Store.User().DeactivateGuests() + userIds, err := a.Srv().Store.User().DeactivateGuests() if err != nil { return err } @@ -1029,8 +1029,8 @@ func (a *App) DeactivateGuests() *model.AppError { } } - a.Srv.Store.Channel().ClearCaches() - a.Srv.Store.User().ClearCaches() + a.Srv().Store.Channel().ClearCaches() + a.Srv().Store.User().ClearCaches() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_GUESTS_DEACTIVATED, "", "", "", nil) a.Publish(message) @@ -1093,13 +1093,13 @@ func (a *App) UpdateUserAuth(userId string, userAuth *model.UserAuth) (*model.Us } password := model.HashPassword(userAuth.Password) - if err := a.Srv.Store.User().UpdatePassword(userId, password); err != nil { + if err := a.Srv().Store.User().UpdatePassword(userId, password); err != nil { return nil, err } } else { userAuth.Password = "" - if _, err := a.Srv.Store.User().UpdateAuthData(userId, userAuth.AuthService, userAuth.AuthData, "", false); err != nil { + if _, err := a.Srv().Store.User().UpdateAuthData(userId, userAuth.AuthService, userAuth.AuthData, "", false); err != nil { return nil, err } } @@ -1123,7 +1123,7 @@ func (a *App) sendUpdatedUserEvent(user model.User) { } func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) { - prev, err := a.Srv.Store.User().Get(user.Id) + prev, err := a.Srv().Store.User().Get(user.Id) if err != nil { return nil, err } @@ -1160,7 +1160,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, } } - userUpdate, err := a.Srv.Store.User().Update(user, false) + userUpdate, err := a.Srv().Store.User().Update(user, false) if err != nil { return nil, err } @@ -1168,13 +1168,13 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, if sendNotifications { if userUpdate.New.Email != userUpdate.Old.Email || newEmail != "" { if *a.Config().EmailSettings.RequireEmailVerification { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendEmailVerification(userUpdate.New, newEmail); err != nil { mlog.Error("Failed to send email verification", mlog.Err(err)) } }) } else { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendEmailChangeEmail(userUpdate.Old.Email, userUpdate.New.Email, userUpdate.New.Locale, a.GetSiteURL()); err != nil { mlog.Error("Failed to send email change email", mlog.Err(err)) } @@ -1183,7 +1183,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, } if userUpdate.New.Username != userUpdate.Old.Username { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendChangeUsernameEmail(userUpdate.Old.Username, userUpdate.New.Username, userUpdate.New.Email, userUpdate.New.Locale, a.GetSiteURL()); err != nil { mlog.Error("Failed to send change username email", mlog.Err(err)) } @@ -1194,7 +1194,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, a.InvalidateCacheForUser(user.Id) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -1244,7 +1244,7 @@ func (a *App) UpdateMfa(activate bool, userId, token string) *model.AppError { } } - a.Srv.Go(func() { + a.Srv().Go(func() { user, err := a.GetUser(userId) if err != nil { mlog.Error("Failed to get user", mlog.Err(err)) @@ -1275,7 +1275,7 @@ func (a *App) UpdatePassword(user *model.User, newPassword string) *model.AppErr hashedPassword := model.HashPassword(newPassword) - if err := a.Srv.Store.User().UpdatePassword(user.Id, hashedPassword); err != nil { + if err := a.Srv().Store.User().UpdatePassword(user.Id, hashedPassword); err != nil { return model.NewAppError("UpdatePassword", "api.user.update_password.failed.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1287,7 +1287,7 @@ func (a *App) UpdatePasswordSendEmail(user *model.User, newPassword, method stri return err } - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendPasswordChangeEmail(user.Email, method, user.Locale, a.GetSiteURL()); err != nil { mlog.Error("Failed to send password change email", mlog.Err(err)) } @@ -1376,7 +1376,7 @@ func (a *App) CreatePasswordRecoveryToken(userId, email string) (*model.Token, * token := model.NewToken(TOKEN_TYPE_PASSWORD_RECOVERY, string(jsonData)) - if err := a.Srv.Store.Token().Save(token); err != nil { + if err := a.Srv().Store.Token().Save(token); err != nil { return nil, err } @@ -1384,7 +1384,7 @@ func (a *App) CreatePasswordRecoveryToken(userId, email string) (*model.Token, * } func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) { - rtoken, err := a.Srv.Store.Token().GetByToken(token) + rtoken, err := a.Srv().Store.Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -1395,7 +1395,7 @@ func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppEr } func (a *App) DeleteToken(token *model.Token) *model.AppError { - return a.Srv.Store.Token().Delete(token.Token) + return a.Srv().Store.Token().Delete(token.Token) } func (a *App) UpdateUserRoles(userId string, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError) { @@ -1412,14 +1412,14 @@ func (a *App) UpdateUserRoles(userId string, newRoles string, sendWebSocketEvent user.Roles = newRoles uchan := make(chan store.StoreResult, 1) go func() { - userUpdate, err := a.Srv.Store.User().Update(user, true) + userUpdate, err := a.Srv().Store.User().Update(user, true) uchan <- store.StoreResult{Data: userUpdate, Err: err} close(uchan) }() schan := make(chan store.StoreResult, 1) go func() { - userId, err := a.Srv.Store.Session().UpdateRoles(user.Id, newRoles) + userId, err := a.Srv().Store.Session().UpdateRoles(user.Id, newRoles) schan <- store.StoreResult{Data: userId, Err: err} close(schan) }() @@ -1458,51 +1458,51 @@ func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { return err } - if err := a.Srv.Store.Session().PermanentDeleteSessionsByUser(user.Id); err != nil { + if err := a.Srv().Store.Session().PermanentDeleteSessionsByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.UserAccessToken().DeleteAllForUser(user.Id); err != nil { + if err := a.Srv().Store.UserAccessToken().DeleteAllForUser(user.Id); err != nil { return err } - if err := a.Srv.Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); err != nil { + if err := a.Srv().Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Webhook().PermanentDeleteIncomingByUser(user.Id); err != nil { + if err := a.Srv().Store.Webhook().PermanentDeleteIncomingByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); err != nil { + if err := a.Srv().Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Command().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store.Command().PermanentDeleteByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Preference().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store.Preference().PermanentDeleteByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Channel().PermanentDeleteMembersByUser(user.Id); err != nil { + if err := a.Srv().Store.Channel().PermanentDeleteMembersByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Group().PermanentDeleteMembersByUser(user.Id); err != nil { + if err := a.Srv().Store.Group().PermanentDeleteMembersByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Post().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store.Post().PermanentDeleteByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Bot().PermanentDelete(user.Id); err != nil { + if err := a.Srv().Store.Bot().PermanentDelete(user.Id); err != nil { return err } - infos, err := a.Srv.Store.FileInfo().GetForUser(user.Id) + infos, err := a.Srv().Store.FileInfo().GetForUser(user.Id) if err != nil { mlog.Warn("Error getting file list for user from FileInfoStore", mlog.Err(err)) } @@ -1534,27 +1534,27 @@ func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { } } - if _, err := a.Srv.Store.FileInfo().PermanentDeleteByUser(user.Id); err != nil { + if _, err := a.Srv().Store.FileInfo().PermanentDeleteByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.User().PermanentDelete(user.Id); err != nil { + if err := a.Srv().Store.User().PermanentDelete(user.Id); err != nil { return err } - if err := a.Srv.Store.Audit().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store.Audit().PermanentDeleteByUser(user.Id); err != nil { return err } - if err := a.Srv.Store.Team().RemoveAllMembersByUser(user.Id); err != nil { + if err := a.Srv().Store.Team().RemoveAllMembersByUser(user.Id); err != nil { return err } mlog.Warn("Permanently deleted account", mlog.String("user_email", user.Email), mlog.String("user_id", user.Id)) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { - if err := a.Elasticsearch.DeleteUser(user); err != nil { + a.Srv().Go(func() { + if err := a.Elasticsearch().DeleteUser(user); err != nil { mlog.Error("Encountered error deleting user", mlog.String("user_id", user.Id), mlog.Err(err)) } }) @@ -1564,7 +1564,7 @@ func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { } func (a *App) PermanentDeleteAllUsers() *model.AppError { - users, err := a.Srv.Store.User().GetAll() + users, err := a.Srv().Store.User().GetAll() if err != nil { return err } @@ -1617,7 +1617,7 @@ func (a *App) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppErr } if user.Email != tokenData.Email { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.SendEmailChangeEmail(user.Email, tokenData.Email, user.Locale, a.GetSiteURL()); err != nil { mlog.Error("Failed to send email change email", mlog.Err(err)) } @@ -1647,7 +1647,7 @@ func (a *App) CreateVerifyEmailToken(userId string, newEmail string) (*model.Tok token := model.NewToken(TOKEN_TYPE_VERIFY_EMAIL, string(jsonData)) - if err := a.Srv.Store.Token().Save(token); err != nil { + if err := a.Srv().Store.Token().Save(token); err != nil { return nil, err } @@ -1655,7 +1655,7 @@ func (a *App) CreateVerifyEmailToken(userId string, newEmail string) (*model.Tok } func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) { - rtoken, err := a.Srv.Store.Token().GetByToken(token) + rtoken, err := a.Srv().Store.Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -1667,7 +1667,7 @@ func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) // GetTotalUsersStats is used for the DM list total func (a *App) GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) (*model.UsersStats, *model.AppError) { - count, err := a.Srv.Store.User().Count(model.UserCountOptions{ + count, err := a.Srv().Store.User().Count(model.UserCountOptions{ IncludeBotAccounts: true, ViewRestrictions: viewRestrictions, }) @@ -1681,7 +1681,7 @@ func (a *App) GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) } func (a *App) VerifyUserEmail(userId, email string) *model.AppError { - _, err := a.Srv.Store.User().VerifyEmail(userId, email) + _, err := a.Srv().Store.User().VerifyEmail(userId, email) if err != nil { return err } @@ -1715,7 +1715,7 @@ func (a *App) SearchUsers(props *model.UserSearch, options *model.UserSearchOpti func (a *App) SearchUsersInChannel(channelId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv.Store.User().SearchInChannel(channelId, term, options) + users, err := a.Srv().Store.User().SearchInChannel(channelId, term, options) if err != nil { return nil, err } @@ -1728,7 +1728,7 @@ func (a *App) SearchUsersInChannel(channelId string, term string, options *model func (a *App) SearchUsersNotInChannel(teamId string, channelId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, options) + users, err := a.Srv().Store.User().SearchNotInChannel(teamId, channelId, term, options) if err != nil { return nil, err } @@ -1741,7 +1741,7 @@ func (a *App) SearchUsersNotInChannel(teamId string, channelId string, term stri } func (a *App) esSearchUsersInTeam(teamId, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { - listOfAllowedChannels, err := a.GetViewUsersRestrictionsForTeam(a.Session.UserId, teamId) + listOfAllowedChannels, err := a.GetViewUsersRestrictionsForTeam(a.Session().UserId, teamId) if err != nil { return nil, err } @@ -1749,12 +1749,12 @@ func (a *App) esSearchUsersInTeam(teamId, term string, options *model.UserSearch return []*model.User{}, nil } - usersIds, err := a.Elasticsearch.SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) + usersIds, err := a.Elasticsearch().SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) if err != nil { return nil, err } - users, err := a.Srv.Store.User().GetProfileByIds(usersIds, nil, false) + users, err := a.Srv().Store.User().GetProfileByIds(usersIds, nil, false) if err != nil { return nil, err } @@ -1779,7 +1779,7 @@ func (a *App) SearchUsersInTeam(teamId, term string, options *model.UserSearchOp } if !a.IsESAutocompletionEnabled() || err != nil { - users, err = a.Srv.Store.User().Search(teamId, term, options) + users, err = a.Srv().Store.User().Search(teamId, term, options) if err != nil { return nil, err } @@ -1794,7 +1794,7 @@ func (a *App) SearchUsersInTeam(teamId, term string, options *model.UserSearchOp func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv.Store.User().SearchNotInTeam(notInTeamId, term, options) + users, err := a.Srv().Store.User().SearchNotInTeam(notInTeamId, term, options) if err != nil { return nil, err } @@ -1808,7 +1808,7 @@ func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, options *mod func (a *App) SearchUsersWithoutTeam(term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv.Store.User().SearchWithoutTeam(term, options) + users, err := a.Srv().Store.User().SearchWithoutTeam(term, options) if err != nil { return nil, err } @@ -1831,9 +1831,9 @@ func (a *App) esAutocompleteUsersInChannel(teamId, channelId, term string, optio uchanIds := []string{} nuchanIds := []string{} if !strings.Contains(strings.Join(listOfAllowedChannels, "."), channelId) { - nuchanIds, err = a.Elasticsearch.SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) + nuchanIds, err = a.Elasticsearch().SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) } else { - uchanIds, nuchanIds, err = a.Elasticsearch.SearchUsersInChannel(teamId, channelId, listOfAllowedChannels, term, options) + uchanIds, nuchanIds, err = a.Elasticsearch().SearchUsersInChannel(teamId, channelId, listOfAllowedChannels, term, options) } if err != nil { return nil, err @@ -1841,14 +1841,14 @@ func (a *App) esAutocompleteUsersInChannel(teamId, channelId, term string, optio uchan := make(chan store.StoreResult, 1) go func() { - users, err := a.Srv.Store.User().GetProfileByIds(uchanIds, nil, false) + users, err := a.Srv().Store.User().GetProfileByIds(uchanIds, nil, false) uchan <- store.StoreResult{Data: users, Err: err} close(uchan) }() nuchan := make(chan store.StoreResult, 1) go func() { - users, err := a.Srv.Store.User().GetProfileByIds(nuchanIds, nil, false) + users, err := a.Srv().Store.User().GetProfileByIds(nuchanIds, nil, false) nuchan <- store.StoreResult{Data: users, Err: err} close(nuchan) }() @@ -1899,14 +1899,14 @@ func (a *App) AutocompleteUsersInChannel(teamId string, channelId string, term s uchan := make(chan store.StoreResult, 1) go func() { - users, err := a.Srv.Store.User().SearchInChannel(channelId, term, options) + users, err := a.Srv().Store.User().SearchInChannel(channelId, term, options) uchan <- store.StoreResult{Data: users, Err: err} close(uchan) }() nuchan := make(chan store.StoreResult, 1) go func() { - users, err := a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, options) + users, err := a.Srv().Store.User().SearchNotInChannel(teamId, channelId, term, options) nuchan <- store.StoreResult{Data: users, Err: err} close(nuchan) }() @@ -1949,12 +1949,12 @@ func (a *App) esAutocompleteUsersInTeam(teamId, term string, options *model.User return &model.UserAutocompleteInTeam{}, nil } - usersIds, err := a.Elasticsearch.SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) + usersIds, err := a.Elasticsearch().SearchUsersInTeam(teamId, listOfAllowedChannels, term, options) if err != nil { return nil, err } - users, err := a.Srv.Store.User().GetProfileByIds(usersIds, nil, false) + users, err := a.Srv().Store.User().GetProfileByIds(usersIds, nil, false) if err != nil { return nil, err } @@ -1984,7 +1984,7 @@ func (a *App) AutocompleteUsersInTeam(teamId string, term string, options *model if !a.IsESAutocompletionEnabled() || err != nil { autocomplete = &model.UserAutocompleteInTeam{} - users, err := a.Srv.Store.User().Search(teamId, term, options) + users, err := a.Srv().Store.User().Search(teamId, term, options) if err != nil { return nil, err } @@ -2034,7 +2034,7 @@ func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provide } if userAttrsChanged { - users, err := a.Srv.Store.User().Update(user, true) + users, err := a.Srv().Store.User().Update(user, true) if err != nil { return err } @@ -2043,7 +2043,7 @@ func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provide a.InvalidateCacheForUser(user.Id) if a.IsESIndexingEnabled() { - a.Srv.Go(func() { + a.Srv().Go(func() { if err := a.indexUser(user); err != nil { mlog.Error("Encountered error indexing user", mlog.String("user_id", user.Id), mlog.Err(err)) } @@ -2088,7 +2088,7 @@ func (a *App) FilterNonGroupChannelMembers(userIds []string, channel *model.Chan // and returns the list of normal users present in userIds but not in groupUsers. func (a *App) filterNonGroupUsers(userIds []string, groupUsers []*model.User) ([]string, error) { nonMemberIds := []string{} - users, err := a.Srv.Store.User().GetProfileByIds(userIds, nil, false) + users, err := a.Srv().Store.User().GetProfileByIds(userIds, nil, false) if err != nil { return nil, err } @@ -2135,7 +2135,7 @@ func (a *App) UserCanSeeOtherUser(userId string, otherUserId string) (bool, *mod } if len(restrictions.Teams) > 0 { - result, err := a.Srv.Store.Team().UserBelongsToTeams(otherUserId, restrictions.Teams) + result, err := a.Srv().Store.Team().UserBelongsToTeams(otherUserId, restrictions.Teams) if err != nil { return false, err } @@ -2158,7 +2158,7 @@ func (a *App) UserCanSeeOtherUser(userId string, otherUserId string) (bool, *mod } func (a *App) userBelongsToChannels(userId string, channelIds []string) (bool, *model.AppError) { - return a.Srv.Store.Channel().UserBelongsToChannels(userId, channelIds) + return a.Srv().Store.Channel().UserBelongsToChannels(userId, channelIds) } func (a *App) GetViewUsersRestrictions(userId string) (*model.ViewUsersRestrictions, *model.AppError) { @@ -2166,7 +2166,7 @@ func (a *App) GetViewUsersRestrictions(userId string) (*model.ViewUsersRestricti return nil, nil } - teamIds, getTeamErr := a.Srv.Store.Team().GetUserTeamIds(userId, true) + teamIds, getTeamErr := a.Srv().Store.Team().GetUserTeamIds(userId, true) if getTeamErr != nil { return nil, getTeamErr } @@ -2178,7 +2178,7 @@ func (a *App) GetViewUsersRestrictions(userId string) (*model.ViewUsersRestricti } } - userChannelMembers, err := a.Srv.Store.Channel().GetAllChannelMembersForUser(userId, true, true) + userChannelMembers, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(userId, true, true) if err != nil { return nil, err } @@ -2205,7 +2205,7 @@ func (a *App) GetViewUsersRestrictionsForTeam(userId string, teamId string) ([]s return nil, nil } - members, err := a.Srv.Store.Channel().GetMembersForUser(teamId, userId) + members, err := a.Srv().Store.Channel().GetMembersForUser(teamId, userId) if err != nil { return nil, err } @@ -2221,7 +2221,7 @@ func (a *App) GetViewUsersRestrictionsForTeam(userId string, teamId string) ([]s func (a *App) getListOfAllowedChannelsForTeam(teamId string, viewRestrictions *model.ViewUsersRestrictions) ([]string, *model.AppError) { var listOfAllowedChannels []string if viewRestrictions == nil || strings.Contains(strings.Join(viewRestrictions.Teams, "."), teamId) { - channels, err := a.Srv.Store.Channel().GetTeamChannels(teamId) + channels, err := a.Srv().Store.Channel().GetTeamChannels(teamId) if err != nil { return nil, err } @@ -2233,7 +2233,7 @@ func (a *App) getListOfAllowedChannelsForTeam(teamId string, viewRestrictions *m return channelIds, nil } - channels, err := a.Srv.Store.Channel().GetChannelsByIds(viewRestrictions.Channels) + channels, err := a.Srv().Store.Channel().GetChannelsByIds(viewRestrictions.Channels) if err != nil { return nil, err } @@ -2249,12 +2249,12 @@ func (a *App) getListOfAllowedChannelsForTeam(teamId string, viewRestrictions *m // PromoteGuestToUser Convert user's roles and all his mermbership's roles from // guest roles to regular user roles. func (a *App) PromoteGuestToUser(user *model.User, requestorId string) *model.AppError { - err := a.Srv.Store.User().PromoteGuestToUser(user.Id) + err := a.Srv().Store.User().PromoteGuestToUser(user.Id) a.InvalidateCacheForUser(user.Id) if err != nil { return err } - userTeams, err := a.Srv.Store.Team().GetTeamsByUserId(user.Id) + userTeams, err := a.Srv().Store.Team().GetTeamsByUserId(user.Id) if err != nil { return err } @@ -2303,7 +2303,7 @@ func (a *App) PromoteGuestToUser(user *model.User, requestorId string) *model.Ap // DemoteUserToGuest Convert user's roles and all his mermbership's roles from // regular user roles to guest roles. func (a *App) DemoteUserToGuest(user *model.User) *model.AppError { - err := a.Srv.Store.User().DemoteUserToGuest(user.Id) + err := a.Srv().Store.User().DemoteUserToGuest(user.Id) a.InvalidateCacheForUser(user.Id) if err != nil { return err diff --git a/app/user_terms_of_service.go b/app/user_terms_of_service.go index caa45165e2..7873ee3abc 100644 --- a/app/user_terms_of_service.go +++ b/app/user_terms_of_service.go @@ -6,7 +6,7 @@ package app import "github.com/mattermost/mattermost-server/v5/model" func (a *App) GetUserTermsOfService(userId string) (*model.UserTermsOfService, *model.AppError) { - return a.Srv.Store.UserTermsOfService().GetByUser(userId) + return a.Srv().Store.UserTermsOfService().GetByUser(userId) } func (a *App) SaveUserTermsOfService(userId, termsOfServiceId string, accepted bool) *model.AppError { @@ -16,11 +16,11 @@ func (a *App) SaveUserTermsOfService(userId, termsOfServiceId string, accepted b TermsOfServiceId: termsOfServiceId, } - if _, err := a.Srv.Store.UserTermsOfService().Save(userTermsOfService); err != nil { + if _, err := a.Srv().Store.UserTermsOfService().Save(userTermsOfService); err != nil { return err } } else { - if err := a.Srv.Store.UserTermsOfService().Delete(userId, termsOfServiceId); err != nil { + if err := a.Srv().Store.UserTermsOfService().Delete(userId, termsOfServiceId); err != nil { return err } } diff --git a/app/user_test.go b/app/user_test.go index 5fc8acac22..bb66c076a9 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -372,7 +372,7 @@ func TestUpdateUserEmail(t *testing.T) { Username: model.NewId(), IsBot: true, } - _, err = th.App.Srv.Store.User().Save(&botuser) + _, err = th.App.Srv().Store.User().Save(&botuser) assert.Nil(t, err) newBotEmail := th.MakeEmail() @@ -415,7 +415,7 @@ func TestUpdateUserEmail(t *testing.T) { Username: model.NewId(), IsBot: true, } - _, err = th.App.Srv.Store.User().Save(&botuser) + _, err = th.App.Srv().Store.User().Save(&botuser) assert.Nil(t, err) newBotEmail := th.MakeEmail() @@ -583,7 +583,7 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_VERIFY_EMAIL, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(&user, token) require.NotNil(t, err, "Should fail on bad token type") @@ -595,7 +595,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1 - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(&user, token) require.NotNil(t, err, "Should fail on expired token") @@ -606,7 +606,7 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": model.NewId(), "email": user.Email}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(&user, token) require.NotNil(t, err, "Should fail on bad team id") @@ -618,13 +618,13 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_TEAM_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) newUser, err := th.App.CreateUserWithToken(&user, token) require.Nil(t, err, "Should add user to the team. err=%v", err) assert.False(t, newUser.IsGuest()) require.Equal(t, invitationEmail, newUser.Email, "The user email must be the invitation one") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newUser.Id) @@ -638,14 +638,14 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) guest := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} newGuest, err := th.App.CreateUserWithToken(&guest, token) require.Nil(t, err, "Should add user to the team. err=%v", err) assert.True(t, newGuest.IsGuest()) require.Equal(t, invitationEmail, newGuest.Email, "The user email must be the invitation one") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) @@ -672,8 +672,8 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(forbiddenDomainToken)) - require.Nil(t, th.App.Srv.Store.Token().Save(grantedDomainToken)) + require.Nil(t, th.App.Srv().Store.Token().Save(forbiddenDomainToken)) + require.Nil(t, th.App.Srv().Store.Token().Save(grantedDomainToken)) guest := model.User{ Email: strings.ToLower(model.NewId()) + "+test@example.com", Nickname: "Darth Vader", @@ -690,7 +690,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Nil(t, err) assert.True(t, newGuest.IsGuest()) require.Equal(t, grantedInvitationEmail, newGuest.Email) - _, err = th.App.Srv.Store.Token().GetByToken(grantedDomainToken.Token) + _, err = th.App.Srv().Store.Token().GetByToken(grantedDomainToken.Token) require.NotNil(t, err) members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) @@ -715,7 +715,7 @@ func TestCreateUserWithToken(t *testing.T) { TOKEN_TYPE_GUEST_INVITATION, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) - require.Nil(t, th.App.Srv.Store.Token().Save(token)) + require.Nil(t, th.App.Srv().Store.Token().Save(token)) guest := model.User{ Email: strings.ToLower(model.NewId()) + "+test@example.com", Nickname: "Darth Vader", @@ -727,7 +727,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Nil(t, err) assert.True(t, newGuest.IsGuest()) assert.Equal(t, invitationEmail, newGuest.Email, "The user email must be the invitation one") - _, err = th.App.Srv.Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store.Token().GetByToken(token.Token) require.NotNil(t, err) members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) diff --git a/app/web_conn.go b/app/web_conn.go index 8f7d82226f..1a7da373e2 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -47,7 +47,7 @@ type WebConn struct { func (a *App) NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.TranslateFunc, locale string) *WebConn { if len(session.UserId) > 0 { - a.Srv.Go(func() { + a.Srv().Go(func() { a.SetStatusOnline(session.UserId, false) a.UpdateLastActivityAtIfNeeded(session) }) @@ -132,7 +132,7 @@ func (wc *WebConn) readPump() { wc.WebSocket.SetPongHandler(func(string) error { wc.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) if wc.IsAuthenticated() { - wc.App.Srv.Go(func() { + wc.App.Srv().Go(func() { wc.App.SetStatusAwayIfNeeded(wc.UserId, false) }) } @@ -150,7 +150,7 @@ func (wc *WebConn) readPump() { } return } - wc.App.Srv.WebSocketRouter.ServeWebSocket(wc, &req) + wc.App.Srv().WebSocketRouter.ServeWebSocket(wc, &req) } } @@ -231,9 +231,9 @@ func (wc *WebConn) writePump() { return } - if wc.App.Metrics != nil { - wc.App.Srv.Go(func() { - wc.App.Metrics.IncrementWebSocketBroadcast(msg.EventType()) + if wc.App.Metrics() != nil { + wc.App.Srv().Go(func() { + wc.App.Metrics().IncrementWebSocketBroadcast(msg.EventType()) }) } } @@ -374,7 +374,7 @@ func (wc *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { } if wc.AllChannelMembers == nil { - result, err := wc.App.Srv.Store.Channel().GetAllChannelMembersForUser(wc.UserId, true, false) + result, err := wc.App.Srv().Store.Channel().GetAllChannelMembersForUser(wc.UserId, true, false) if err != nil { mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) return false diff --git a/app/web_hub.go b/app/web_hub.go index d7f4c62c54..65ab3cbf2e 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -62,7 +62,7 @@ func (a *App) NewWebHub() *Hub { func (a *App) TotalWebsocketConnections() int { count := int64(0) - for _, hub := range a.Srv.Hubs { + for _, hub := range a.Srv().Hubs { count = count + atomic.LoadInt64(&hub.connectionCount) } @@ -74,13 +74,13 @@ func (a *App) HubStart() { numberOfHubs := runtime.NumCPU() * 2 mlog.Info("Starting websocket hubs", mlog.Int("number_of_hubs", numberOfHubs)) - a.Srv.Hubs = make([]*Hub, numberOfHubs) - a.Srv.HubsStopCheckingForDeadlock = make(chan bool, 1) + a.Srv().Hubs = make([]*Hub, numberOfHubs) + a.Srv().HubsStopCheckingForDeadlock = make(chan bool, 1) - for i := 0; i < len(a.Srv.Hubs); i++ { - a.Srv.Hubs[i] = a.NewWebHub() - a.Srv.Hubs[i].connectionIndex = i - a.Srv.Hubs[i].Start() + for i := 0; i < len(a.Srv().Hubs); i++ { + a.Srv().Hubs[i] = a.NewWebHub() + a.Srv().Hubs[i].connectionIndex = i + a.Srv().Hubs[i].Start() } go func() { @@ -93,7 +93,7 @@ func (a *App) HubStart() { for { select { case <-ticker.C: - for _, hub := range a.Srv.Hubs { + for _, hub := range a.Srv().Hubs { if len(hub.broadcast) >= DEADLOCK_WARN { mlog.Error( "Hub processing might be deadlock with events in the buffer", @@ -114,7 +114,7 @@ func (a *App) HubStart() { } } - case <-a.Srv.HubsStopCheckingForDeadlock: + case <-a.Srv().HubsStopCheckingForDeadlock: return } } @@ -125,27 +125,27 @@ func (a *App) HubStop() { mlog.Info("stopping websocket hub connections") select { - case a.Srv.HubsStopCheckingForDeadlock <- true: + case a.Srv().HubsStopCheckingForDeadlock <- true: default: mlog.Warn("We appear to have already sent the stop checking for deadlocks command") } - for _, hub := range a.Srv.Hubs { + for _, hub := range a.Srv().Hubs { hub.Stop() } - a.Srv.Hubs = []*Hub{} + a.Srv().Hubs = []*Hub{} } func (a *App) GetHubForUserId(userId string) *Hub { - if len(a.Srv.Hubs) == 0 { + if len(a.Srv().Hubs) == 0 { return nil } hash := fnv.New32a() hash.Write([]byte(userId)) - index := hash.Sum32() % uint32(len(a.Srv.Hubs)) - return a.Srv.Hubs[index] + index := hash.Sum32() % uint32(len(a.Srv().Hubs)) + return a.Srv().Hubs[index] } func (a *App) HubRegister(webConn *WebConn) { @@ -163,13 +163,13 @@ func (a *App) HubUnregister(webConn *WebConn) { } func (a *App) Publish(message *model.WebSocketEvent) { - if metrics := a.Metrics; metrics != nil { + if metrics := a.Metrics(); metrics != nil { metrics.IncrementWebsocketEvent(message.EventType()) } a.PublishSkipClusterSend(message) - if a.Cluster != nil { + if a.Cluster() != nil { cm := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_PUBLISH, SendType: model.CLUSTER_SEND_BEST_EFFORT, @@ -184,7 +184,7 @@ func (a *App) Publish(message *model.WebSocketEvent) { cm.SendType = model.CLUSTER_SEND_RELIABLE } - a.Cluster.SendClusterMessage(cm) + a.Cluster().SendClusterMessage(cm) } } @@ -195,17 +195,17 @@ func (a *App) PublishSkipClusterSend(message *model.WebSocketEvent) { hub.Broadcast(message) } } else { - for _, hub := range a.Srv.Hubs { + for _, hub := range a.Srv().Hubs { hub.Broadcast(message) } } } func (a *App) InvalidateCacheForChannel(channel *model.Channel) { - a.Srv.Store.Channel().InvalidateChannel(channel.Id) + a.Srv().Store.Channel().InvalidateChannel(channel.Id) a.InvalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) - if a.Cluster != nil { + if a.Cluster() != nil { nameMsg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, SendType: model.CLUSTER_SEND_BEST_EFFORT, @@ -219,31 +219,31 @@ func (a *App) InvalidateCacheForChannel(channel *model.Channel) { nameMsg.Props["id"] = channel.TeamId } - a.Cluster.SendClusterMessage(nameMsg) + a.Cluster().SendClusterMessage(nameMsg) } } func (a *App) InvalidateCacheForChannelMembers(channelId string) { - a.Srv.Store.User().InvalidateProfilesInChannelCache(channelId) - a.Srv.Store.Channel().InvalidateMemberCount(channelId) - a.Srv.Store.Channel().InvalidateGuestCount(channelId) + a.Srv().Store.User().InvalidateProfilesInChannelCache(channelId) + a.Srv().Store.Channel().InvalidateMemberCount(channelId) + a.Srv().Store.Channel().InvalidateGuestCount(channelId) } func (a *App) InvalidateCacheForChannelMembersNotifyProps(channelId string) { a.InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId) - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: channelId, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } func (a *App) InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId string) { - a.Srv.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelId) + a.Srv().Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelId) } func (a *App) InvalidateCacheForChannelByNameSkipClusterSend(teamId, name string) { @@ -251,46 +251,46 @@ func (a *App) InvalidateCacheForChannelByNameSkipClusterSend(teamId, name string teamId = "dm" } - a.Srv.Store.Channel().InvalidateChannelByName(teamId, name) + a.Srv().Store.Channel().InvalidateChannelByName(teamId, name) } func (a *App) InvalidateCacheForChannelPosts(channelId string) { - a.Srv.Store.Channel().InvalidatePinnedPostCount(channelId) - a.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) + a.Srv().Store.Channel().InvalidatePinnedPostCount(channelId) + a.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) } func (a *App) InvalidateCacheForUser(userId string) { a.InvalidateCacheForUserSkipClusterSend(userId) - a.Srv.Store.User().InvalidateProfilesInChannelCacheByUser(userId) - a.Srv.Store.User().InvalidateProfileCacheForUser(userId) + a.Srv().Store.User().InvalidateProfilesInChannelCacheByUser(userId) + a.Srv().Store.User().InvalidateProfileCacheForUser(userId) - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: userId, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } func (a *App) InvalidateCacheForUserTeams(userId string) { a.InvalidateCacheForUserTeamsSkipClusterSend(userId) - a.Srv.Store.Team().InvalidateAllTeamIdsForUser(userId) + a.Srv().Store.Team().InvalidateAllTeamIdsForUser(userId) - if a.Cluster != nil { + if a.Cluster() != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: userId, } - a.Cluster.SendClusterMessage(msg) + a.Cluster().SendClusterMessage(msg) } } func (a *App) InvalidateCacheForUserSkipClusterSend(userId string) { - a.Srv.Store.Channel().InvalidateAllChannelMembersForUser(userId) + a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(userId) hub := a.GetHubForUserId(userId) if hub != nil { @@ -306,7 +306,7 @@ func (a *App) InvalidateCacheForUserTeamsSkipClusterSend(userId string) { } func (a *App) InvalidateCacheForWebhook(webhookId string) { - a.Srv.Store.Webhook().InvalidateWebhookCache(webhookId) + a.Srv().Store.Webhook().InvalidateWebhookCache(webhookId) } func (a *App) InvalidateWebConnSessionCacheForUser(userId string) { @@ -406,7 +406,7 @@ func (h *Hub) Start() { conns := connections.ForUser(webCon.UserId) if len(conns) == 0 { - h.app.Srv.Go(func() { + h.app.Srv().Go(func() { h.app.SetStatusOffline(webCon.UserId, false) }) } else { @@ -417,7 +417,7 @@ func (h *Hub) Start() { } } if h.app.IsUserAway(latestActivity) { - h.app.Srv.Go(func() { + h.app.Srv().Go(func() { h.app.SetStatusLastActivityAt(webCon.UserId, latestActivity) }) } diff --git a/app/web_hub_test.go b/app/web_hub_test.go index aa5faff1b0..ef0083b00e 100644 --- a/app/web_hub_test.go +++ b/app/web_hub_test.go @@ -77,7 +77,7 @@ func TestHubStopRaceCondition(t *testing.T) { wc1 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) defer wc1.Close() - hub := th.App.Srv.Hubs[0] + hub := th.App.Srv().Hubs[0] th.App.HubStop() time.Sleep(5 * time.Second) diff --git a/app/webhook.go b/app/webhook.go index f3ee891516..22f80125d9 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -32,7 +32,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m return nil } - hooks, err := a.Srv.Store.Webhook().GetOutgoingByTeam(team.Id, -1, -1) + hooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(team.Id, -1, -1) if err != nil { return err } @@ -79,7 +79,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m TriggerWord: triggerWord, FileIds: strings.Join(post.FileIds, ","), } - a.Srv.Go(func(hook *model.OutgoingWebhook) func() { + a.Srv().Go(func(hook *model.OutgoingWebhook) func() { return func() { a.TriggerWebhook(payload, hook, post, channel) } @@ -104,7 +104,7 @@ func (a *App) TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model. // Get the callback URL by index to properly capture it for the go func url := hook.CallbackURLs[i] - a.Srv.Go(func() { + a.Srv().Go(func() { webhookResp, err := a.doOutgoingWebhookRequest(url, body, contentType) if err != nil { mlog.Error("Event POST failed.", mlog.Err(err)) @@ -154,7 +154,7 @@ func (a *App) doOutgoingWebhookRequest(url string, body io.Reader, contentType s req.Header.Set("Content-Type", contentType) req.Header.Set("Accept", "application/json") - resp, err := a.HTTPService.MakeClient(false).Do(req) + resp, err := a.HTTPService().MakeClient(false).Do(req) if err != nil { return nil, err } @@ -257,7 +257,7 @@ func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, ove return nil, err } - if metrics := a.Metrics; metrics != nil { + if metrics := a.Metrics(); metrics != nil { metrics.IncrementWebhookPost() } @@ -323,7 +323,7 @@ func (a *App) CreateIncomingWebhookForChannel(creatorId string, channel *model.C return nil, model.NewAppError("CreateIncomingWebhookForChannel", "api.incoming_webhook.invalid_username.app_error", nil, "", http.StatusBadRequest) } - return a.Srv.Store.Webhook().SaveIncoming(hook) + return a.Srv().Store.Webhook().SaveIncoming(hook) } func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { @@ -349,7 +349,7 @@ func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) updatedHook.TeamId = oldHook.TeamId updatedHook.DeleteAt = oldHook.DeleteAt - newWebhook, err := a.Srv.Store.Webhook().UpdateIncoming(updatedHook) + newWebhook, err := a.Srv().Store.Webhook().UpdateIncoming(updatedHook) if err != nil { return nil, err } @@ -362,7 +362,7 @@ func (a *App) DeleteIncomingWebhook(hookId string) *model.AppError { return model.NewAppError("DeleteIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if err := a.Srv.Store.Webhook().DeleteIncoming(hookId, model.GetMillis()); err != nil { + if err := a.Srv().Store.Webhook().DeleteIncoming(hookId, model.GetMillis()); err != nil { return err } @@ -376,7 +376,7 @@ func (a *App) GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model. return nil, model.NewAppError("GetIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetIncoming(hookId, true) + return a.Srv().Store.Webhook().GetIncoming(hookId, true) } func (a *App) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { @@ -388,7 +388,7 @@ func (a *App) GetIncomingWebhooksForTeamPageByUser(teamId string, userId string, return nil, model.NewAppError("GetIncomingWebhooksForTeamPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetIncomingByTeamByUser(teamId, userId, page*perPage, perPage) + return a.Srv().Store.Webhook().GetIncomingByTeamByUser(teamId, userId, page*perPage, perPage) } func (a *App) GetIncomingWebhooksPageByUser(userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { @@ -396,7 +396,7 @@ func (a *App) GetIncomingWebhooksPageByUser(userId string, page, perPage int) ([ return nil, model.NewAppError("GetIncomingWebhooksPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetIncomingListByUser(userId, page*perPage, perPage) + return a.Srv().Store.Webhook().GetIncomingListByUser(userId, page*perPage, perPage) } func (a *App) GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { @@ -409,7 +409,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } if len(hook.ChannelId) != 0 { - channel, errCh := a.Srv.Store.Channel().Get(hook.ChannelId, true) + channel, errCh := a.Srv().Store.Channel().Get(hook.ChannelId, true) if errCh != nil { return nil, errCh } @@ -425,7 +425,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin return nil, model.NewAppError("CreateOutgoingWebhook", "api.webhook.create_outgoing.triggers.app_error", nil, "", http.StatusBadRequest) } - if allHooks, err := a.Srv.Store.Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1); err != nil { + if allHooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1); err != nil { return nil, err } else { @@ -439,7 +439,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } } - webhook, err := a.Srv.Store.Webhook().SaveOutgoing(hook) + webhook, err := a.Srv().Store.Webhook().SaveOutgoing(hook) if err != nil { return nil, err } @@ -469,7 +469,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) return nil, model.NewAppError("UpdateOutgoingWebhook", "api.webhook.create_outgoing.triggers.app_error", nil, "", http.StatusInternalServerError) } - allHooks, err := a.Srv.Store.Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1) + allHooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1) if err != nil { return nil, err } @@ -489,7 +489,7 @@ func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) updatedHook.TeamId = oldHook.TeamId updatedHook.UpdateAt = model.GetMillis() - return a.Srv.Store.Webhook().UpdateOutgoing(updatedHook) + return a.Srv().Store.Webhook().UpdateOutgoing(updatedHook) } func (a *App) GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model.AppError) { @@ -497,7 +497,7 @@ func (a *App) GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model. return nil, model.NewAppError("GetOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetOutgoing(hookId) + return a.Srv().Store.Webhook().GetOutgoing(hookId) } func (a *App) GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { @@ -509,7 +509,7 @@ func (a *App) GetOutgoingWebhooksPageByUser(userId string, page, perPage int) ([ return nil, model.NewAppError("GetOutgoingWebhooksPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetOutgoingListByUser(userId, page*perPage, perPage) + return a.Srv().Store.Webhook().GetOutgoingListByUser(userId, page*perPage, perPage) } func (a *App) GetOutgoingWebhooksForChannelPageByUser(channelId string, userId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { @@ -517,7 +517,7 @@ func (a *App) GetOutgoingWebhooksForChannelPageByUser(channelId string, userId s return nil, model.NewAppError("GetOutgoingWebhooksForChannelPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetOutgoingByChannelByUser(channelId, userId, page*perPage, perPage) + return a.Srv().Store.Webhook().GetOutgoingByChannelByUser(channelId, userId, page*perPage, perPage) } func (a *App) GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { @@ -529,7 +529,7 @@ func (a *App) GetOutgoingWebhooksForTeamPageByUser(teamId string, userId string, return nil, model.NewAppError("GetOutgoingWebhooksForTeamPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().GetOutgoingByTeamByUser(teamId, userId, page*perPage, perPage) + return a.Srv().Store.Webhook().GetOutgoingByTeamByUser(teamId, userId, page*perPage, perPage) } func (a *App) DeleteOutgoingWebhook(hookId string) *model.AppError { @@ -537,7 +537,7 @@ func (a *App) DeleteOutgoingWebhook(hookId string) *model.AppError { return model.NewAppError("DeleteOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - return a.Srv.Store.Webhook().DeleteOutgoing(hookId, model.GetMillis()) + return a.Srv().Store.Webhook().DeleteOutgoing(hookId, model.GetMillis()) } func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { @@ -547,7 +547,7 @@ func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.Out hook.Token = model.NewId() - return a.Srv.Store.Webhook().UpdateOutgoing(hook) + return a.Srv().Store.Webhook().UpdateOutgoing(hook) } func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *model.AppError { @@ -557,7 +557,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq hchan := make(chan store.StoreResult, 1) go func() { - webhook, err := a.Srv.Store.Webhook().GetIncoming(hookId, true) + webhook, err := a.Srv().Store.Webhook().GetIncoming(hookId, true) hchan <- store.StoreResult{Data: webhook, Err: err} close(hchan) }() @@ -583,7 +583,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv.Store.User().Get(hook.UserId) + user, err := a.Srv().Store.User().Get(hook.UserId) uchan <- store.StoreResult{Data: user, Err: err} close(uchan) }() @@ -607,7 +607,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq if len(channelName) != 0 { if channelName[0] == '@' { - if result, err := a.Srv.Store.User().GetByUsername(channelName[1:]); err != nil { + if result, err := a.Srv().Store.User().GetByUsername(channelName[1:]); err != nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.user.app_error", nil, "err="+err.Message, http.StatusBadRequest) } else { if ch, err := a.GetOrCreateDirectChannel(hook.UserId, result.Id); err != nil { @@ -619,21 +619,21 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq } else if channelName[0] == '#' { cchan = make(chan store.StoreResult, 1) go func() { - chnn, chnnErr := a.Srv.Store.Channel().GetByName(hook.TeamId, channelName[1:], true) + chnn, chnnErr := a.Srv().Store.Channel().GetByName(hook.TeamId, channelName[1:], true) cchan <- store.StoreResult{Data: chnn, Err: chnnErr} close(cchan) }() } else { cchan = make(chan store.StoreResult, 1) go func() { - chnn, chnnErr := a.Srv.Store.Channel().GetByName(hook.TeamId, channelName, true) + chnn, chnnErr := a.Srv().Store.Channel().GetByName(hook.TeamId, channelName, true) cchan <- store.StoreResult{Data: chnn, Err: chnnErr} close(cchan) }() } } else { var err *model.AppError - channel, err = a.Srv.Store.Channel().Get(hook.ChannelId, true) + channel, err = a.Srv().Store.Channel().Get(hook.ChannelId, true) if err != nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.channel.app_error", nil, "err="+err.Message, err.StatusCode) } @@ -691,7 +691,7 @@ func (a *App) CreateCommandWebhook(commandId string, args *model.CommandArgs) (* ParentId: args.ParentId, } - return a.Srv.Store.CommandWebhook().Save(hook) + return a.Srv().Store.CommandWebhook().Save(hook) } func (a *App) HandleCommandWebhook(hookId string, response *model.CommandResponse) *model.AppError { @@ -699,12 +699,12 @@ func (a *App) HandleCommandWebhook(hookId string, response *model.CommandRespons return model.NewAppError("HandleCommandWebhook", "web.command_webhook.parse.app_error", nil, "", http.StatusBadRequest) } - hook, err := a.Srv.Store.CommandWebhook().Get(hookId) + hook, err := a.Srv().Store.CommandWebhook().Get(hookId) if err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.invalid.app_error", nil, "err="+err.Message, err.StatusCode) } - cmd, err := a.Srv.Store.Command().Get(hook.CommandId) + cmd, err := a.Srv().Store.Command().Get(hook.CommandId) if err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.command.app_error", nil, "err="+err.Message, http.StatusBadRequest) } @@ -717,7 +717,7 @@ func (a *App) HandleCommandWebhook(hookId string, response *model.CommandRespons ParentId: hook.ParentId, } - if err = a.Srv.Store.CommandWebhook().TryUse(hook.Id, 5); err != nil { + if err = a.Srv().Store.CommandWebhook().TryUse(hook.Id, 5); err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.invalid.app_error", nil, "err="+err.Message, err.StatusCode) } diff --git a/app/webhook_test.go b/app/webhook_test.go index 6f0bd4b4b1..1af4ca3805 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -709,9 +709,9 @@ func TestDoOutgoingWebhookRequest(t *testing.T) { defer server.Close() defer close(releaseHandler) - th.App.HTTPService.(*httpservice.HTTPServiceImpl).RequestTimeout = 500 * time.Millisecond + th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = 500 * time.Millisecond defer func() { - th.App.HTTPService.(*httpservice.HTTPServiceImpl).RequestTimeout = httpservice.RequestTimeout + th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = httpservice.RequestTimeout }() _, err := th.App.doOutgoingWebhookRequest(server.URL, strings.NewReader(""), "application/json") diff --git a/app/websocket_router.go b/app/websocket_router.go index bdb758c0b2..236fca56de 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -54,7 +54,7 @@ func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketReque return } - wr.app.Srv.Go(func() { + wr.app.Srv().Go(func() { wr.app.SetStatusOnline(session.UserId, false) wr.app.UpdateLastActivityAtIfNeeded(*session) }) diff --git a/cmd/mattermost/commands/channel.go b/cmd/mattermost/commands/channel.go index 7ed1a908f7..cd8e428912 100644 --- a/cmd/mattermost/commands/channel.go +++ b/cmd/mattermost/commands/channel.go @@ -266,7 +266,7 @@ func removeUserFromChannel(a *app.App, channel *model.Channel, user *model.User, } func removeAllUsersFromChannel(a *app.App, channel *model.Channel) { - if err := a.Srv.Store.Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { + if err := a.Srv().Store.Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { CommandPrintErrorln("Unable to remove all users from " + channel.Name + ". Error: " + err.Error()) } } @@ -314,7 +314,7 @@ func archiveChannelsCmdF(command *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if err := a.Srv.Store.Channel().Delete(channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store.Channel().Delete(channel.Id, model.GetMillis()); err != nil { CommandPrintErrorln("Unable to archive channel '" + channel.Name + "' error: " + err.Error()) } } @@ -409,7 +409,7 @@ func moveChannel(a *app.App, team *model.Team, channel *model.Channel, user *mod for _, webhook := range incomingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if _, err := a.Srv.Store.Webhook().UpdateIncoming(webhook); err != nil { + if _, err := a.Srv().Store.Webhook().UpdateIncoming(webhook); err != nil { CommandPrintErrorln("Failed to move incoming webhook '" + webhook.Id + "' to new team.") } } @@ -422,7 +422,7 @@ func moveChannel(a *app.App, team *model.Team, channel *model.Channel, user *mod for _, webhook := range outgoingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if _, err := a.Srv.Store.Webhook().UpdateOutgoing(webhook); err != nil { + if _, err := a.Srv().Store.Webhook().UpdateOutgoing(webhook); err != nil { CommandPrintErrorln("Failed to move outgoing webhook '" + webhook.Id + "' to new team.") } } @@ -445,7 +445,7 @@ func listChannelsCmdF(command *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find team '" + args[i] + "'") continue } - if channels, chanErr := a.Srv.Store.Channel().GetAll(team.Id); chanErr != nil { + if channels, chanErr := a.Srv().Store.Channel().GetAll(team.Id); chanErr != nil { CommandPrintErrorln("Unable to list channels for '" + args[i] + "'") } else { for _, channel := range channels { @@ -477,7 +477,7 @@ func restoreChannelsCmdF(command *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if err := a.Srv.Store.Channel().SetDeleteAt(channel.Id, 0, model.GetMillis()); err != nil { + if err := a.Srv().Store.Channel().SetDeleteAt(channel.Id, 0, model.GetMillis()); err != nil { CommandPrintErrorln("Unable to restore channel '" + args[i] + "'") } } diff --git a/cmd/mattermost/commands/channel_test.go b/cmd/mattermost/commands/channel_test.go index aabf9553a8..8fc29081c3 100644 --- a/cmd/mattermost/commands/channel_test.go +++ b/cmd/mattermost/commands/channel_test.go @@ -236,7 +236,7 @@ func TestModifyChannel(t *testing.T) { channel2 := th.CreatePrivateChannel() th.CheckCommand(t, "channel", "modify", "--public", th.BasicTeam.Name+":"+channel1.Name, "--username", th.BasicUser2.Email) - res, err := th.App.Srv.Store.Channel().Get(channel1.Id, false) + res, err := th.App.Srv().Store.Channel().Get(channel1.Id, false) require.Nil(t, err) assert.Equal(t, model.CHANNEL_OPEN, res.Type) @@ -247,7 +247,7 @@ func TestModifyChannel(t *testing.T) { pchannel2 := th.CreatePublicChannel() th.CheckCommand(t, "channel", "modify", "--private", th.BasicTeam.Name+":"+pchannel1.Name, "--username", th.BasicUser2.Email) - res, err = th.App.Srv.Store.Channel().Get(pchannel1.Id, false) + res, err = th.App.Srv().Store.Channel().Get(pchannel1.Id, false) require.Nil(t, err) assert.Equal(t, model.CHANNEL_PRIVATE, res.Type) diff --git a/cmd/mattermost/commands/channelargs.go b/cmd/mattermost/commands/channelargs.go index ce65aaba1f..03a42e5b33 100644 --- a/cmd/mattermost/commands/channelargs.go +++ b/cmd/mattermost/commands/channelargs.go @@ -43,7 +43,7 @@ func getChannelFromChannelArg(a *app.App, channelArg string) *model.Channel { return nil } - if result, err := a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, channelPart, true); err == nil { + if result, err := a.Srv().Store.Channel().GetByNameIncludeDeleted(team.Id, channelPart, true); err == nil { channel = result } else { fmt.Println(err.Error()) @@ -51,7 +51,7 @@ func getChannelFromChannelArg(a *app.App, channelArg string) *model.Channel { } if channel == nil { - if ch, errCh := a.Srv.Store.Channel().Get(channelPart, true); errCh == nil { + if ch, errCh := a.Srv().Store.Channel().Get(channelPart, true); errCh == nil { channel = ch } } diff --git a/cmd/mattermost/commands/command.go b/cmd/mattermost/commands/command.go index 3697135fbf..87ad6347d9 100644 --- a/cmd/mattermost/commands/command.go +++ b/cmd/mattermost/commands/command.go @@ -257,7 +257,7 @@ func listCommandCmdF(command *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find team '" + args[i] + "'") continue } - commands, err := a.Srv.Store.Command().GetByTeam(team.Id) + commands, err := a.Srv().Store.Command().GetByTeam(team.Id) if err != nil { CommandPrintErrorln("Unable to list commands for '" + args[i] + "'") continue diff --git a/cmd/mattermost/commands/commandargs.go b/cmd/mattermost/commands/commandargs.go index fe497f2bf6..7c5aa658b3 100644 --- a/cmd/mattermost/commands/commandargs.go +++ b/cmd/mattermost/commands/commandargs.go @@ -47,14 +47,14 @@ func getCommandFromCommandArg(a *app.App, commandArg string) *model.Command { return nil } var err *model.AppError - command, err = a.Srv.Store.Command().GetByTrigger(team.Id, commandPart) + command, err = a.Srv().Store.Command().GetByTrigger(team.Id, commandPart) if err != nil { fmt.Println(err.Error()) } } if command == nil { - command, _ = a.Srv.Store.Command().Get(commandPart) + command, _ = a.Srv().Store.Command().Get(commandPart) } return command diff --git a/cmd/mattermost/commands/export.go b/cmd/mattermost/commands/export.go index a5fdb579c9..fc9a8b8113 100644 --- a/cmd/mattermost/commands/export.go +++ b/cmd/mattermost/commands/export.go @@ -117,7 +117,7 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error { return errors.New("timeoutSeconds must be a positive integer") } - if messageExportI := a.MessageExport; messageExportI != nil { + if messageExportI := a.MessageExport(); messageExportI != nil { ctx := context.Background() if timeoutSeconds > 0 { var cancel context.CancelFunc @@ -152,11 +152,11 @@ func buildExportCmdF(format string) func(command *cobra.Command, args []string) return errors.New("exportFrom must be a positive integer") } - if a.MessageExport == nil { + if a.MessageExport() == nil { CommandPrettyPrintln("MessageExport feature not available") } - err2 := a.MessageExport.RunExport(format, startTime) + err2 := a.MessageExport().RunExport(format, startTime) if err2 != nil { return err2 } diff --git a/cmd/mattermost/commands/integrity.go b/cmd/mattermost/commands/integrity.go index 160bdf58bc..e132d5f48d 100644 --- a/cmd/mattermost/commands/integrity.go +++ b/cmd/mattermost/commands/integrity.go @@ -83,7 +83,7 @@ func integrityCmdF(command *cobra.Command, args []string) error { } verboseFlag, _ := command.Flags().GetBool("verbose") - results := a.Srv.Store.CheckIntegrity() + results := a.Srv().Store.CheckIntegrity() for result := range results { if result.Err != nil { fmt.Fprintf(os.Stderr, "%s\n", result.Err.Error()) diff --git a/cmd/mattermost/commands/jobserver.go b/cmd/mattermost/commands/jobserver.go index 03441b95d6..bf548b2369 100644 --- a/cmd/mattermost/commands/jobserver.go +++ b/cmd/mattermost/commands/jobserver.go @@ -47,12 +47,12 @@ func jobserverCmdF(command *cobra.Command, args []string) error { defer mlog.Info("Stopped Mattermost job server") if !noJobs { - a.Srv.Jobs.StartWorkers() - defer a.Srv.Jobs.StopWorkers() + a.Srv().Jobs.StartWorkers() + defer a.Srv().Jobs.StopWorkers() } if !noSchedule { - a.Srv.Jobs.StartSchedulers() - defer a.Srv.Jobs.StopSchedulers() + a.Srv().Jobs.StartSchedulers() + defer a.Srv().Jobs.StopSchedulers() } signalChan := make(chan os.Signal, 1) diff --git a/cmd/mattermost/commands/ldap.go b/cmd/mattermost/commands/ldap.go index d07367522e..305db32c16 100644 --- a/cmd/mattermost/commands/ldap.go +++ b/cmd/mattermost/commands/ldap.go @@ -45,7 +45,7 @@ func ldapSyncCmdF(command *cobra.Command, args []string) error { } defer a.Shutdown() - if ldapI := a.Ldap; ldapI != nil { + if ldapI := a.Ldap(); ldapI != nil { job, err := ldapI.StartSynchronizeJob(true) if err != nil || job.Status == model.JOB_STATUS_ERROR || job.Status == model.JOB_STATUS_CANCELED { CommandPrintErrorln("ERROR: AD/LDAP Synchronization please check the server logs") @@ -65,7 +65,7 @@ func ldapIdMigrateCmdF(command *cobra.Command, args []string) error { defer a.Shutdown() toAttribute := args[0] - if ldapI := a.Ldap; ldapI != nil { + if ldapI := a.Ldap(); ldapI != nil { if err := ldapI.MigrateIDAttribute(toAttribute); err != nil { CommandPrintErrorln("ERROR: AD/LDAP IdAttribute migration failed! Error: " + err.Error()) } else { diff --git a/cmd/mattermost/commands/reset.go b/cmd/mattermost/commands/reset.go index df49bc8f06..a9494e24ac 100644 --- a/cmd/mattermost/commands/reset.go +++ b/cmd/mattermost/commands/reset.go @@ -46,7 +46,7 @@ func resetCmdF(command *cobra.Command, args []string) error { } } - a.Srv.Store.DropAllTables() + a.Srv().Store.DropAllTables() CommandPrettyPrintln("Database successfully reset") return nil diff --git a/cmd/mattermost/commands/roles_test.go b/cmd/mattermost/commands/roles_test.go index 69201b9c74..928704d666 100644 --- a/cmd/mattermost/commands/roles_test.go +++ b/cmd/mattermost/commands/roles_test.go @@ -16,13 +16,13 @@ func TestAssignRole(t *testing.T) { th.CheckCommand(t, "roles", "system_admin", th.BasicUser.Email) - user, err := th.App.Srv.Store.User().GetByEmail(th.BasicUser.Email) + user, err := th.App.Srv().Store.User().GetByEmail(th.BasicUser.Email) require.Nil(t, err) assert.Equal(t, "system_user system_admin", user.Roles) th.CheckCommand(t, "roles", "member", th.BasicUser.Email) - user, err = th.App.Srv.Store.User().GetByEmail(th.BasicUser.Email) + user, err = th.App.Srv().Store.User().GetByEmail(th.BasicUser.Email) require.Nil(t, err) assert.Equal(t, "system_user", user.Roles) diff --git a/cmd/mattermost/commands/team_test.go b/cmd/mattermost/commands/team_test.go index eeefb36231..9c3b5c48ba 100644 --- a/cmd/mattermost/commands/team_test.go +++ b/cmd/mattermost/commands/team_test.go @@ -65,7 +65,7 @@ func TestLeaveTeam(t *testing.T) { require.False(t, found, "profile should not be on team") - teams, err := th.App.Srv.Store.Team().GetTeamsByUserId(th.BasicUser.Id) + teams, err := th.App.Srv().Store.Team().GetTeamsByUserId(th.BasicUser.Id) require.Nil(t, err) require.Equal(t, 0, len(teams), "Shouldn't be in team") } diff --git a/cmd/mattermost/commands/teamargs.go b/cmd/mattermost/commands/teamargs.go index ab44754ecc..de9d1e0bb9 100644 --- a/cmd/mattermost/commands/teamargs.go +++ b/cmd/mattermost/commands/teamargs.go @@ -19,11 +19,11 @@ func getTeamsFromTeamArgs(a *app.App, teamArgs []string) []*model.Team { func getTeamFromTeamArg(a *app.App, teamArg string) *model.Team { var team *model.Team - team, err := a.Srv.Store.Team().GetByName(teamArg) + team, err := a.Srv().Store.Team().GetByName(teamArg) if err != nil { var t *model.Team - if t, err = a.Srv.Store.Team().Get(teamArg); err == nil { + if t, err = a.Srv().Store.Team().Get(teamArg); err == nil { team = t } } diff --git a/cmd/mattermost/commands/test.go b/cmd/mattermost/commands/test.go index 96c452a941..bfc5404eb9 100644 --- a/cmd/mattermost/commands/test.go +++ b/cmd/mattermost/commands/test.go @@ -53,13 +53,13 @@ func webClientTestsCmdF(command *cobra.Command, args []string) error { defer a.Shutdown() utils.InitTranslations(a.Config().LocalizationSettings) - serverErr := a.Srv.Start() + serverErr := a.Srv().Start() if serverErr != nil { return serverErr } - api4.Init(a, a.Srv.AppOptions, a.Srv.Router) - wsapi.Init(a, a.Srv.WebSocketRouter) + api4.Init(a, a.Srv().AppOptions, a.Srv().Router) + wsapi.Init(a, a.Srv().WebSocketRouter) a.UpdateConfig(setupClientTests) runWebClientTests() @@ -74,13 +74,13 @@ func serverForWebClientTestsCmdF(command *cobra.Command, args []string) error { defer a.Shutdown() utils.InitTranslations(a.Config().LocalizationSettings) - serverErr := a.Srv.Start() + serverErr := a.Srv().Start() if serverErr != nil { return serverErr } - api4.Init(a, a.Srv.AppOptions, a.Srv.Router) - wsapi.Init(a, a.Srv.WebSocketRouter) + api4.Init(a, a.Srv().AppOptions, a.Srv().Router) + wsapi.Init(a, a.Srv().WebSocketRouter) a.UpdateConfig(setupClientTests) c := make(chan os.Signal, 1) diff --git a/cmd/mattermost/commands/user.go b/cmd/mattermost/commands/user.go index 899d995ce9..cc5c197966 100644 --- a/cmd/mattermost/commands/user.go +++ b/cmd/mattermost/commands/user.go @@ -513,7 +513,7 @@ func botToUser(command *cobra.Command, args []string, a *app.App) error { } } - appErr = a.Srv.Store.Bot().PermanentDelete(user.Id) + appErr = a.Srv().Store.Bot().PermanentDelete(user.Id) if appErr != nil { return fmt.Errorf("Unable to delete bot. Error: %s", appErr.Error()) } @@ -624,7 +624,7 @@ func resetUserPasswordCmdF(command *cobra.Command, args []string) error { } password := args[1] - if err := a.Srv.Store.User().UpdatePassword(user.Id, model.HashPassword(password)); err != nil { + if err := a.Srv().Store.User().UpdatePassword(user.Id, model.HashPassword(password)); err != nil { return err } @@ -809,7 +809,7 @@ func migrateAuthToLdapCmdF(command *cobra.Command, args []string) error { forceFlag, _ := command.Flags().GetBool("force") dryRunFlag, _ := command.Flags().GetBool("dryRun") - if migrate := a.AccountMigration; migrate != nil { + if migrate := a.AccountMigration(); migrate != nil { if err := migrate.MigrateToLdap(fromAuth, matchField, forceFlag, dryRunFlag); err != nil { return errors.New("Error while migrating users: " + err.Error()) } @@ -865,7 +865,7 @@ func migrateAuthToSamlCmdF(command *cobra.Command, args []string) error { fromAuth = "" } - if migrate := a.AccountMigration; migrate != nil { + if migrate := a.AccountMigration(); migrate != nil { if err := migrate.MigrateToSaml(fromAuth, matches, autoFlag, dryRunFlag); err != nil { return errors.New("Error while migrating users: " + err.Error()) } @@ -894,7 +894,7 @@ func verifyUserCmdF(command *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find user '" + args[i] + "'") continue } - if _, err := a.Srv.Store.User().VerifyEmail(user.Id, user.Email); err != nil { + if _, err := a.Srv().Store.User().VerifyEmail(user.Id, user.Email); err != nil { CommandPrintErrorln("Unable to verify '" + args[i] + "' email. Error: " + err.Error()) } } diff --git a/cmd/mattermost/commands/user_test.go b/cmd/mattermost/commands/user_test.go index 3222a36ab3..7820e66ebb 100644 --- a/cmd/mattermost/commands/user_test.go +++ b/cmd/mattermost/commands/user_test.go @@ -46,7 +46,7 @@ func TestCreateUserWithoutTeam(t *testing.T) { th.CheckCommand(t, "user", "create", "--email", email, "--password", "mypassword1", "--username", username) - user, err := th.App.Srv.Store.User().GetByEmail(email) + user, err := th.App.Srv().Store.User().GetByEmail(email) require.Nil(t, err) require.Equal(t, email, user.Email) @@ -81,10 +81,10 @@ func TestChangeUserEmail(t *testing.T) { newEmail := model.NewId() + "@mattermost-test.com" th.CheckCommand(t, "user", "email", th.BasicUser.Username, newEmail) - _, err := th.App.Srv.Store.User().GetByEmail(th.BasicUser.Email) + _, err := th.App.Srv().Store.User().GetByEmail(th.BasicUser.Email) require.NotNil(t, err, "should've updated to the new email") - user, err := th.App.Srv.Store.User().GetByEmail(newEmail) + user, err := th.App.Srv().Store.User().GetByEmail(newEmail) require.Nil(t, err) require.Equal(t, user.Email, newEmail, "should've updated to the new email") @@ -114,7 +114,7 @@ func TestDeleteUserBotUser(t *testing.T) { defer th.TearDown() th.CheckCommand(t, "user", "delete", th.BasicUser.Username, "--confirm") - _, err := th.App.Srv.Store.User().Get(th.BasicUser.Id) + _, err := th.App.Srv().Store.User().Get(th.BasicUser.Id) require.Error(t, err) // Make a bot @@ -123,16 +123,16 @@ func TestDeleteUserBotUser(t *testing.T) { Description: "Delete me!", OwnerId: model.NewId(), } - user, err := th.App.Srv.Store.User().Save(model.UserFromBot(bot)) + user, err := th.App.Srv().Store.User().Save(model.UserFromBot(bot)) require.Nil(t, err) bot.UserId = user.Id - bot, err = th.App.Srv.Store.Bot().Save(bot) + bot, err = th.App.Srv().Store.Bot().Save(bot) require.Nil(t, err) th.CheckCommand(t, "user", "delete", bot.Username, "--confirm") - _, err = th.App.Srv.Store.User().Get(user.Id) + _, err = th.App.Srv().Store.User().Get(user.Id) require.Error(t, err) - _, err = th.App.Srv.Store.Bot().Get(user.Id, true) + _, err = th.App.Srv().Store.Bot().Get(user.Id, true) require.Error(t, err) } @@ -153,7 +153,7 @@ func TestConvertUser(t *testing.T) { t.Run("Convert to bot from username", func(t *testing.T) { th.CheckCommand(t, "user", "convert", th.BasicUser.Username, "anotherinvaliduser", "--bot") - _, err := th.App.Srv.Store.Bot().Get(th.BasicUser.Id, false) + _, err := th.App.Srv().Store.Bot().Get(th.BasicUser.Id, false) require.Nil(t, err) }) @@ -173,13 +173,13 @@ func TestConvertUser(t *testing.T) { err := th.RunCommand(t, "user", "convert", th.BasicUser.Username, "--user", "--password", "password") require.Nil(t, err) - _, err = th.App.Srv.Store.Bot().Get(th.BasicUser.Id, false) + _, err = th.App.Srv().Store.Bot().Get(th.BasicUser.Id, false) require.NotNil(t, err) }) t.Run("Convert to bot from email", func(t *testing.T) { th.CheckCommand(t, "user", "convert", th.BasicUser2.Email, "--bot") - _, err := th.App.Srv.Store.Bot().Get(th.BasicUser2.Id, false) + _, err := th.App.Srv().Store.Bot().Get(th.BasicUser2.Id, false) require.Nil(t, err) }) @@ -195,10 +195,10 @@ func TestConvertUser(t *testing.T) { "--system_admin") require.Nil(t, err) - _, err = th.App.Srv.Store.Bot().Get(th.BasicUser2.Id, false) + _, err = th.App.Srv().Store.Bot().Get(th.BasicUser2.Id, false) require.NotNil(t, err) - user, appErr := th.App.Srv.Store.User().Get(th.BasicUser2.Id) + user, appErr := th.App.Srv().Store.User().Get(th.BasicUser2.Id) require.Nil(t, appErr) require.Equal(t, "newusername", user.Username) require.Equal(t, "valid@email.com", user.Email) diff --git a/cmd/mattermost/commands/userargs.go b/cmd/mattermost/commands/userargs.go index 5114073717..b2b48ec3d9 100644 --- a/cmd/mattermost/commands/userargs.go +++ b/cmd/mattermost/commands/userargs.go @@ -18,17 +18,17 @@ func getUsersFromUserArgs(a *app.App, userArgs []string) []*model.User { } func getUserFromUserArg(a *app.App, userArg string) *model.User { - user, _ := a.Srv.Store.User().GetByEmail(userArg) + user, _ := a.Srv().Store.User().GetByEmail(userArg) if user == nil { var err *model.AppError - if user, err = a.Srv.Store.User().GetByUsername(userArg); err == nil { + if user, err = a.Srv().Store.User().GetByUsername(userArg); err == nil { return user } } if user == nil { - user, _ = a.Srv.Store.User().Get(userArg) + user, _ = a.Srv().Store.User().Get(userArg) } return user diff --git a/cmd/mattermost/commands/version.go b/cmd/mattermost/commands/version.go index dd96928147..a502fc7d6c 100644 --- a/cmd/mattermost/commands/version.go +++ b/cmd/mattermost/commands/version.go @@ -36,5 +36,5 @@ func printVersion(a *app.App) { CommandPrintln("Build Date: " + model.BuildDate) CommandPrintln("Build Hash: " + model.BuildHash) CommandPrintln("Build Enterprise Ready: " + model.BuildEnterpriseReady) - CommandPrintln("DB Version: " + a.Srv.Store.GetCurrentSchemaVersion()) + CommandPrintln("DB Version: " + a.Srv().Store.GetCurrentSchemaVersion()) } diff --git a/cmd/mattermost/commands/webhook.go b/cmd/mattermost/commands/webhook.go index 20c0a61890..549654940a 100644 --- a/cmd/mattermost/commands/webhook.go +++ b/cmd/mattermost/commands/webhook.go @@ -114,13 +114,13 @@ func listWebhookCmdF(command *cobra.Command, args []string) error { // Fetch all hooks with a very large limit so we get them all. incomingResult := make(chan store.StoreResult, 1) go func() { - incomingHooks, err := app.Srv.Store.Webhook().GetIncomingByTeam(team.Id, 0, 100000000) + incomingHooks, err := app.Srv().Store.Webhook().GetIncomingByTeam(team.Id, 0, 100000000) incomingResult <- store.StoreResult{Data: incomingHooks, Err: err} close(incomingResult) }() outgoingResult := make(chan store.StoreResult, 1) go func() { - outgoingHooks, err := app.Srv.Store.Webhook().GetOutgoingByTeam(team.Id, 0, 100000000) + outgoingHooks, err := app.Srv().Store.Webhook().GetOutgoingByTeam(team.Id, 0, 100000000) outgoingResult <- store.StoreResult{Data: outgoingHooks, Err: err} close(outgoingResult) }() diff --git a/go.mod b/go.mod index be31f9f9d4..a75d5f0e10 100644 --- a/go.mod +++ b/go.mod @@ -41,7 +41,7 @@ require ( github.com/icrowley/fake v0.0.0-20180203215853-4178557ae428 github.com/jaytaylor/html2text v0.0.0-20190408195923-01ec452cbe43 github.com/jmoiron/sqlx v1.2.0 - github.com/jonboulle/clockwork v0.1.0 // indirect + github.com/jonboulle/clockwork v0.1.0 github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/lib/pq v1.3.0 github.com/magiconair/properties v1.8.1 // indirect @@ -66,6 +66,7 @@ require ( github.com/pelletier/go-toml v1.6.0 // indirect github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.4.0 + github.com/reflog/struct2interface v0.3.0 // indirect github.com/rs/cors v1.7.0 github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7 github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd @@ -92,10 +93,11 @@ require ( golang.org/x/crypto v0.0.0-20200117160349-530e935923ad golang.org/x/image v0.0.0-20200119044424-58c23975cae1 golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f // indirect + golang.org/x/mod v0.2.0 // indirect golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect golang.org/x/text v0.3.2 - golang.org/x/tools v0.0.0-20200128002243-345141a36859 + golang.org/x/tools v0.0.0-20200211205636-11eff242d136 google.golang.org/genproto v0.0.0-20200128133413-58ce757ed39b // indirect google.golang.org/grpc v1.26.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect diff --git a/go.sum b/go.sum index 8881f707f6..308470fdd3 100644 --- a/go.sum +++ b/go.sum @@ -384,6 +384,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLkt8= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/reflog/struct2interface v0.3.0 h1:6vLzQ9LxPUy+0hV+aSLN17cPEWdEmR+EjD1cBsoLdPA= +github.com/reflog/struct2interface v0.3.0/go.mod h1:Hj4XSqbzQyLswqmKfmGqzOlh4xCRPSl27779XT9TPN4= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= @@ -498,7 +500,10 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f h1:J5lckAjkw6qYlOZNj90mLYNTEKDvWeuc1yieZ8qUzUE= golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -582,10 +587,12 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200128002243-345141a36859 h1:xIszjAtlVeHg9hhv6Zhntvwqowji1k2rrgoOhj/aaKw= -golang.org/x/tools v0.0.0-20200128002243-345141a36859/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200206050830-dd0d5d485177/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200211205636-11eff242d136 h1:yFWeDNMOyrJIQNtXrNR5smCrv+Y4IN6Ul42TzAXxd9k= +golang.org/x/tools v0.0.0-20200211205636-11eff242d136/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index 8cdf9d75ed..e7a3b73b3b 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -75,7 +75,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { Type: model.TEAM_OPEN, } - createdTeam, err := c.App.Srv.Store.Team().Save(team) + createdTeam, err := c.App.Srv().Store.Team().Save(team) if err != nil { c.Err = err return @@ -101,8 +101,8 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { return } - c.App.Srv.Store.User().VerifyEmail(user.Id, user.Email) - c.App.Srv.Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam) + c.App.Srv().Store.User().VerifyEmail(user.Id, user.Email) + c.App.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam) userID = user.Id @@ -151,9 +151,9 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { } } -func getChannelID(a *app.App, channelname string, teamid string, userid string) (string, bool) { +func getChannelID(a app.AppIface, channelname string, teamid string, userid string) (string, bool) { // Grab all the channels - channels, err := a.Srv.Store.Channel().GetChannels(teamid, userid, false) + channels, err := a.Srv().Store.Channel().GetChannels(teamid, userid, false) if err != nil { mlog.Debug("Unable to get channels") return "", false diff --git a/migrations/advanced_permissions_phase_2.go b/migrations/advanced_permissions_phase_2.go index 1f29ad161d..1630c9f243 100644 --- a/migrations/advanced_permissions_phase_2.go +++ b/migrations/advanced_permissions_phase_2.go @@ -71,7 +71,7 @@ func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bo if progress.CurrentTable == "TeamMembers" { // Run a TeamMembers migration batch. - if result, err := worker.app.Srv.Store.Team().MigrateTeamMembers(progress.LastTeamId, progress.LastUserId); err != nil { + if result, err := worker.app.Srv().Store.Team().MigrateTeamMembers(progress.LastTeamId, progress.LastUserId); err != nil { return false, progress.ToJson(), err } else { if result == nil { @@ -86,7 +86,7 @@ func (worker *Worker) runAdvancedPermissionsPhase2Migration(lastDone string) (bo } } else if progress.CurrentTable == "ChannelMembers" { // Run a ChannelMembers migration batch. - if data, err := worker.app.Srv.Store.Channel().MigrateChannelMembers(progress.LastChannelId, progress.LastUserId); err != nil { + if data, err := worker.app.Srv().Store.Channel().MigrateChannelMembers(progress.LastChannelId, progress.LastUserId); err != nil { return false, progress.ToJson(), err } else { if data == nil { diff --git a/migrations/helper_test.go b/migrations/helper_test.go index 71ed284b88..5eb3e812f1 100644 --- a/migrations/helper_test.go +++ b/migrations/helper_test.go @@ -65,7 +65,7 @@ func setupTestHelper(enterprise bool) *TestHelper { th.App.DoAppMigrations() - th.App.Srv.Store.MarkSystemRanUnitTests() + th.App.Srv().Store.MarkSystemRanUnitTests() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -267,14 +267,14 @@ func (me *TestHelper) ResetRoleMigration() { } func (me *TestHelper) DeleteAllJobsByTypeAndMigrationKey(jobType string, migrationKey string) { - jobs, err := me.App.Srv.Store.Job().GetAllByType(model.JOB_TYPE_MIGRATIONS) + jobs, err := me.App.Srv().Store.Job().GetAllByType(model.JOB_TYPE_MIGRATIONS) if err != nil { panic(err) } for _, job := range jobs { if key, ok := job.Data[JOB_DATA_KEY_MIGRATION]; ok && key == migrationKey { - if _, err = me.App.Srv.Store.Job().Delete(job.Id); err != nil { + if _, err = me.App.Srv().Store.Job().Delete(job.Id); err != nil { panic(err) } } diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 15c36382df..e2227c5abd 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -24,7 +24,7 @@ func TestGetMigrationState(t *testing.T) { th.DeleteAllJobsByTypeAndMigrationKey(model.JOB_TYPE_MIGRATIONS, migrationKey) // Test with no job yet. - state, job, err := GetMigrationState(migrationKey, th.App.Srv.Store) + state, job, err := GetMigrationState(migrationKey, th.App.Srv().Store) assert.Nil(t, err) assert.Nil(t, job) assert.Equal(t, "unscheduled", state) @@ -34,15 +34,15 @@ func TestGetMigrationState(t *testing.T) { Name: migrationKey, Value: "true", } - err = th.App.Srv.Store.System().Save(&system) + err = th.App.Srv().Store.System().Save(&system) assert.Nil(t, err) - state, job, err = GetMigrationState(migrationKey, th.App.Srv.Store) + state, job, err = GetMigrationState(migrationKey, th.App.Srv().Store) assert.Nil(t, err) assert.Nil(t, job) assert.Equal(t, "completed", state) - _, err = th.App.Srv.Store.System().PermanentDeleteByName(migrationKey) + _, err = th.App.Srv().Store.System().PermanentDeleteByName(migrationKey) assert.Nil(t, err) // Test with a job scheduled in "pending" state. @@ -56,10 +56,10 @@ func TestGetMigrationState(t *testing.T) { Type: model.JOB_TYPE_MIGRATIONS, } - j1, err = th.App.Srv.Store.Job().Save(j1) + j1, err = th.App.Srv().Store.Job().Save(j1) require.Nil(t, err) - state, job, err = GetMigrationState(migrationKey, th.App.Srv.Store) + state, job, err = GetMigrationState(migrationKey, th.App.Srv().Store) assert.Nil(t, err) assert.Equal(t, j1.Id, job.Id) assert.Equal(t, "in_progress", state) @@ -75,10 +75,10 @@ func TestGetMigrationState(t *testing.T) { Type: model.JOB_TYPE_MIGRATIONS, } - j2, err = th.App.Srv.Store.Job().Save(j2) + j2, err = th.App.Srv().Store.Job().Save(j2) require.Nil(t, err) - state, job, err = GetMigrationState(migrationKey, th.App.Srv.Store) + state, job, err = GetMigrationState(migrationKey, th.App.Srv().Store) assert.Nil(t, err) assert.Equal(t, j2.Id, job.Id) assert.Equal(t, "in_progress", state) @@ -94,10 +94,10 @@ func TestGetMigrationState(t *testing.T) { Type: model.JOB_TYPE_MIGRATIONS, } - j3, err = th.App.Srv.Store.Job().Save(j3) + j3, err = th.App.Srv().Store.Job().Save(j3) require.Nil(t, err) - state, job, err = GetMigrationState(migrationKey, th.App.Srv.Store) + state, job, err = GetMigrationState(migrationKey, th.App.Srv().Store) assert.Nil(t, err) assert.Equal(t, j3.Id, job.Id) assert.Equal(t, "unscheduled", state) diff --git a/migrations/scheduler.go b/migrations/scheduler.go index 12bcc6f33c..807f19e2ff 100644 --- a/migrations/scheduler.go +++ b/migrations/scheduler.go @@ -51,7 +51,7 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las // Work through the list of migrations in order. Schedule the first one that isn't done (assuming it isn't in progress already). for _, key := range MakeMigrationsList() { - state, job, err := GetMigrationState(key, scheduler.App.Srv.Store) + state, job, err := GetMigrationState(key, scheduler.App.Srv().Store) if err != nil { mlog.Error("Failed to determine status of migration: ", mlog.String("scheduler", scheduler.Name()), mlog.String("migration_key", key), mlog.String("error", err.Error())) return nil, nil @@ -61,10 +61,10 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las // Check the migration job isn't wedged. if job != nil && job.LastActivityAt < model.GetMillis()-MIGRATION_JOB_WEDGED_TIMEOUT_MILLISECONDS && job.CreateAt < model.GetMillis()-MIGRATION_JOB_WEDGED_TIMEOUT_MILLISECONDS { mlog.Warn("Job appears to be wedged. Rescheduling another instance.", mlog.String("scheduler", scheduler.Name()), mlog.String("wedged_job_id", job.Id), mlog.String("migration_key", key)) - if err := scheduler.App.Srv.Jobs.SetJobError(job, nil); err != nil { + if err := scheduler.App.Srv().Jobs.SetJobError(job, nil); err != nil { mlog.Error("Worker: Failed to set job error", mlog.String("scheduler", scheduler.Name()), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) } - return scheduler.createJob(key, job, scheduler.App.Srv.Store) + return scheduler.createJob(key, job, scheduler.App.Srv().Store) } return nil, nil @@ -77,7 +77,7 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las if state == MIGRATION_STATE_UNSCHEDULED { mlog.Debug("Scheduling a new job for migration.", mlog.String("scheduler", scheduler.Name()), mlog.String("migration_key", key)) - return scheduler.createJob(key, job, scheduler.App.Srv.Store) + return scheduler.createJob(key, job, scheduler.App.Srv().Store) } mlog.Error("Unknown migration state. Not doing anything.", mlog.String("migration_state", state)) @@ -102,7 +102,7 @@ func (scheduler *Scheduler) createJob(migrationKey string, lastJob *model.Job, s JOB_DATA_KEY_MIGRATION_LAST_DONE: lastDone, } - if job, err := scheduler.App.Srv.Jobs.CreateJob(model.JOB_TYPE_MIGRATIONS, data); err != nil { + if job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_MIGRATIONS, data); err != nil { return nil, err } else { return job, nil diff --git a/migrations/worker.go b/migrations/worker.go index 42f5e80c86..1b20f13c98 100644 --- a/migrations/worker.go +++ b/migrations/worker.go @@ -33,7 +33,7 @@ func (m *MigrationsJobInterfaceImpl) MakeWorker() model.Worker { stop: make(chan bool, 1), stopped: make(chan bool, 1), jobs: make(chan model.Job), - jobServer: m.App.Srv.Jobs, + jobServer: m.App.Srv().Jobs, app: m.App, } @@ -83,7 +83,7 @@ func (worker *Worker) DoJob(job *model.Job) { cancelCtx, cancelCancelWatcher := context.WithCancel(context.Background()) cancelWatcherChan := make(chan interface{}, 1) - go worker.app.Srv.Jobs.CancellationWatcher(cancelCtx, job.Id, cancelWatcherChan) + go worker.app.Srv().Jobs.CancellationWatcher(cancelCtx, job.Id, cancelWatcherChan) defer cancelCancelWatcher() @@ -111,7 +111,7 @@ func (worker *Worker) DoJob(job *model.Job) { return } else { job.Data[JOB_DATA_KEY_MIGRATION_LAST_DONE] = progress - if err := worker.app.Srv.Jobs.UpdateInProgressJobData(job); err != nil { + if err := worker.app.Srv().Jobs.UpdateInProgressJobData(job); err != nil { mlog.Error("Worker: Failed to update migration status data for job", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) return @@ -122,20 +122,20 @@ func (worker *Worker) DoJob(job *model.Job) { } func (worker *Worker) setJobSuccess(job *model.Job) { - if err := worker.app.Srv.Jobs.SetJobSuccess(job); err != nil { + if err := worker.app.Srv().Jobs.SetJobSuccess(job); err != nil { mlog.Error("Worker: Failed to set success for job", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) } } func (worker *Worker) setJobError(job *model.Job, appError *model.AppError) { - if err := worker.app.Srv.Jobs.SetJobError(job, appError); err != nil { + if err := worker.app.Srv().Jobs.SetJobError(job, appError); err != nil { mlog.Error("Worker: Failed to set job error", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) } } func (worker *Worker) setJobCanceled(job *model.Job) { - if err := worker.app.Srv.Jobs.SetJobCanceled(job); err != nil { + if err := worker.app.Srv().Jobs.SetJobCanceled(job); err != nil { mlog.Error("Worker: Failed to mark job as canceled", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) } } @@ -157,7 +157,7 @@ func (worker *Worker) runMigration(key string, lastDone string) (bool, string, * } if done { - if saveErr := worker.app.Srv.Store.System().Save(&model.System{Name: key, Value: "true"}); saveErr != nil { + if saveErr := worker.app.Srv().Store.System().Save(&model.System{Name: key, Value: "true"}); saveErr != nil { return false, "", saveErr } } diff --git a/plugin/interface_generator/main.go b/plugin/interface_generator/main.go index 2c90cea73c..fbe8cb00e5 100644 --- a/plugin/interface_generator/main.go +++ b/plugin/interface_generator/main.go @@ -263,7 +263,7 @@ func (g *hooksRPCClient) {{.Name}}{{funcStyle .Params}} {{funcStyle .Return}} { _returns := &{{.Name | obscure}}Returns{} if g.implemented[{{.Name}}Id] { if err := g.client.Call("Plugin.{{.Name}}", _args, _returns); err != nil { - g.log.Error("RPC call {{.Name}} to plugin failed.", mlog.Err(err)) + g.Log().Error("RPC call {{.Name}} to plugin failed.", mlog.Err(err)) } } {{ if .Return }} return {{destruct "_returns." .Return}} {{ end }} diff --git a/plugin/scheduler/scheduler.go b/plugin/scheduler/scheduler.go index 45c57251e5..72919bb15e 100644 --- a/plugin/scheduler/scheduler.go +++ b/plugin/scheduler/scheduler.go @@ -41,7 +41,7 @@ func (scheduler *Scheduler) NextScheduleTime(cfg *model.Config, now time.Time, p func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, lastSuccessfulJob *model.Job) (*model.Job, *model.AppError) { mlog.Debug("Scheduling Job", mlog.String("scheduler", scheduler.Name())) - job, err := scheduler.App.Srv.Jobs.CreateJob(model.JOB_TYPE_PLUGINS, nil) + job, err := scheduler.App.Srv().Jobs.CreateJob(model.JOB_TYPE_PLUGINS, nil) if err != nil { return nil, err } diff --git a/plugin/scheduler/worker.go b/plugin/scheduler/worker.go index 99e769d19e..6ace11be77 100644 --- a/plugin/scheduler/worker.go +++ b/plugin/scheduler/worker.go @@ -25,7 +25,7 @@ func (m *PluginsJobInterfaceImpl) MakeWorker() model.Worker { stop: make(chan bool, 1), stopped: make(chan bool, 1), jobs: make(chan model.Job), - jobServer: m.App.Srv.Jobs, + jobServer: m.App.Srv().Jobs, app: m.App, } @@ -84,14 +84,14 @@ func (worker *Worker) DoJob(job *model.Job) { } func (worker *Worker) setJobSuccess(job *model.Job) { - if err := worker.app.Srv.Jobs.SetJobSuccess(job); err != nil { + if err := worker.app.Srv().Jobs.SetJobSuccess(job); err != nil { mlog.Error("Worker: Failed to set success for job", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) } } func (worker *Worker) setJobError(job *model.Job, appError *model.AppError) { - if err := worker.app.Srv.Jobs.SetJobError(job, appError); err != nil { + if err := worker.app.Srv().Jobs.SetJobError(job, appError); err != nil { mlog.Error("Worker: Failed to set job error", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) } } diff --git a/vendor/golang.org/x/tools/go/analysis/doc.go b/vendor/golang.org/x/tools/go/analysis/doc.go index 8fa4a8531b..ea56b724e8 100644 --- a/vendor/golang.org/x/tools/go/analysis/doc.go +++ b/vendor/golang.org/x/tools/go/analysis/doc.go @@ -1,6 +1,6 @@ /* -The analysis package defines the interface between a modular static +Package analysis defines the interface between a modular static analysis and an analysis driver program. diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go index 9cf186605f..8dcd8bbb71 100644 --- a/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go @@ -344,7 +344,7 @@ func (p *parser) expectKeyword(keyword string) { // PackageId = string_lit . // -func (p *parser) parsePackageId() string { +func (p *parser) parsePackageID() string { id, err := strconv.Unquote(p.expect(scanner.String)) if err != nil { p.error(err) @@ -384,7 +384,7 @@ func (p *parser) parseDotIdent() string { // func (p *parser) parseQualifiedName() (id, name string) { p.expect('@') - id = p.parsePackageId() + id = p.parsePackageID() p.expect('.') // Per rev f280b8a485fd (10/2/2013), qualified names may be used for anonymous fields. if p.tok == '?' { @@ -696,7 +696,7 @@ func (p *parser) parseInterfaceType(parent *types.Package) types.Type { // Complete requires the type's embedded interfaces to be fully defined, // but we do not define any - return types.NewInterface(methods, nil).Complete() + return newInterface(methods, nil).Complete() } // ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . @@ -785,7 +785,7 @@ func (p *parser) parseType(parent *types.Package) types.Type { func (p *parser) parseImportDecl() { p.expectKeyword("import") name := p.parsePackageName() - p.getPkg(p.parsePackageId(), name) + p.getPkg(p.parsePackageID(), name) } // int_lit = [ "+" | "-" ] { "0" ... "9" } . diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 3089711321..fc0b28ecf9 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -16,6 +16,7 @@ import ( "path" "path/filepath" "reflect" + "sort" "strconv" "strings" "sync" @@ -420,6 +421,8 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse return nil, err } seen := make(map[string]*jsonPackage) + pkgs := make(map[string]*Package) + additionalErrors := make(map[string][]Error) // Decode the JSON and convert it to Package form. var response driverResponse for dec := json.NewDecoder(buf); dec.More(); { @@ -460,11 +463,62 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse } if old, found := seen[p.ImportPath]; found { - if !reflect.DeepEqual(p, old) { - return nil, fmt.Errorf("internal error: go list gives conflicting information for package %v", p.ImportPath) + // If one version of the package has an error, and the other doesn't, assume + // that this is a case where go list is reporting a fake dependency variant + // of the imported package: When a package tries to invalidly import another + // package, go list emits a variant of the imported package (with the same + // import path, but with an error on it, and the package will have a + // DepError set on it). An example of when this can happen is for imports of + // main packages: main packages can not be imported, but they may be + // separately matched and listed by another pattern. + // See golang.org/issue/36188 for more details. + + // The plan is that eventually, hopefully in Go 1.15, the error will be + // reported on the importing package rather than the duplicate "fake" + // version of the imported package. Once all supported versions of Go + // have the new behavior this logic can be deleted. + // TODO(matloob): delete the workaround logic once all supported versions of + // Go return the errors on the proper package. + + // There should be exactly one version of a package that doesn't have an + // error. + if old.Error == nil && p.Error == nil { + if !reflect.DeepEqual(p, old) { + return nil, fmt.Errorf("internal error: go list gives conflicting information for package %v", p.ImportPath) + } + continue } - // skip the duplicate - continue + + // Determine if this package's error needs to be bubbled up. + // This is a hack, and we expect for go list to eventually set the error + // on the package. + if old.Error != nil { + var errkind string + if strings.Contains(old.Error.Err, "not an importable package") { + errkind = "not an importable package" + } else if strings.Contains(old.Error.Err, "use of internal package") && strings.Contains(old.Error.Err, "not allowed") { + errkind = "use of internal package not allowed" + } + if errkind != "" { + if len(old.Error.ImportStack) < 2 { + return nil, fmt.Errorf(`internal error: go list gave a %q error with an import stack with fewer than two elements`, errkind) + } + importingPkg := old.Error.ImportStack[len(old.Error.ImportStack)-2] + additionalErrors[importingPkg] = append(additionalErrors[importingPkg], Error{ + Pos: old.Error.Pos, + Msg: old.Error.Err, + Kind: ListError, + }) + } + } + + // Make sure that if there's a version of the package without an error, + // that's the one reported to the user. + if old.Error == nil { + continue + } + + // This package will replace the old one at the end of the loop. } seen[p.ImportPath] = p @@ -563,8 +617,18 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse }) } + pkgs[pkg.ID] = pkg + } + + for id, errs := range additionalErrors { + if p, ok := pkgs[id]; ok { + p.Errors = append(p.Errors, errs...) + } + } + for _, pkg := range pkgs { response.Packages = append(response.Packages, pkg) } + sort.Slice(response.Packages, func(i, j int) bool { return response.Packages[i].ID < response.Packages[j].ID }) return &response, nil } @@ -699,7 +763,12 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, !strings.ContainsRune("!\"#$%&'()*,:;<=>?[\\]^`{|}\uFFFD", r) } if len(stderr.String()) > 0 && strings.HasPrefix(stderr.String(), "# ") { - if strings.HasPrefix(strings.TrimLeftFunc(stderr.String()[len("# "):], isPkgPathRune), "\n") { + msg := stderr.String()[len("# "):] + if strings.HasPrefix(strings.TrimLeftFunc(msg, isPkgPathRune), "\n") { + return stdout, nil + } + // Treat pkg-config errors as a special case (golang.org/issue/36770). + if strings.HasPrefix(msg, "pkg-config") { return stdout, nil } } diff --git a/vendor/golang.org/x/tools/go/packages/golist_overlay.go b/vendor/golang.org/x/tools/go/packages/golist_overlay.go index c6925c87be..7974a6c9bb 100644 --- a/vendor/golang.org/x/tools/go/packages/golist_overlay.go +++ b/vendor/golang.org/x/tools/go/packages/golist_overlay.go @@ -7,6 +7,7 @@ import ( "go/token" "os" "path/filepath" + "sort" "strconv" "strings" ) @@ -34,7 +35,23 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif // potentially modifying the transitive set of dependencies). var overlayAddsImports bool - for opath, contents := range state.cfg.Overlay { + // If both a package and its test package are created by the overlay, we + // need the real package first. Process all non-test files before test + // files, and make the whole process deterministic while we're at it. + var overlayFiles []string + for opath := range state.cfg.Overlay { + overlayFiles = append(overlayFiles, opath) + } + sort.Slice(overlayFiles, func(i, j int) bool { + iTest := strings.HasSuffix(overlayFiles[i], "_test.go") + jTest := strings.HasSuffix(overlayFiles[j], "_test.go") + if iTest != jTest { + return !iTest // non-tests are before tests. + } + return overlayFiles[i] < overlayFiles[j] + }) + for _, opath := range overlayFiles { + contents := state.cfg.Overlay[opath] base := filepath.Base(opath) dir := filepath.Dir(opath) var pkg *Package // if opath belongs to both a package and its test variant, this will be the test variant @@ -64,14 +81,8 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif testVariantOf = p continue nextPackage } + // We must have already seen the package of which this is a test variant. if pkg != nil && p != pkg && pkg.PkgPath == p.PkgPath { - // If we've already seen the test variant, - // make sure to label which package it is a test variant of. - if hasTestFiles(pkg) { - testVariantOf = p - continue nextPackage - } - // If we have already seen the package of which this is a test variant. if hasTestFiles(p) { testVariantOf = pkg } diff --git a/vendor/modules.txt b/vendor/modules.txt index 9273f76df0..81aeed4a49 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -335,7 +335,7 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/tools v0.0.0-20200128002243-345141a36859 +# golang.org/x/tools v0.0.0-20200207224406-61798d64f025 golang.org/x/tools/go/analysis golang.org/x/tools/go/analysis/passes/inspect golang.org/x/tools/go/ast/astutil diff --git a/web/context.go b/web/context.go index 39dc8dbe24..69fcb7948f 100644 --- a/web/context.go +++ b/web/context.go @@ -16,7 +16,7 @@ import ( ) type Context struct { - App *app.App + App app.AppIface Log *mlog.Logger Params *Params Err *model.AppError @@ -24,20 +24,20 @@ type Context struct { } func (c *Context) LogAudit(extraInfo string) { - audit := &model.Audit{UserId: c.App.Session.UserId, IpAddress: c.App.IpAddress, Action: c.App.Path, ExtraInfo: extraInfo, SessionId: c.App.Session.Id} - if err := c.App.Srv.Store.Audit().Save(audit); err != nil { + audit := &model.Audit{UserId: c.App.Session().UserId, IpAddress: c.App.IpAddress(), Action: c.App.Path(), ExtraInfo: extraInfo, SessionId: c.App.Session().Id} + if err := c.App.Srv().Store.Audit().Save(audit); err != nil { c.LogError(err) } } func (c *Context) LogAuditWithUserId(userId, extraInfo string) { - if len(c.App.Session.UserId) > 0 { - extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.App.Session.UserId) + if len(c.App.Session().UserId) > 0 { + extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.App.Session().UserId) } - audit := &model.Audit{UserId: userId, IpAddress: c.App.IpAddress, Action: c.App.Path, ExtraInfo: extraInfo, SessionId: c.App.Session.Id} - if err := c.App.Srv.Store.Audit().Save(audit); err != nil { + audit := &model.Audit{UserId: userId, IpAddress: c.App.IpAddress(), Action: c.App.Path(), ExtraInfo: extraInfo, SessionId: c.App.Session().Id} + if err := c.App.Srv().Store.Audit().Save(audit); err != nil { c.LogError(err) } } @@ -45,7 +45,7 @@ func (c *Context) LogAuditWithUserId(userId, extraInfo string) { func (c *Context) LogError(err *model.AppError) { // Filter out 404s, endless reconnects and browser compatibility errors if err.StatusCode == http.StatusNotFound || - (c.App.Path == "/api/v3/users/websocket" && err.StatusCode == http.StatusUnauthorized) || + (c.App.Path() == "/api/v3/users/websocket" && err.StatusCode == http.StatusUnauthorized) || err.Id == "web.check_browser_compatibility.app_error" { c.LogDebug(err) } else { @@ -82,19 +82,19 @@ func (c *Context) LogDebug(err *model.AppError) { } func (c *Context) IsSystemAdmin() bool { - return c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM) + return c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) } func (c *Context) SessionRequired() { if !*c.App.Config().ServiceSettings.EnableUserAccessTokens && - c.App.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN && - c.App.Session.Props[model.SESSION_PROP_IS_BOT] != model.SESSION_PROP_IS_BOT_VALUE { + c.App.Session().Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN && + c.App.Session().Props[model.SESSION_PROP_IS_BOT] != model.SESSION_PROP_IS_BOT_VALUE { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized) return } - if len(c.App.Session.UserId) == 0 { + if len(c.App.Session().UserId) == 0 { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserRequired", http.StatusUnauthorized) return } @@ -107,11 +107,11 @@ func (c *Context) MfaRequired() { } // OAuth integrations are excepted - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { return } - if user, err := c.App.GetUser(c.App.Session.UserId); err != nil { + if user, err := c.App.GetUser(c.App.Session().UserId); err != nil { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "MfaRequired", http.StatusUnauthorized) return } else { @@ -127,7 +127,7 @@ func (c *Context) MfaRequired() { // Special case to let user get themself subpath, _ := utils.GetSubpathFromConfig(c.App.Config()) - if c.App.Path == path.Join(subpath, "/api/v4/users/me") { + if c.App.Path() == path.Join(subpath, "/api/v4/users/me") { return } @@ -174,7 +174,7 @@ func (c *Context) SetCommandNotFoundError() { } func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool { - metrics := c.App.Metrics + metrics := c.App.Metrics() if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 { if et == etag { w.Header().Set(model.HEADER_ETAG_SERVER, etag) @@ -224,7 +224,7 @@ func (c *Context) RequireUserId() *Context { } if c.Params.UserId == model.ME { - c.Params.UserId = c.App.Session.UserId + c.Params.UserId = c.App.Session().UserId } if len(c.Params.UserId) != 26 { diff --git a/web/handlers.go b/web/handlers.go index 59a396f7ec..8dbd5ccd74 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -82,14 +82,16 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.App = app.New( h.GetGlobalAppOptions()..., ) - c.App.T, _ = utils.GetTranslationsAndLocale(w, r) - c.App.RequestId = requestID - c.App.IpAddress = utils.GetIpAddress(r, c.App.Config().ServiceSettings.TrustedProxyIPHeader) - c.App.UserAgent = r.UserAgent() - c.App.AcceptLanguage = r.Header.Get("Accept-Language") + + t, _ := utils.GetTranslationsAndLocale(w, r) + c.App.SetT(t) + c.App.SetRequestId(requestID) + c.App.SetIpAddress(utils.GetIpAddress(r, c.App.Config().ServiceSettings.TrustedProxyIPHeader)) + c.App.SetUserAgent(r.UserAgent()) + c.App.SetAcceptLanguage(r.Header.Get("Accept-Language")) + c.App.SetPath(r.URL.Path) c.Params = ParamsFromRequest(r) - c.App.Path = r.URL.Path - c.Log = c.App.Log + c.Log = c.App.Log() // Set the max request body size to be equal to MaxFileSize. // Ideally, non-file request bodies should be smaller than file request bodies, @@ -103,7 +105,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { siteURLHeader := app.GetProtocol(r) + "://" + r.Host + subpath c.SetSiteURLHeader(siteURLHeader) - w.Header().Set(model.HEADER_REQUEST_ID, c.App.RequestId) + w.Header().Set(model.HEADER_REQUEST_ID, c.App.RequestId()) w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.License() != nil)) if *c.App.Config().ServiceSettings.TLSStrictTransport { @@ -142,22 +144,22 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } else if !session.IsOAuth && tokenLocation == app.TokenLocationQueryString { c.Err = model.NewAppError("ServeHTTP", "api.context.token_provided.app_error", nil, "token="+token, http.StatusUnauthorized) } else { - c.App.Session = *session + c.App.SetSession(session) } // Rate limit by UserID - if c.App.Srv.RateLimiter != nil && c.App.Srv.RateLimiter.UserIdRateLimit(c.App.Session.UserId, w) { + if c.App.Srv().RateLimiter != nil && c.App.Srv().RateLimiter.UserIdRateLimit(c.App.Session().UserId, w) { return } h.checkCSRFToken(c, r, token, tokenLocation, session) } - c.Log = c.App.Log.With( - mlog.String("path", c.App.Path), - mlog.String("request_id", c.App.RequestId), - mlog.String("ip_addr", c.App.IpAddress), - mlog.String("user_id", c.App.Session.UserId), + c.Log = c.App.Log().With( + mlog.String("path", c.App.Path()), + mlog.String("request_id", c.App.RequestId()), + mlog.String("ip_addr", c.App.IpAddress()), + mlog.String("user_id", c.App.Session().UserId), mlog.String("method", r.Method), ) @@ -169,7 +171,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.MfaRequired() } - if c.Err == nil && h.DisableWhenBusy && c.App.Srv.Busy.IsBusy() { + if c.Err == nil && h.DisableWhenBusy && c.App.Srv().Busy.IsBusy() { c.SetServerBusyError() } @@ -180,7 +182,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Handle errors that have occurred if c.Err != nil { c.Err.Translate(c.App.T) - c.Err.RequestId = c.App.RequestId + c.Err.RequestId = c.App.RequestId() if c.Err.Id == "api.context.session_expired.app_error" { c.LogInfo(c.Err) @@ -212,18 +214,18 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { utils.RenderWebAppError(c.App.Config(), w, r, c.Err, c.App.AsymmetricSigningKey()) } - if c.App.Metrics != nil { - c.App.Metrics.IncrementHttpError() + if c.App.Metrics() != nil { + c.App.Metrics().IncrementHttpError() } } - if c.App.Metrics != nil { - c.App.Metrics.IncrementHttpRequest() + if c.App.Metrics() != nil { + c.App.Metrics().IncrementHttpRequest() if r.URL.Path != model.API_URL_SUFFIX+"/websocket" { elapsed := float64(time.Since(now)) / float64(time.Second) - c.App.Metrics.ObserveHttpRequestDuration(elapsed) - c.App.Metrics.ObserveApiEndpointDuration(h.HandlerName, r.Method, elapsed) + c.App.Metrics().ObserveHttpRequestDuration(elapsed) + c.App.Metrics().ObserveApiEndpointDuration(h.HandlerName, r.Method, elapsed) } } } @@ -267,7 +269,7 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke } if !csrfCheckPassed { - c.App.Session = model.Session{} + c.App.SetSession(&model.Session{}) c.Err = model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token+" Appears to be a CSRF attempt", http.StatusUnauthorized) } } diff --git a/web/handlers_test.go b/web/handlers_test.go index 74c7351884..e2f1c822f6 100644 --- a/web/handlers_test.go +++ b/web/handlers_test.go @@ -422,7 +422,7 @@ func TestCheckCSRFToken(t *testing.T) { c := &Context{ App: th.App, - Log: th.App.Log, + Log: th.App.Log(), } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) @@ -457,7 +457,7 @@ func TestCheckCSRFToken(t *testing.T) { c := &Context{ App: th.App, - Log: th.App.Log, + Log: th.App.Log(), } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) diff --git a/web/oauth.go b/web/oauth.go index 8c5f47e086..264ea280c1 100644 --- a/web/oauth.go +++ b/web/oauth.go @@ -51,7 +51,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session.IsOAuth { + if c.App.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted access by oauth app" return @@ -59,7 +59,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("attempt") - redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.App.Session.UserId, authRequest) + redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.App.Session().UserId, authRequest) if err != nil { c.Err = err @@ -80,7 +80,7 @@ func deauthorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - err := c.App.DeauthorizeOAuthAppForUser(c.App.Session.UserId, clientId) + err := c.App.DeauthorizeOAuthAppForUser(c.App.Session().UserId, clientId) if err != nil { c.Err = err return @@ -119,7 +119,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { } // here we should check if the user is logged in - if len(c.App.Session.UserId) == 0 { + if len(c.App.Session().UserId) == 0 { if loginHint == model.USER_AUTH_SERVICE_SAML { http.Redirect(w, r, c.GetSiteURLHeader()+"/login/sso/saml?redirect_to="+url.QueryEscape(r.RequestURI), http.StatusFound) } else { @@ -136,14 +136,14 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { isAuthorized := false - if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.App.Session.UserId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, authRequest.ClientId); err == nil { + if _, err := c.App.GetPreferenceByCategoryAndNameForUser(c.App.Session().UserId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, authRequest.ClientId); err == nil { // when we support scopes we should check if the scopes match isAuthorized = true } // Automatically allow if the app is trusted if oauthApp.IsTrusted || isAuthorized { - redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.App.Session.UserId, authRequest) + redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.App.Session().UserId, authRequest) if err != nil { utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey()) diff --git a/web/oauth_test.go b/web/oauth_test.go index 63c8ef2ccc..7080bdfe71 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -336,7 +336,7 @@ func TestOAuthAccessToken(t *testing.T) { require.Nil(t, err) authData := &model.AuthData{ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], UserId: th.BasicUser.Id, Code: model.NewId(), ExpiresIn: -1} - _, err = th.App.Srv.Store.OAuth().SaveAuthData(authData) + _, err = th.App.Srv().Store.OAuth().SaveAuthData(authData) require.Nil(t, err) data.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE) @@ -473,7 +473,7 @@ func TestOAuthComplete(t *testing.T) { closeBody(r) } - _, err = th.App.Srv.Store.User().UpdateAuthData( + _, err = th.App.Srv().Store.User().UpdateAuthData( th.BasicUser.Id, model.SERVICE_GITLAB, &th.BasicUser.Email, th.BasicUser.Email, true) require.Nil(t, err) diff --git a/web/saml.go b/web/saml.go index e7bd23b2f7..59ff24ad91 100644 --- a/web/saml.go +++ b/web/saml.go @@ -18,7 +18,7 @@ func (w *Web) InitSaml() { } func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { - samlInterface := c.App.Saml + samlInterface := c.App.Saml() if samlInterface == nil { c.Err = model.NewAppError("loginWithSaml", "api.user.saml.not_available.app_error", nil, "", http.StatusFound) @@ -61,7 +61,7 @@ func loginWithSaml(c *Context, w http.ResponseWriter, r *http.Request) { } func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { - samlInterface := c.App.Saml + samlInterface := c.App.Saml() if samlInterface == nil { c.Err = model.NewAppError("completeSaml", "api.user.saml.not_available.app_error", nil, "", http.StatusFound) @@ -111,7 +111,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { case model.OAUTH_ACTION_SIGNUP: teamId := relayProps["team_id"] if len(teamId) > 0 { - c.App.Srv.Go(func() { + c.App.Srv().Go(func() { if err = c.App.AddUserToTeamByTeamId(teamId, user); err != nil { mlog.Error(err.Error()) } else { @@ -125,7 +125,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { return } c.LogAuditWithUserId(user.Id, "Revoked all sessions for user") - c.App.Srv.Go(func() { + c.App.Srv().Go(func() { if err = c.App.SendSignInChangeEmail(user.Email, strings.Title(model.USER_AUTH_SERVICE_SAML)+" SSO", user.Locale, c.App.GetSiteURL()); err != nil { mlog.Error(err.Error()) } diff --git a/web/unsupported_browser.go b/web/unsupported_browser.go index 5178821df8..6c9debbfdc 100644 --- a/web/unsupported_browser.go +++ b/web/unsupported_browser.go @@ -44,7 +44,7 @@ type SystemBrowser struct { MakeDefaultString string } -func renderUnsupportedBrowser(app *app.App, w http.ResponseWriter, r *http.Request) { +func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") page := utils.NewHTMLTemplate(app.HTMLTemplates(), "unsupported_browser") @@ -88,7 +88,7 @@ func renderUnsupportedBrowser(app *app.App, w http.ResponseWriter, r *http.Reque page.RenderToWriter(w) } -func renderMattermostAppMac(app *app.App) MattermostApp { +func renderMattermostAppMac(app app.AppIface) MattermostApp { return MattermostApp{ "/static/images/browser-icons/mac.png", app.T("web.error.unsupported_browser.download_the_app"), @@ -100,7 +100,7 @@ func renderMattermostAppMac(app *app.App) MattermostApp { } } -func renderMattermostAppWindows(app *app.App) MattermostApp { +func renderMattermostAppWindows(app app.AppIface) MattermostApp { return MattermostApp{ "/static/images/browser-icons/windows.svg", app.T("web.error.unsupported_browser.download_the_app"), @@ -112,7 +112,7 @@ func renderMattermostAppWindows(app *app.App) MattermostApp { } } -func renderBrowserChrome(app *app.App) Browser { +func renderBrowserChrome(app app.AppIface) Browser { return Browser{ "/static/images/browser-icons/chrome.svg", app.T("web.error.unsupported_browser.browser_title.chrome"), @@ -122,7 +122,7 @@ func renderBrowserChrome(app *app.App) Browser { } } -func renderBrowserFirefox(app *app.App) Browser { +func renderBrowserFirefox(app app.AppIface) Browser { return Browser{ "/static/images/browser-icons/firefox.svg", app.T("web.error.unsupported_browser.browser_title.firefox"), @@ -132,7 +132,7 @@ func renderBrowserFirefox(app *app.App) Browser { } } -func renderBrowserSafari(app *app.App) Browser { +func renderBrowserSafari(app app.AppIface) Browser { return Browser{ "/static/images/browser-icons/safari.svg", app.T("web.error.unsupported_browser.browser_title.safari"), @@ -142,7 +142,7 @@ func renderBrowserSafari(app *app.App) Browser { } } -func renderSystemBrowserEdge(app *app.App, r *http.Request) SystemBrowser { +func renderSystemBrowserEdge(app app.AppIface, r *http.Request) SystemBrowser { return SystemBrowser{ "/static/images/browser-icons/edge.svg", app.T("web.error.unsupported_browser.browser_title.edge"), diff --git a/web/web.go b/web/web.go index 278b0a8fe3..c0400eb60c 100644 --- a/web/web.go +++ b/web/web.go @@ -82,7 +82,7 @@ func IsApiCall(config configservice.ConfigService, r *http.Request) bool { return strings.HasPrefix(r.URL.Path, path.Join(subpath, "api")+"/") } -func IsWebhookCall(a *app.App, r *http.Request) bool { +func IsWebhookCall(a app.AppIface, r *http.Request) bool { subpath, _ := utils.GetSubpathFromConfig(a.Config()) return strings.HasPrefix(r.URL.Path, path.Join(subpath, "hooks")+"/") diff --git a/web/web_test.go b/web/web_test.go index 22cd796f67..ae2766d41a 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -26,7 +26,7 @@ var ApiClient *model.Client4 var URL string type TestHelper struct { - App *app.App + App app.AppIface Server *app.Server Web *Web @@ -75,12 +75,12 @@ func Setup(tb testing.TB) *TestHelper { }) web := New(s, s.AppOptions, s.Router) - URL = fmt.Sprintf("http://localhost:%v", a.Srv.ListenAddr.Port) + URL = fmt.Sprintf("http://localhost:%v", a.Srv().ListenAddr.Port) ApiClient = model.NewAPIv4Client(URL) a.DoAppMigrations() - a.Srv.Store.MarkSystemRanUnitTests() + a.Srv().Store.MarkSystemRanUnitTests() a.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true @@ -226,7 +226,7 @@ func TestPublicFilesRequest(t *testing.T) { defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) - env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log) + env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log()) require.NoError(t, err) pluginID := "com.mattermost.sample" diff --git a/web/webhook.go b/web/webhook.go index f589904777..1e33b367d3 100644 --- a/web/webhook.go +++ b/web/webhook.go @@ -33,7 +33,7 @@ func incomingWebhook(c *Context, w http.ResponseWriter, r *http.Request) { defer func() { if *c.App.Config().LogSettings.EnableWebhookDebugging { if c.Err != nil { - mlog.Debug("Incoming webhook received", mlog.String("webhook_id", id), mlog.String("request_id", c.App.RequestId), mlog.String("payload", incomingWebhookPayload.ToJson())) + mlog.Debug("Incoming webhook received", mlog.String("webhook_id", id), mlog.String("request_id", c.App.RequestId()), mlog.String("payload", incomingWebhookPayload.ToJson())) } } }() diff --git a/wsapi/user.go b/wsapi/user.go index b727e33519..45bd9a1302 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -13,7 +13,7 @@ func (api *API) InitUser() { } func (api *API) userTyping(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { - if api.App.Srv.Busy.IsBusy() { + if api.App.Srv().Busy.IsBusy() { // this is considered a non-critical service and will be disabled when server busy. return nil, NewServerBusyWebSocketError(req.Action) }