diff --git a/api4/api.go b/api4/api.go index f033824adbd..12aa721305b 100644 --- a/api4/api.go +++ b/api4/api.go @@ -11,7 +11,6 @@ import ( "github.com/mattermost/mattermost-server/v5/app" "github.com/mattermost/mattermost-server/v5/model" - "github.com/mattermost/mattermost-server/v5/services/configservice" "github.com/mattermost/mattermost-server/v5/web" ) @@ -136,16 +135,14 @@ type Routes struct { } type API struct { - ConfigService configservice.ConfigService - GetGlobalAppOptions app.AppOptionCreator - BaseRoutes *Routes + app app.AppIface + BaseRoutes *Routes } -func Init(configservice configservice.ConfigService, globalOptionsFunc app.AppOptionCreator, root *mux.Router) *API { +func Init(a app.AppIface, root *mux.Router) *API { api := &API{ - ConfigService: configservice, - GetGlobalAppOptions: globalOptionsFunc, - BaseRoutes: &Routes{}, + app: a, + BaseRoutes: &Routes{}, } api.BaseRoutes.Root = root @@ -301,11 +298,10 @@ func Init(configservice configservice.ConfigService, globalOptionsFunc app.AppOp return api } -func InitLocal(configservice configservice.ConfigService, globalOptionsFunc app.AppOptionCreator, root *mux.Router) *API { +func InitLocal(a app.AppIface, root *mux.Router) *API { api := &API{ - ConfigService: configservice, - GetGlobalAppOptions: globalOptionsFunc, - BaseRoutes: &Routes{}, + app: a, + BaseRoutes: &Routes{}, } api.BaseRoutes.Root = root @@ -396,7 +392,7 @@ func InitLocal(configservice configservice.ConfigService, globalOptionsFunc app. } func (api *API) Handle404(w http.ResponseWriter, r *http.Request) { - web.Handle404(api.ConfigService, w, r) + web.Handle404(api.app, w, r) } var ReturnStatusOK = web.ReturnStatusOK diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 33817725bdd..ee23132d650 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -22,6 +22,7 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock" @@ -41,6 +42,7 @@ type TestHelper struct { Server *app.Server ConfigStore *config.Store + Context *request.Context Client *model.Client4 BasicUser *model.User BasicUser2 *model.User @@ -127,6 +129,11 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent Server: s, ConfigStore: configStore, IncludeCacheLayer: includeCache, + Context: &request.Context{}, + } + + if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && searchEngine != nil { + searchEngine.BleveEngine = s.SearchEngine.BleveEngine } if searchEngine != nil { @@ -158,13 +165,15 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent panic(err) } - Init(th.Server, th.Server.AppOptions, th.App.Srv().Router) - InitLocal(th.Server, th.Server.AppOptions, th.App.Srv().LocalRouter) - web.New(th.Server, th.Server.AppOptions, th.App.Srv().Router) + Init(th.App, th.App.Srv().Router) + InitLocal(th.App, th.App.Srv().LocalRouter) + web.New(th.App, th.App.Srv().Router) wsapi.Init(th.App.Srv()) if enterprise { th.App.Srv().SetLicense(model.NewTestLicense()) + th.App.Srv().Jobs.InitWorkers() + th.App.Srv().Jobs.InitSchedulers() } else { th.App.Srv().SetLicense(nil) } @@ -189,8 +198,6 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent th.tempWorkspace = tempWorkspace } - th.App.InitServer() - return th } @@ -545,7 +552,7 @@ func (th *TestHelper) CreateUserWithAuth(authService string) *model.User { EmailVerified: true, AuthService: authService, } - user, err := th.App.CreateUser(user) + user, err := th.App.CreateUser(th.Context, user) if err != nil { panic(err) } @@ -714,7 +721,7 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel { utils.DisableDebugLogForTest() var err *model.AppError var channel *model.Channel - if channel, err = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, user.Id); err != nil { + if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -789,7 +796,7 @@ func (th *TestHelper) LoginSystemAdminWithClient(client *model.Client4) { func (th *TestHelper) UpdateActiveUser(user *model.User, active bool) { utils.DisableDebugLogForTest() - _, err := th.App.UpdateActive(user, active) + _, err := th.App.UpdateActive(th.Context, user, active) if err != nil { panic(err) } @@ -800,7 +807,7 @@ func (th *TestHelper) UpdateActiveUser(user *model.User, active bool) { func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - _, err := th.App.JoinUserToTeam(team, user, "") + _, err := th.App.JoinUserToTeam(th.Context, team, user, "") if err != nil { panic(err) } diff --git a/api4/bleve.go b/api4/bleve.go index 0d2177bd406..3a54a0f4711 100644 --- a/api4/bleve.go +++ b/api4/bleve.go @@ -18,7 +18,7 @@ func purgeBleveIndexes(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("purgeBleveIndexes", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_PURGE_BLEVE_INDEXES) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PURGE_BLEVE_INDEXES) { c.SetPermissionError(model.PERMISSION_PURGE_BLEVE_INDEXES) return } diff --git a/api4/bot.go b/api4/bot.go index fcdee5bdcc0..5da0d774e7b 100644 --- a/api4/bot.go +++ b/api4/bot.go @@ -37,7 +37,7 @@ func createBot(c *Context, w http.ResponseWriter, r *http.Request) { } bot := &model.Bot{ - OwnerId: c.App.Session().UserId, + OwnerId: c.AppContext.Session().UserId, } bot.Patch(botPatch) @@ -45,12 +45,12 @@ func createBot(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("bot", bot) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_BOT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session().UserId); err == nil { if user.IsBot { c.SetPermissionError(model.PERMISSION_CREATE_BOT) return @@ -62,7 +62,7 @@ func createBot(c *Context, w http.ResponseWriter, r *http.Request) { return } - createdBot, err := c.App.CreateBot(bot) + createdBot, err := c.App.CreateBot(c.AppContext, bot) if err != nil { c.Err = err return @@ -92,7 +92,7 @@ func patchBot(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("bot_id", botUserId) - if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.AppContext.Session(), botUserId); err != nil { c.Err = err return } @@ -124,10 +124,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.AppContext.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.AppContext.Session().UserId { + if !c.App.SessionHasPermissionTo(*c.AppContext.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. @@ -153,12 +153,12 @@ func getBots(c *Context, w http.ResponseWriter, r *http.Request) { onlyOrphaned, _ := strconv.ParseBool(r.URL.Query().Get("only_orphaned")) var OwnerId string - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_OTHERS_BOTS) { + if c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session(), model.PERMISSION_READ_BOTS) { // Only get bots created by this user. - OwnerId = c.App.Session().UserId + OwnerId = c.AppContext.Session().UserId } else { c.SetPermissionError(model.PERMISSION_READ_BOTS) return @@ -203,12 +203,12 @@ func updateBotActive(c *Context, w http.ResponseWriter, active bool) { auditRec.AddMeta("bot_id", botUserId) auditRec.AddMeta("enable", active) - if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.AppContext.Session(), botUserId); err != nil { c.Err = err return } - bot, err := c.App.UpdateBotActive(botUserId, active) + bot, err := c.App.UpdateBotActive(c.AppContext, botUserId, active) if err != nil { c.Err = err return @@ -234,7 +234,7 @@ func assignBot(c *Context, w http.ResponseWriter, _ *http.Request) { auditRec.AddMeta("bot_id", botUserId) auditRec.AddMeta("assign_user_id", userId) - if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.AppContext.Session(), botUserId); err != nil { c.Err = err return } @@ -265,7 +265,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.AppContext.Session().UserId, botUserId) if err != nil { c.Err = err return @@ -312,7 +312,7 @@ func setBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("bot_id", botUserId) - if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.AppContext.Session(), botUserId); err != nil { c.Err = err return } @@ -364,7 +364,7 @@ func deleteBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("bot_id", botUserId) - if err := c.App.SessionHasPermissionToManageBot(*c.App.Session(), botUserId); err != nil { + if err := c.App.SessionHasPermissionToManageBot(*c.AppContext.Session(), botUserId); err != nil { c.Err = err return } @@ -406,7 +406,7 @@ func convertBotToUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("userPatch", userPatch) auditRec.AddMeta("set_system_admin", systemAdmin) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/brand.go b/api4/brand.go index 137eb68c860..a9213deac67 100644 --- a/api4/brand.go +++ b/api4/brand.go @@ -61,7 +61,7 @@ func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("uploadBrandImage", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_EDIT_BRAND) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_EDIT_BRAND) { c.SetPermissionError(model.PERMISSION_EDIT_BRAND) return } @@ -82,7 +82,7 @@ func deleteBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deleteBrandImage", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_EDIT_BRAND) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_EDIT_BRAND) { c.SetPermissionError(model.PERMISSION_EDIT_BRAND) return } diff --git a/api4/channel.go b/api4/channel.go index c02ff9368d0..5fc81685446 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -89,17 +89,17 @@ func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_CREATE_PUBLIC_CHANNEL) { + if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_CREATE_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_CREATE_PUBLIC_CHANNEL) 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.AppContext.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(c.AppContext, channel, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -146,20 +146,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.AppContext.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.AppContext.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 _, errGet := c.App.GetChannelMember(context.Background(), channel.Id, c.App.Session().UserId); errGet != nil { + if _, errGet := c.App.GetChannelMember(context.Background(), channel.Id, c.AppContext.Session().UserId); errGet != nil { c.Err = model.NewAppError("updateChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -212,7 +212,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("update", updatedChannel) 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.AppContext, c.AppContext.Session().UserId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { mlog.Warn("Error while posting channel display name message", mlog.Err(err)) } } @@ -239,7 +239,7 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", oldPublicChannel) - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { c.SetPermissionError(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) return } @@ -254,7 +254,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -263,7 +263,7 @@ func convertChannelToPrivate(c *Context, w http.ResponseWriter, r *http.Request) oldPublicChannel.Type = model.CHANNEL_PRIVATE - rchannel, err := c.App.UpdateChannelPrivacy(oldPublicChannel, user) + rchannel, err := c.App.UpdateChannelPrivacy(c.AppContext, oldPublicChannel, user) if err != nil { c.Err = err return @@ -299,12 +299,12 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) auditRec.AddMeta("new_type", privacy) - if privacy == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC) { + if privacy == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC) { c.SetPermissionError(model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC) return } - if privacy == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { + if privacy == model.CHANNEL_PRIVATE && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) { c.SetPermissionError(model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE) return } @@ -314,7 +314,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -323,7 +323,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { channel.Type = privacy - updatedChannel, err := c.App.UpdateChannelPrivacy(channel, user) + updatedChannel, err := c.App.UpdateChannelPrivacy(c.AppContext, channel, user) if err != nil { c.Err = err return @@ -359,20 +359,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.AppContext.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.AppContext.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(context.Background(), c.Params.ChannelId, c.App.Session().UserId); err != nil { + if _, err = c.App.GetChannelMember(context.Background(), c.Params.ChannelId, c.AppContext.Session().UserId); err != nil { c.Err = model.NewAppError("patchChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -382,7 +382,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(c.AppContext, oldChannel, patch, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -418,12 +418,12 @@ func restoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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(c.AppContext, channel, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -449,7 +449,7 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("user_id") return } - if id == c.App.Session().UserId { + if id == c.AppContext.Session().UserId { allowed = true } } @@ -457,24 +457,24 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createDirectChannel", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_DIRECT_CHANNEL) { + if !c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } otherUserId := userIds[0] - if c.App.Session().UserId == otherUserId { + if c.AppContext.Session().UserId == otherUserId { otherUserId = userIds[1] } auditRec.AddMeta("other_user_id", otherUserId) - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, otherUserId) + canSee, err := c.App.UserCanSeeOtherUser(c.AppContext.Session().UserId, otherUserId) if err != nil { c.Err = err return @@ -485,7 +485,7 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - sc, err := c.App.GetOrCreateDirectChannel(userIds[0], userIds[1]) + sc, err := c.App.GetOrCreateDirectChannel(c.AppContext, userIds[0], userIds[1]) if err != nil { c.Err = err return @@ -505,7 +505,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.AppContext.Session().UserId, props.Term) if err != nil { c.Err = err return @@ -528,27 +528,27 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.SetInvalidParam("user_id") return } - if id == c.App.Session().UserId { + if id == c.AppContext.Session().UserId { found = true } } if !found { - userIds = append(userIds, c.App.Session().UserId) + userIds = append(userIds, c.AppContext.Session().UserId) } auditRec := c.MakeAuditRecord("createGroupChannel", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_GROUP_CHANNEL) { + if !c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session().UserId != id { + canSee, err := c.App.UserCanSeeOtherUser(c.AppContext.Session().UserId, id) if err != nil { c.Err = err return @@ -564,7 +564,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -590,12 +590,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.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -616,12 +616,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.AppContext.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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -641,7 +641,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -674,7 +674,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -700,12 +700,12 @@ func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS, model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS, } - if !c.App.SessionHasPermissionToAny(*c.App.Session(), permissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), permissions) { c.SetPermissionError(permissions...) return } // Only system managers may use the ExcludePolicyConstrained parameter - if c.Params.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.Params.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -716,7 +716,7 @@ func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { IncludeDeleted: c.Params.IncludeDeleted, ExcludePolicyConstrained: c.Params.ExcludePolicyConstrained, } - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { opts.IncludePolicyID = true } @@ -751,7 +751,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) return } @@ -777,7 +777,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -798,7 +798,7 @@ func getPrivateChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -837,7 +837,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -863,12 +863,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.AppContext.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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -909,7 +909,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { c.SetPermissionError(model.PERMISSION_LIST_TEAM_CHANNELS) return } @@ -935,7 +935,7 @@ func autocompleteChannelsForTeamForSearch(c *Context, w http.ResponseWriter, r * 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.AppContext.Session().UserId, name) if err != nil { c.Err = err return @@ -958,16 +958,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.AppContext.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.AppContext.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.AppContext.Session().UserId, c.Params.TeamId, props.Term) } if err != nil { @@ -994,16 +994,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_LIST_TEAM_CHANNELS) { + channels, err = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.AppContext.Session().UserId) } else { // If the user is not a team member, return a 404 - if _, err = c.App.GetTeamMember(c.Params.TeamId, c.App.Session().UserId); err != nil { + if _, err = c.App.GetTeamMember(c.Params.TeamId, c.AppContext.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.AppContext.Session().UserId) } if err != nil { @@ -1023,12 +1023,12 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { return } // Only system managers may use the ExcludePolicyConstrained field - if props.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if props.ExcludePolicyConstrained && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) return } @@ -1049,7 +1049,7 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { Page: props.Page, PerPage: props.PerPage, } - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { opts.IncludePolicyID = true } @@ -1092,12 +1092,12 @@ 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.AppContext.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.AppContext.Session(), channel.Id, model.PERMISSION_DELETE_PRIVATE_CHANNEL) { c.SetPermissionError(model.PERMISSION_DELETE_PRIVATE_CHANNEL) return } @@ -1109,7 +1109,7 @@ func deleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { err = model.NewAppError("deleteChannel", "api.user.delete_channel.not_enabled.app_error", nil, "channelId="+c.Params.ChannelId, http.StatusUnauthorized) } } else { - err = c.App.DeleteChannel(channel, c.App.Session().UserId) + err = c.App.DeleteChannel(c.AppContext, channel, c.AppContext.Session().UserId) } if err != nil { c.Err = err @@ -1136,12 +1136,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.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.Err = model.NewAppError("getChannelByName", "app.channel.get_by_name.missing.app_error", nil, "teamId="+channel.TeamId+", "+"name="+channel.Name+"", http.StatusNotFound) return } @@ -1169,8 +1169,8 @@ func getChannelByNameForTeamName(c *Context, w http.ResponseWriter, r *http.Requ return } - teamOk := c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) - channelOk := c.App.SessionHasPermissionToChannel(*c.App.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) + teamOk := c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) + channelOk := c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) if channel.Type == model.CHANNEL_OPEN { if !teamOk && !channelOk { @@ -1197,7 +1197,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1217,7 +1217,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1243,7 +1243,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1263,7 +1263,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1283,12 +1283,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.AppContext.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.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1308,7 +1308,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1330,13 +1330,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.AppContext.Session().Id) if err != nil { c.Err = err return } - c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) + c.App.UpdateLastActivityAtIfNeeded(*c.AppContext.Session()) c.ExtendSessionExpiryIfNeeded(w, r) // Returning {"status": "OK", ...} for backwards compatibility @@ -1367,7 +1367,7 @@ func updateChannelMemberRoles(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) return } @@ -1399,7 +1399,7 @@ func updateChannelMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.R auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", schemeRoles) - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_MANAGE_CHANNEL_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_CHANNEL_ROLES) return } @@ -1431,7 +1431,7 @@ func updateChannelMemberNotifyProps(c *Context, w http.ResponseWriter, r *http.R auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("props", props) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1508,18 +1508,18 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - isSelfAdd := member.UserId == c.App.Session().UserId + isSelfAdd := member.UserId == c.AppContext.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.AppContext.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.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) return } @@ -1528,14 +1528,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.AppContext.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.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) return } @@ -1558,8 +1558,8 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - cm, err := c.App.AddChannelMember(member.UserId, channel, app.ChannelMemberOpts{ - UserRequestorID: c.App.Session().UserId, + cm, err := c.App.AddChannelMember(c.AppContext, member.UserId, channel, app.ChannelMemberOpts{ + UserRequestorID: c.AppContext.Session().UserId, PostRootID: postRootId, }) if err != nil { @@ -1603,24 +1603,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.AppContext.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.AppContext.Session().UserId { + if channel.Type == model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) { c.SetPermissionError(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) 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.AppContext.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.AppContext, c.Params.UserId, c.AppContext.Session().UserId, channel); err != nil { c.Err = err return } @@ -1652,7 +1652,7 @@ func updateChannelScheme(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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1712,7 +1712,7 @@ func channelMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http. groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) return } @@ -1751,7 +1751,7 @@ func channelMemberCountsByGroup(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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -1784,7 +1784,7 @@ func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) return } @@ -1824,7 +1824,7 @@ func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) auditRec := c.MakeAuditRecord("patchChannelModerations", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_CHANNELS) return } @@ -1897,12 +1897,12 @@ func moveChannel(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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - user, err := c.App.GetUser(c.App.Session().UserId) + user, err := c.App.GetUser(c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -1915,14 +1915,14 @@ func moveChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if force { - err = c.App.RemoveUsersFromChannelNotMemberOfTeam(user, channel, team) + err = c.App.RemoveUsersFromChannelNotMemberOfTeam(c.AppContext, user, channel, team) if err != nil { c.Err = err return } } - err = c.App.MoveChannel(team, channel, user) + err = c.App.MoveChannel(c.AppContext, team, channel, user) if err != nil { c.Err = err return diff --git a/api4/channel_category.go b/api4/channel_category.go index eb158fe7f7b..ccfa9ee02c1 100644 --- a/api4/channel_category.go +++ b/api4/channel_category.go @@ -17,7 +17,7 @@ func getCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.Requ return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -37,7 +37,7 @@ func createCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -72,7 +72,7 @@ func getCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *http.R return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -92,7 +92,7 @@ func updateCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *htt return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -103,7 +103,7 @@ func updateCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *htt categoryOrder := model.ArrayFromJson(r.Body) for _, categoryId := range categoryOrder { - if !c.App.SessionHasPermissionToCategory(*c.App.Session(), c.Params.UserId, c.Params.TeamId, categoryId) { + if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, categoryId) { c.SetInvalidParam("category") return } @@ -125,7 +125,7 @@ func getCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionToCategory(*c.App.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -145,7 +145,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -160,7 +160,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R } for _, category := range categoriesUpdateRequest { - if !c.App.SessionHasPermissionToCategory(*c.App.Session(), c.Params.UserId, c.Params.TeamId, category.Id) { + if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, category.Id) { c.SetInvalidParam("category") return } @@ -233,7 +233,7 @@ func updateCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToCategory(*c.App.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -270,7 +270,7 @@ func deleteCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToCategory(*c.App.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/channel_category_test.go b/api4/channel_category_test.go index 5667e2ff60d..0ab22ccd3fe 100644 --- a/api4/channel_category_test.go +++ b/api4/channel_category_test.go @@ -438,7 +438,7 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) { func setupUserForSubtest(t *testing.T, th *TestHelper) (*model.User, *model.Client4) { password := "password" - user, err := th.App.CreateUser(&model.User{ + user, err := th.App.CreateUser(th.Context, &model.User{ Email: th.GenerateTestEmail(), Username: "user_" + model.NewId(), Password: password, diff --git a/api4/channel_local.go b/api4/channel_local.go index 6648d324f92..e921d4789ce 100644 --- a/api4/channel_local.go +++ b/api4/channel_local.go @@ -43,7 +43,7 @@ func localCreateChannel(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel", channel) - sc, err := c.App.CreateChannel(channel, false) + sc, err := c.App.CreateChannel(c.AppContext, channel, false) if err != nil { c.Err = err return @@ -154,7 +154,7 @@ func localRemoveChannelMember(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("channel", channel) auditRec.AddMeta("remove_user_id", user.Id) - if err = c.App.RemoveUserFromChannel(c.Params.UserId, "", channel); err != nil { + if err = c.App.RemoveUserFromChannel(c.AppContext, c.Params.UserId, "", channel); err != nil { c.Err = err return } @@ -258,14 +258,14 @@ func localMoveChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if force { - err = c.App.RemoveUsersFromChannelNotMemberOfTeam(nil, channel, team) + err = c.App.RemoveUsersFromChannelNotMemberOfTeam(c.AppContext, nil, channel, team) if err != nil { c.Err = err return } } - err = c.App.MoveChannel(team, channel, nil) + err = c.App.MoveChannel(c.AppContext, team, channel, nil) if err != nil { c.Err = err return @@ -302,7 +302,7 @@ func localDeleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { if c.Params.Permanent { err = c.App.PermanentDeleteChannel(channel) } else { - err = c.App.DeleteChannel(channel, "") + err = c.App.DeleteChannel(c.AppContext, channel, "") } if err != nil { c.Err = err diff --git a/api4/channel_test.go b/api4/channel_test.go index 03e2f55ad8b..908b42fae85 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -448,7 +448,7 @@ func TestCreateDirectChannelAsGuest(t *testing.T) { Password: "Password1", EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) _, resp := Client.Login(guest.Username, "Password1") @@ -575,7 +575,7 @@ func TestCreateGroupChannelAsGuest(t *testing.T) { Password: "Password1", EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) _, resp := Client.Login(guest.Username, "Password1") @@ -943,12 +943,12 @@ func TestGetChannelsForTeamForUser(t *testing.T) { TeamId: th.BasicTeam.Id, CreatorId: th.BasicUser.Id, } - th.App.CreateChannel(testChannel, true) + th.App.CreateChannel(th.Context, testChannel, true) defer th.App.PermanentDeleteChannel(testChannel) channels, resp := Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "") CheckNoError(t, resp) assert.Equal(t, 6, len(channels)) - th.App.DeleteChannel(testChannel, th.BasicUser.Id) + th.App.DeleteChannel(th.Context, testChannel, th.BasicUser.Id) channels, resp = Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "") CheckNoError(t, resp) assert.Equal(t, 5, len(channels)) @@ -1182,7 +1182,7 @@ func TestSearchChannels(t *testing.T) { }) t.Run("Remove the user from BasicChannel and search again, should not be returned", func(t *testing.T) { - th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicChannel) + th.App.RemoveUserFromChannel(th.Context, th.BasicUser.Id, th.BasicUser.Id, th.BasicChannel) search.Term = th.BasicChannel.Name channelList, resp := Client.SearchChannels(th.BasicTeam.Id, search) @@ -1270,7 +1270,7 @@ func TestSearchArchivedChannels(t *testing.T) { }) t.Run("Remove the user from BasicDeletedChannel and search again, should still return", func(t *testing.T) { - th.App.RemoveUserFromChannel(th.BasicUser.Id, th.BasicUser.Id, th.BasicDeletedChannel) + th.App.RemoveUserFromChannel(th.Context, th.BasicUser.Id, th.BasicUser.Id, th.BasicDeletedChannel) search.Term = th.BasicDeletedChannel.Name channelList, resp := Client.SearchArchivedChannels(th.BasicTeam.Id, search) @@ -2878,7 +2878,7 @@ func TestRemoveChannelMember(t *testing.T) { *cfg.ServiceSettings.EnableBotAccountCreation = true }) bot := th.CreateBotWithSystemAdminClient() - th.App.AddUserToTeam(team.Id, bot.UserId, "") + th.App.AddUserToTeam(th.Context, team.Id, bot.UserId, "") pass, resp := Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id) CheckNoError(t, resp) @@ -3166,13 +3166,13 @@ func TestAutocompleteChannelsForSearch(t *testing.T) { th.LoginBasicWithClient(th.Client) u1 := th.CreateUserWithClient(th.SystemAdminClient) - defer th.App.PermanentDeleteUser(u1) + defer th.App.PermanentDeleteUser(th.Context, u1) u2 := th.CreateUserWithClient(th.SystemAdminClient) - defer th.App.PermanentDeleteUser(u2) + defer th.App.PermanentDeleteUser(th.Context, u2) u3 := th.CreateUserWithClient(th.SystemAdminClient) - defer th.App.PermanentDeleteUser(u3) + defer th.App.PermanentDeleteUser(th.Context, u3) u4 := th.CreateUserWithClient(th.SystemAdminClient) - defer th.App.PermanentDeleteUser(u4) + defer th.App.PermanentDeleteUser(th.Context, u4) // A private channel to make sure private channels are not used utils.DisableDebugLogForTest() @@ -3278,7 +3278,7 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) { defer th.TearDown() u1 := th.CreateUserWithClient(th.SystemAdminClient) - defer th.App.PermanentDeleteUser(u1) + defer th.App.PermanentDeleteUser(th.Context, u1) enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { @@ -3296,7 +3296,7 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) { Password: "Password1", EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) th.LoginSystemAdminWithClient(th.SystemAdminClient) @@ -3533,9 +3533,9 @@ func TestChannelMembersMinusGroupMembers(t *testing.T) { channel := th.CreatePrivateChannel() - _, err := th.App.AddChannelMember(user1.Id, channel, app.ChannelMemberOpts{}) + _, err := th.App.AddChannelMember(th.Context, user1.Id, channel, app.ChannelMemberOpts{}) require.Nil(t, err) - _, err = th.App.AddChannelMember(user2.Id, channel, app.ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, user2.Id, channel, app.ChannelMemberOpts{}) require.Nil(t, err) channel.GroupConstrained = model.NewBool(true) diff --git a/api4/cloud.go b/api4/cloud.go index fd777f55675..ba69abc44bc 100644 --- a/api4/cloud.go +++ b/api4/cloud.go @@ -50,12 +50,12 @@ func getSubscription(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) return } - subscription, err := c.App.Cloud().GetSubscription(c.App.Session().UserId) + subscription, err := c.App.Cloud().GetSubscription(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("Api4.getSubscription", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return @@ -106,12 +106,12 @@ func getCloudProducts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) return } - products, err := c.App.Cloud().GetCloudProducts(c.App.Session().UserId) + products, err := c.App.Cloud().GetCloudProducts(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("Api4.getCloudProducts", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return @@ -132,12 +132,12 @@ func getCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) return } - customer, err := c.App.Cloud().GetCloudCustomer(c.App.Session().UserId) + customer, err := c.App.Cloud().GetCloudCustomer(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("Api4.getCloudCustomer", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return @@ -158,7 +158,7 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) return } @@ -175,7 +175,7 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - customer, appErr := c.App.Cloud().UpdateCloudCustomer(c.App.Session().UserId, customerInfo) + customer, appErr := c.App.Cloud().UpdateCloudCustomer(c.AppContext.Session().UserId, customerInfo) if appErr != nil { c.Err = model.NewAppError("Api4.updateCloudCustomer", "api.cloud.request_error", nil, appErr.Error(), http.StatusInternalServerError) return @@ -196,7 +196,7 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) return } @@ -213,7 +213,7 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque return } - customer, appErr := c.App.Cloud().UpdateCloudCustomerAddress(c.App.Session().UserId, address) + customer, appErr := c.App.Cloud().UpdateCloudCustomerAddress(c.AppContext.Session().UserId, address) if appErr != nil { c.Err = model.NewAppError("Api4.updateCloudCustomerAddress", "api.cloud.request_error", nil, appErr.Error(), http.StatusInternalServerError) return @@ -234,7 +234,7 @@ func createCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) return } @@ -242,7 +242,7 @@ func createCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createCustomerPayment", audit.Fail) defer c.LogAuditRec(auditRec) - intent, err := c.App.Cloud().CreateCustomerPayment(c.App.Session().UserId) + intent, err := c.App.Cloud().CreateCustomerPayment(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("Api4.createCustomerPayment", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return @@ -265,7 +265,7 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_BILLING) return } @@ -285,7 +285,7 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) return } - err = c.App.Cloud().ConfirmCustomerPayment(c.App.Session().UserId, confirmRequest) + err = c.App.Cloud().ConfirmCustomerPayment(c.AppContext.Session().UserId, confirmRequest) if err != nil { c.Err = model.NewAppError("Api4.createCustomerPayment", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return @@ -302,12 +302,12 @@ func getInvoicesForSubscription(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) return } - invoices, appErr := c.App.Cloud().GetInvoicesForSubscription(c.App.Session().UserId) + invoices, appErr := c.App.Cloud().GetInvoicesForSubscription(c.AppContext.Session().UserId) if appErr != nil { c.Err = model.NewAppError("Api4.getInvoicesForSubscription", "api.cloud.request_error", nil, appErr.Error(), http.StatusInternalServerError) return @@ -333,12 +333,12 @@ func getSubscriptionInvoicePDF(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_BILLING) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_BILLING) return } - pdfData, filename, appErr := c.App.Cloud().GetInvoicePDF(c.App.Session().UserId, c.Params.InvoiceId) + pdfData, filename, appErr := c.App.Cloud().GetInvoicePDF(c.AppContext.Session().UserId, c.Params.InvoiceId) if appErr != nil { c.Err = model.NewAppError("Api4.getSuscriptionInvoicePDF", "api.cloud.request_error", nil, appErr.Error(), http.StatusInternalServerError) return @@ -441,13 +441,13 @@ func sendAdminUpgradeRequestEmail(c *Context, w http.ResponseWriter, r *http.Req return } - user, appErr := c.App.GetUser(c.App.Session().UserId) + user, appErr := c.App.GetUser(c.AppContext.Session().UserId) if appErr != nil { c.Err = model.NewAppError("Api4.sendAdminUpgradeRequestEmail", appErr.Id, nil, appErr.Error(), appErr.StatusCode) return } - sub, err := c.App.Cloud().GetSubscription(c.App.Session().UserId) + sub, err := c.App.Cloud().GetSubscription(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("Api4.sendAdminUpgradeRequestEmail", "api.cloud.request_error", nil, err.Error(), http.StatusInternalServerError) return diff --git a/api4/cluster.go b/api4/cluster.go index 84fb8754fac..8aa72a49862 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_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY) return } diff --git a/api4/command.go b/api4/command.go index 58d835840ee..d330638e49f 100644 --- a/api4/command.go +++ b/api4/command.go @@ -38,12 +38,12 @@ func createCommand(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId rcmd, err := c.App.CreateCommand(cmd) if err != nil { @@ -84,11 +84,11 @@ func updateCommand(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("command", oldCmd) 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.AppContext.Session().UserId, http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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. @@ -96,7 +96,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.AppContext.Session().UserId != oldCmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), oldCmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) return @@ -137,7 +137,7 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("team", newTeam) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), newTeam.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), newTeam.Id, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) return @@ -150,7 +150,7 @@ func moveCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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. @@ -186,7 +186,7 @@ func deleteCommand(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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. @@ -194,7 +194,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.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS) return @@ -221,7 +221,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.AppContext.Session(), teamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -229,7 +229,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.AppContext.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_MANAGE_SLASH_COMMANDS) return } @@ -240,14 +240,14 @@ 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) { - commands, err = c.App.ListAutocompleteCommands(teamId, c.App.T) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + commands, err = c.App.ListAutocompleteCommands(teamId, c.AppContext.T) if err != nil { c.Err = err return } } else { - commands, err = c.App.ListAllCommands(teamId, c.App.T) + commands, err = c.App.ListAllCommands(teamId, c.AppContext.T) if err != nil { c.Err = err return @@ -273,13 +273,13 @@ func getCommand(c *Context, w http.ResponseWriter, r *http.Request) { // check for permissions to view this command; must have perms to view team and // PERMISSION_MANAGE_SLASH_COMMANDS for the team the command belongs to. - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { // again, return not_found to ensure id existence does not leak. c.SetCommandNotFoundError() return @@ -304,7 +304,7 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("commandargs", commandArgs) // checks that user is a member of the specified channel, and that they have permission to use slash commands in it - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), commandArgs.ChannelId, model.PERMISSION_USE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), commandArgs.ChannelId, model.PERMISSION_USE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) return } @@ -322,22 +322,22 @@ 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.AppContext.Session().GetTeamByTeamId(commandArgs.TeamId) == nil { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_USE_SLASH_COMMANDS) { c.SetPermissionError(model.PERMISSION_USE_SLASH_COMMANDS) return } } } - commandArgs.UserId = c.App.Session().UserId - commandArgs.T = c.App.T + commandArgs.UserId = c.AppContext.Session().UserId + commandArgs.T = c.AppContext.T commandArgs.SiteURL = c.GetSiteURLHeader() - commandArgs.Session = *c.App.Session() + commandArgs.Session = *c.AppContext.Session() auditRec.AddMeta("commandargs", commandArgs) // overwrite in case teamid changed - response, err := c.App.ExecuteCommand(commandArgs) + response, err := c.App.ExecuteCommand(c.AppContext, commandArgs) if err != nil { c.Err = err return @@ -353,12 +353,12 @@ 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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - commands, err := c.App.ListAutocompleteCommands(c.Params.TeamId, c.App.T) + commands, err := c.App.ListAutocompleteCommands(c.Params.TeamId, c.AppContext.T) if err != nil { c.Err = err return @@ -372,7 +372,7 @@ func listCommandAutocompleteSuggestions(c *Context, w http.ResponseWriter, r *ht if c.Err != nil { return } - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -390,7 +390,7 @@ func listCommandAutocompleteSuggestions(c *Context, w http.ResponseWriter, r *ht } userInput = strings.TrimPrefix(userInput, "/") - commands, err := c.App.ListAutocompleteCommands(c.Params.TeamId, c.App.T) + commands, err := c.App.ListAutocompleteCommands(c.Params.TeamId, c.AppContext.T) if err != nil { c.Err = err return @@ -401,14 +401,14 @@ func listCommandAutocompleteSuggestions(c *Context, w http.ResponseWriter, r *ht TeamId: c.Params.TeamId, RootId: query.Get("root_id"), ParentId: query.Get("parent_id"), - UserId: c.App.Session().UserId, - T: c.App.T, - Session: *c.App.Session(), + UserId: c.AppContext.Session().UserId, + T: c.AppContext.T, + Session: *c.AppContext.Session(), SiteURL: c.GetSiteURLHeader(), Command: userInput, } - suggestions := c.App.GetSuggestions(commandArgs, commands, roleId) + suggestions := c.App.GetSuggestions(c.AppContext, commandArgs, commands, roleId) w.Write(model.AutocompleteSuggestionsToJSON(suggestions)) } @@ -431,7 +431,7 @@ func regenCommandToken(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("command", cmd) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), cmd.TeamId, model.PERMISSION_MANAGE_SLASH_COMMANDS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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. @@ -439,7 +439,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.AppContext.Session().UserId != cmd.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.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 e0457cd3bd5..397dd50307e 100644 --- a/api4/compliance.go +++ b/api4/compliance.go @@ -30,12 +30,12 @@ func createComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) auditRec := c.MakeAuditRecord("createComplianceReport", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB) { c.SetPermissionError(model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB) return } - job.UserId = c.App.Session().UserId + job.UserId = c.AppContext.Session().UserId rjob, err := c.App.SaveComplianceReport(job) if err != nil { @@ -53,7 +53,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_READ_COMPLIANCE_EXPORT_JOB) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) { c.SetPermissionError(model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) return } @@ -80,7 +80,7 @@ func getComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("getComplianceReport", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) { c.SetPermissionError(model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB) return } @@ -108,7 +108,7 @@ func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request defer c.LogAuditRec(auditRec) auditRec.AddMeta("compliance_id", c.Params.ReportId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { c.SetPermissionError(model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) return } diff --git a/api4/config.go b/api4/config.go index 2d8e774aaf9..091c3325f2a 100644 --- a/api4/config.go +++ b/api4/config.go @@ -47,7 +47,7 @@ func init() { } func getConfig(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleReadPermissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleReadPermissions) { c.SetPermissionError(model.SysconsoleReadPermissions...) return } @@ -78,7 +78,7 @@ func configReload(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("configReload", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_RELOAD_CONFIG) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_RELOAD_CONFIG) { c.SetPermissionError(model.PERMISSION_RELOAD_CONFIG) return } @@ -108,7 +108,7 @@ func updateConfig(c *Context, w http.ResponseWriter, r *http.Request) { cfg.SetDefaults() - if !c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleWritePermissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleWritePermissions) { c.SetPermissionError(model.SysconsoleWritePermissions...) return } @@ -183,7 +183,7 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { } var config map[string]string - if c.App.Session().UserId == "" { + if c.AppContext.Session().UserId == "" { config = c.App.LimitedClientConfigWithComputed() } else { config = c.App.ClientConfigWithComputed() @@ -213,7 +213,7 @@ func patchConfig(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchConfig", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleWritePermissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleWritePermissions) { c.SetPermissionError(model.SysconsoleWritePermissions...) return } @@ -289,7 +289,7 @@ func makeFilterConfigByPermission(accessType filterType) func(c *Context, struct // If there are no access tag values and the role has manage_system, no need to continue // checking permissions. if len(tagPermissions) == 0 { - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { return true } } @@ -322,13 +322,13 @@ func makeFilterConfigByPermission(accessType filterType) func(c *Context, struct continue } if tagValue == model.ConfigAccessTagAnySysConsoleRead && accessType == FilterTypeRead && - c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleReadPermissions) { + c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleReadPermissions) { return true } permissionID := fmt.Sprintf("sysconsole_%s_%s", accessType, tagValue) if permission, ok := permissionMap[permissionID]; ok { - if c.App.SessionHasPermissionTo(*c.App.Session(), permission) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), permission) { return true } } else { @@ -337,7 +337,7 @@ func makeFilterConfigByPermission(accessType filterType) func(c *Context, struct } // with manage_system, default to allow, otherwise default not-allow - return c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) + return c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) } } @@ -359,7 +359,7 @@ func migrateConfig(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("to", to) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/data_retention.go b/api4/data_retention.go index 9fc52806800..bf150992d06 100644 --- a/api4/data_retention.go +++ b/api4/data_retention.go @@ -44,7 +44,7 @@ func getGlobalPolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getPolicies(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -62,7 +62,7 @@ func getPolicies(c *Context, w http.ResponseWriter, r *http.Request) { } func getPoliciesCount(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -78,7 +78,7 @@ func getPoliciesCount(c *Context, w http.ResponseWriter, r *http.Request) { } func getPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -102,7 +102,7 @@ func createPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy", policy) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -131,7 +131,7 @@ func patchPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("patch", patch) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -152,7 +152,7 @@ func deletePolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deletePolicy", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy_id", policyId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -167,7 +167,7 @@ func deletePolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getTeamsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -194,7 +194,7 @@ func getTeamsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { func searchTeamsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) { c.RequirePolicyId() - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -212,7 +212,7 @@ func searchTeamsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = err return } - c.App.SanitizeTeams(*c.App.Session(), teams) + c.App.SanitizeTeams(*c.AppContext.Session(), teams) payload := []byte(model.TeamListToJson(teams)) w.Write(payload) @@ -231,7 +231,7 @@ func addTeamsToPolicy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("team_ids", teamIDs) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -260,7 +260,7 @@ func removeTeamsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("team_ids", teamIDs) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -276,7 +276,7 @@ func removeTeamsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request) { } func getChannelsForPolicy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -308,7 +308,7 @@ func searchChannelsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -347,7 +347,7 @@ func addChannelsToPolicy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("channel_ids", channelIDs) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -376,7 +376,7 @@ func removeChannelsFromPolicy(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("policy_id", policyId) auditRec.AddMeta("channel_ids", channelIDs) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY) return } @@ -400,7 +400,7 @@ func getTeamPoliciesForUser(c *Context, w http.ResponseWriter, r *http.Request) limit := c.Params.PerPage offset := c.Params.Page * limit - if userID != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -423,7 +423,7 @@ func getChannelPoliciesForUser(c *Context, w http.ResponseWriter, r *http.Reques limit := c.Params.PerPage offset := c.Params.Page * limit - if userID != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if userID != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/elasticsearch.go b/api4/elasticsearch.go index dd129a979d9..6d299338bdd 100644 --- a/api4/elasticsearch.go +++ b/api4/elasticsearch.go @@ -23,7 +23,7 @@ func testElasticsearch(c *Context, w http.ResponseWriter, r *http.Request) { // PERMISSION_TEST_ELASTICSEARCH is an ancillary permission of PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH, // which should prevent read-only managers from password sniffing - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_TEST_ELASTICSEARCH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_ELASTICSEARCH) { c.SetPermissionError(model.PERMISSION_TEST_ELASTICSEARCH) return } @@ -45,7 +45,7 @@ func purgeElasticsearchIndexes(c *Context, w http.ResponseWriter, r *http.Reques auditRec := c.MakeAuditRecord("purgeElasticsearchIndexes", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES) { c.SetPermissionError(model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES) return } diff --git a/api4/emoji.go b/api4/emoji.go index 59a60eef470..198895bdeeb 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -52,17 +52,17 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) // 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.AppContext.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.AppContext.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.AppContext.Session(), membership.TeamId, model.PERMISSION_CREATE_EMOJIS) { hasPermission = true break } @@ -89,7 +89,7 @@ func createEmoji(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("emoji", emoji) - newEmoji, err := c.App.CreateEmoji(c.App.Session().UserId, emoji, m) + newEmoji, err := c.App.CreateEmoji(c.AppContext.Session().UserId, emoji, m) if err != nil { c.Err = err return @@ -138,17 +138,17 @@ func deleteEmoji(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("emoji", emoji) // 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.AppContext.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.AppContext.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.AppContext.Session(), membership.TeamId, model.PERMISSION_DELETE_EMOJIS) { hasPermission = true break } @@ -159,11 +159,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.AppContext.Session().UserId != emoji.CreatorId { + if !c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session(), membership.TeamId, model.PERMISSION_DELETE_OTHERS_EMOJIS) { hasPermission = true break } diff --git a/api4/file.go b/api4/file.go index 0203695c516..80444a0953a 100644 --- a/api4/file.go +++ b/api4/file.go @@ -162,7 +162,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel_id", c.Params.ChannelId) - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -170,9 +170,9 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F clientId := r.Form.Get("client_id") auditRec.AddMeta("client_id", clientId) - info, appErr := c.App.UploadFileX(c.Params.ChannelId, c.Params.Filename, r.Body, + info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, c.Params.Filename, r.Body, app.UploadFileSetTeamId(FileTeamId), - app.UploadFileSetUserId(c.App.Session().UserId), + app.UploadFileSetUserId(c.AppContext.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(r.ContentLength), app.UploadFileSetClientId(clientId)) @@ -307,7 +307,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.AppContext.Session(), c.Params.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -333,9 +333,9 @@ NEXT_PART: auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("client_id", clientId) - info, appErr := c.App.UploadFileX(c.Params.ChannelId, filename, part, + info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, filename, part, app.UploadFileSetTeamId(FileTeamId), - app.UploadFileSetUserId(c.App.Session().UserId), + app.UploadFileSetUserId(c.AppContext.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), app.UploadFileSetClientId(clientId)) @@ -396,7 +396,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.AppContext.Session(), channelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return nil } @@ -436,9 +436,9 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, auditRec.AddMeta("channel_id", channelId) auditRec.AddMeta("client_id", clientId) - info, appErr := c.App.UploadFileX(c.Params.ChannelId, fileHeader.Filename, f, + info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, fileHeader.Filename, f, app.UploadFileSetTeamId(FileTeamId), - app.UploadFileSetUserId(c.App.Session().UserId), + app.UploadFileSetUserId(c.AppContext.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), app.UploadFileSetClientId(clientId)) @@ -481,7 +481,7 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("file", info) - if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -512,7 +512,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.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -554,7 +554,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("file", info) - if info.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { + if info.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -587,7 +587,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.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -620,7 +620,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.AppContext.Session().UserId && !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), info.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -734,7 +734,7 @@ func searchFiles(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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -778,7 +778,7 @@ func searchFiles(c *Context, w http.ResponseWriter, r *http.Request) { startTime := time.Now() - results, err := c.App.SearchFilesInTeamForUser(terms, c.App.Session().UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) + results, err := c.App.SearchFilesInTeamForUser(c.AppContext, terms, c.AppContext.Session().UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) elapsedTime := float64(time.Since(startTime)) / float64(time.Second) metrics := c.App.Metrics() diff --git a/api4/file_test.go b/api4/file_test.go index d5164dfb670..f5d7b8249d3 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -1067,31 +1067,31 @@ func TestSearchFiles(t *testing.T) { Client := th.Client filename := "search for fileInfo1" - fileInfo1, appErr := th.App.UploadFile(data, th.BasicChannel.Id, filename) + fileInfo1, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo1.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "search for fileInfo2" - fileInfo2, appErr := th.App.UploadFile(data, th.BasicChannel.Id, filename) + fileInfo2, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo2.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "tagged search for fileInfo3" - fileInfo3, appErr := th.App.UploadFile(data, th.BasicChannel.Id, filename) + fileInfo3, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo3.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "tagged for fileInfo4" - fileInfo4, appErr := th.App.UploadFile(data, th.BasicChannel.Id, filename) + fileInfo4, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo4.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) archivedChannel := th.CreatePublicChannel() - fileInfo5, appErr := th.App.UploadFile(data, archivedChannel.Id, "tagged for fileInfo3") + fileInfo5, appErr := th.App.UploadFile(th.Context, data, archivedChannel.Id, "tagged for fileInfo3") require.Nil(t, appErr) post := &model.Post{ChannelId: archivedChannel.Id, Message: model.NewId() + "a"} rpost, resp := Client.CreatePost(post) diff --git a/api4/group.go b/api4/group.go index 35dffb61255..4e3bbc29117 100644 --- a/api4/group.go +++ b/api4/group.go @@ -88,7 +88,7 @@ func getGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -128,7 +128,7 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) return } @@ -247,7 +247,7 @@ func linkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.Srv().Go(func() { - c.App.SyncRolesAndMembership(syncableID, syncableType, false) + c.App.SyncRolesAndMembership(c.AppContext, syncableID, syncableType, false) }) w.WriteHeader(http.StatusCreated) @@ -284,7 +284,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -321,7 +321,7 @@ func getGroupSyncables(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -408,7 +408,7 @@ func patchGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("new_syncable_type", groupSyncable.Type) c.App.Srv().Go(func() { - c.App.SyncRolesAndMembership(syncableID, syncableType, false) + c.App.SyncRolesAndMembership(c.AppContext, syncableID, syncableType, false) }) b, marshalErr := json.Marshal(groupSyncable) @@ -462,7 +462,7 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.Srv().Go(func() { - c.App.SyncRolesAndMembership(syncableID, syncableType, false) + c.App.SyncRolesAndMembership(c.AppContext, syncableID, syncableType, false) }) auditRec.Success() @@ -473,8 +473,8 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType, syncableID string) *model.AppError { switch syncableType { case model.GroupSyncableTypeTeam: - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), syncableID, model.PERMISSION_MANAGE_TEAM) { - return c.App.MakePermissionError([]*model.Permission{model.PERMISSION_MANAGE_TEAM}) + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), syncableID, model.PERMISSION_MANAGE_TEAM) { + return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{model.PERMISSION_MANAGE_TEAM}) } case model.GroupSyncableTypeChannel: channel, err := c.App.GetChannel(syncableID) @@ -489,8 +489,8 @@ func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType permission = model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS } - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), syncableID, permission) { - return c.App.MakePermissionError([]*model.Permission{permission}) + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), syncableID, permission) { + return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{permission}) } } @@ -508,7 +508,7 @@ func getGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -545,7 +545,7 @@ func getGroupStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -575,7 +575,7 @@ func getGroupsByUserId(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.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -622,7 +622,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else { permission = model.PERMISSION_READ_PUBLIC_CHANNEL_GROUPS } - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), c.Params.ChannelId, permission) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, permission) { c.SetPermissionError(permission) return } @@ -784,7 +784,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.AppContext.Session(), channelID, permission) { c.SetPermissionError(permission) return } diff --git a/api4/group_test.go b/api4/group_test.go index a97f7df2cd4..24cfe6698d3 100644 --- a/api4/group_test.go +++ b/api4/group_test.go @@ -978,7 +978,7 @@ func TestGetGroupsByUserId(t *testing.T) { }) assert.Nil(t, err) - user1, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) assert.Nil(t, err) user1.Password = "test-password-1" _, err = th.App.UpsertGroupMember(group1.Id, user1.Id) @@ -1062,7 +1062,7 @@ func TestGetGroupStats(t *testing.T) { assert.Equal(t, stats.TotalMemberCount, int64(0)) }) - user1, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) assert.Nil(t, err) _, err = th.App.UpsertGroupMember(group.Id, user1.Id) assert.Nil(t, err) @@ -1104,7 +1104,7 @@ func TestGetGroupsGroupConstrainedParentTeam(t *testing.T) { TeamId: team.Id, GroupConstrained: model.NewBool(true), } - channel, err := th.App.CreateChannel(channel, false) + channel, err := th.App.CreateChannel(th.Context, channel, false) require.Nil(t, err) // normal result of groups are returned if the team is not group-constrained diff --git a/api4/handlers.go b/api4/handlers.go index 255837afad4..a08f9a465e0 100644 --- a/api4/handlers.go +++ b/api4/handlers.go @@ -17,16 +17,16 @@ type Context = web.Context // granted. func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -36,16 +36,16 @@ func (api *API) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) // be granted. func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: true, - TrustRequester: false, - RequireMfa: true, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: true, + TrustRequester: false, + RequireMfa: true, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -55,17 +55,17 @@ func (api *API) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.R // CloudApiKeyRequired provides a handler for webhook endpoints to access Cloud installations from CWS func (api *API) CloudApiKeyRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: false, - RequireCloudKey: true, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: false, + RequireCloudKey: true, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -75,7 +75,7 @@ func (api *API) CloudApiKeyRequired(h func(*Context, http.ResponseWriter, *http. // RemoteClusterTokenRequired provides a handler for remote cluster requests to /remotecluster endpoints. func (api *API) RemoteClusterTokenRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, + App: api.app, HandleFunc: h, HandlerName: web.GetHandlerName(h), RequireSession: false, @@ -86,7 +86,7 @@ func (api *API) RemoteClusterTokenRequired(h func(*Context, http.ResponseWriter, IsStatic: false, IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -97,16 +97,16 @@ func (api *API) RemoteClusterTokenRequired(h func(*Context, http.ResponseWriter, // authentication must be waived. func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: true, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: true, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -118,16 +118,16 @@ func (api *API) ApiSessionRequiredMfa(h func(*Context, http.ResponseWriter, *htt // websocket. func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: false, - TrustRequester: true, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: false, + TrustRequester: true, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -138,16 +138,16 @@ func (api *API) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, * // are allowed to be requested directly rather than via javascript/XMLHttpRequest, such as emoji or file uploads. func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: true, - TrustRequester: true, - RequireMfa: true, - IsStatic: false, - IsLocal: false, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: true, + TrustRequester: true, + RequireMfa: true, + IsStatic: false, + IsLocal: false, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -158,17 +158,17 @@ func (api *API) ApiSessionRequiredTrustRequester(h func(*Context, http.ResponseW // responding with HTTP 503 (Service Unavailable). func (api *API) ApiSessionRequiredDisableWhenBusy(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: true, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, - DisableWhenBusy: true, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: true, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, + DisableWhenBusy: true, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -181,17 +181,17 @@ func (api *API) ApiSessionRequiredDisableWhenBusy(h func(*Context, http.Response // restrictions func (api *API) ApiLocal(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &web.Handler{ - GetGlobalAppOptions: api.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: web.GetHandlerName(h), - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: true, + App: api.app, + HandleFunc: h, + HandlerName: web.GetHandlerName(h), + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: true, } - if *api.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *api.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler diff --git a/api4/handlers_test.go b/api4/handlers_test.go index cc7d142fc87..9d4d48b6a44 100644 --- a/api4/handlers_test.go +++ b/api4/handlers_test.go @@ -68,7 +68,7 @@ func TestAPIHandlersWithGzip(t *testing.T) { th := Setup(t) defer th.TearDown() - api := Init(th.Server, th.Server.AppOptions, th.Server.Router) + api := Init(th.App, th.Server.Router) session, _ := th.App.GetSession(th.Client.AuthToken) t.Run("with WebserverMode == \"gzip\"", func(t *testing.T) { diff --git a/api4/integration_action.go b/api4/integration_action.go index b15fc96be32..9e441880557 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.AppContext.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.AppContext.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.AppContext, c.Params.PostId, c.Params.ActionId, c.AppContext.Session().UserId, actionRequest.SelectedOption, cookie) if appErr != nil { c.Err = appErr @@ -101,19 +101,19 @@ func submitDialog(c *Context, w http.ResponseWriter, r *http.Request) { return } - submit.UserId = c.App.Session().UserId + submit.UserId = c.AppContext.Session().UserId - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), submit.ChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.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.AppContext.Session(), submit.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } - resp, err := c.App.SubmitInteractiveDialog(submit) + resp, err := c.App.SubmitInteractiveDialog(c.AppContext, submit) if err != nil { c.Err = err return diff --git a/api4/job.go b/api4/job.go index 428f1a007fb..cbbb91fc082 100644 --- a/api4/job.go +++ b/api4/job.go @@ -35,7 +35,7 @@ func getJob(c *Context, w http.ResponseWriter, r *http.Request) { return } - hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.App.Session(), job.Type) + hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), job.Type) if permissionRequired == nil { c.Err = model.NewAppError("getJob", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest) return @@ -71,7 +71,7 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) { // Currently, this endpoint only supports downloading the compliance report. // If you need to download another job type, you will need to alter this section of the code to accommodate it. - if job.Type == model.JOB_TYPE_MESSAGE_EXPORT && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { + if job.Type == model.JOB_TYPE_MESSAGE_EXPORT && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) { c.SetPermissionError(model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT) return } else if job.Type != model.JOB_TYPE_MESSAGE_EXPORT { @@ -111,7 +111,7 @@ func createJob(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("job", job) - hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.App.Session(), job) + hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), job) if permissionRequired == nil { c.Err = model.NewAppError("unableToCreateJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest) return @@ -142,7 +142,7 @@ func getJobs(c *Context, w http.ResponseWriter, r *http.Request) { var validJobTypes []string for _, jobType := range model.ALL_JOB_TYPES { - hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.App.Session(), jobType) + hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), jobType) if permissionRequired == nil { mlog.Warn("The job types of a job you are trying to retrieve does not contain permissions", mlog.String("jobType", jobType)) continue @@ -171,7 +171,7 @@ func getJobsByType(c *Context, w http.ResponseWriter, r *http.Request) { return } - hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.App.Session(), c.Params.JobType) + hasPermission, permissionRequired := c.App.SessionHasPermissionToReadJob(*c.AppContext.Session(), c.Params.JobType) if permissionRequired == nil { c.Err = model.NewAppError("getJobsByType", "api.job.retrieve.nopermissions", nil, "", http.StatusBadRequest) return @@ -207,7 +207,7 @@ func cancelJob(c *Context, w http.ResponseWriter, r *http.Request) { } // if permission to create, permission to cancel, same permission - hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.App.Session(), job) + hasPermission, permissionRequired := c.App.SessionHasPermissionToCreateJob(*c.AppContext.Session(), job) if permissionRequired == nil { c.Err = model.NewAppError("unableToCancelJob", "api.job.unable_to_create_job.incorrect_job_type", nil, "", http.StatusBadRequest) return diff --git a/api4/ldap.go b/api4/ldap.go index 7b89fc35e32..18102d4986f 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -56,7 +56,7 @@ func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("syncLdap", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_LDAP_SYNC_JOB) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_LDAP_SYNC_JOB) { c.SetPermissionError(model.PERMISSION_CREATE_LDAP_SYNC_JOB) return } @@ -73,7 +73,7 @@ func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_TEST_LDAP) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_LDAP) { c.SetPermissionError(model.PERMISSION_TEST_LDAP) return } @@ -87,7 +87,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_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -144,7 +144,7 @@ func linkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) return } @@ -245,7 +245,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("remote_id", c.Params.RemoteId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_GROUPS) return } @@ -285,7 +285,7 @@ func migrateIdLdap(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("idMigrateLdap", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -325,7 +325,7 @@ func parseLdapCertificateRequest(r *http.Request, maxFileSize int64) (*multipart } func addLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_ADD_LDAP_PUBLIC_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_LDAP_PUBLIC_CERT) { c.SetPermissionError(model.PERMISSION_ADD_LDAP_PUBLIC_CERT) return } @@ -349,7 +349,7 @@ func addLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request } func addLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_ADD_LDAP_PRIVATE_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_LDAP_PRIVATE_CERT) { c.SetPermissionError(model.PERMISSION_ADD_LDAP_PRIVATE_CERT) return } @@ -373,7 +373,7 @@ func addLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Reques } func removeLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT) { c.SetPermissionError(model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT) return } @@ -391,7 +391,7 @@ func removeLdapPublicCertificate(c *Context, w http.ResponseWriter, r *http.Requ } func removeLdapPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT) { c.SetPermissionError(model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT) return } diff --git a/api4/license.go b/api4/license.go index 5a6c4347287..3466ef42870 100644 --- a/api4/license.go +++ b/api4/license.go @@ -38,7 +38,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_READ_LICENSE_INFORMATION) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_LICENSE_INFORMATION) { clientLicense = c.App.Srv().ClientLicense() } else { clientLicense = c.App.Srv().GetSanitizedClientLicense() @@ -52,7 +52,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) return } @@ -118,7 +118,7 @@ func removeLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) return } @@ -144,7 +144,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) return } @@ -175,7 +175,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { return } - currentUser, err := c.App.GetUser(c.App.Session().UserId) + currentUser, err := c.App.GetUser(c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -213,7 +213,7 @@ func requestRenewalLink(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_LICENSE_INFORMATION) { c.SetPermissionError(model.PERMISSION_MANAGE_LICENSE_INFORMATION) return } diff --git a/api4/oauth.go b/api4/oauth.go index ed27bd4eb64..8adf9cb7729 100644 --- a/api4/oauth.go +++ b/api4/oauth.go @@ -33,16 +33,16 @@ func createOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("createOAuthApp", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { oauthApp.IsTrusted = false } - oauthApp.CreatorId = c.App.Session().UserId + oauthApp.CreatorId = c.AppContext.Session().UserId rapp, err := c.App.CreateOAuthApp(oauthApp) if err != nil { @@ -69,7 +69,7 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("oauth_app_id", c.Params.AppId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -93,12 +93,12 @@ func updateOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("oauth_app", oldOauthApp) - if c.App.Session().UserId != oldOauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.AppContext.Session().UserId != oldOauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { oauthApp.IsTrusted = oldOauthApp.IsTrusted } @@ -116,17 +116,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.AppContext.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.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { + apps, err = c.App.GetOAuthAppsByCreator(c.AppContext.Session().UserId, c.Params.Page, c.Params.PerPage) } else { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return @@ -146,7 +146,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.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -157,7 +157,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.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -192,7 +192,7 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("oauth_app_id", c.Params.AppId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -204,7 +204,7 @@ func deleteOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("oauth_app", oauthApp) - if c.App.Session().UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if c.AppContext.Session().UserId != oauthApp.CreatorId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -231,7 +231,7 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request defer c.LogAuditRec(auditRec) auditRec.AddMeta("oauth_app_id", c.Params.AppId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_OAUTH) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_OAUTH) return } @@ -243,7 +243,7 @@ func regenerateOAuthAppSecret(c *Context, w http.ResponseWriter, r *http.Request } auditRec.AddMeta("oauth_app", oauthApp) - if oauthApp.CreatorId != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { + if oauthApp.CreatorId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM_WIDE_OAUTH) return } @@ -266,7 +266,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/openGraph.go b/api4/openGraph.go index 45b20c4de4c..3215d7014a4 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -21,7 +21,7 @@ func (api *API) InitOpenGraph() { api.BaseRoutes.OpenGraph.Handle("", api.ApiSessionRequired(getOpenGraphMetadata)).Methods("POST") // Dump the image cache if the proxy settings have changed. (need switch URLs to the correct proxy) - api.ConfigService.AddConfigListener(func(before, after *model.Config) { + api.app.AddConfigListener(func(before, after *model.Config) { if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) || (before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) || (before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) || diff --git a/api4/plugin.go b/api4/plugin.go index 8ab71803e68..6330f76775c 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -55,7 +55,7 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("uploadPlugin", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -106,7 +106,7 @@ func installPluginFromUrl(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("installPluginFromUrl", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -139,7 +139,7 @@ func installMarketplacePlugin(c *Context, w http.ResponseWriter, r *http.Request auditRec := c.MakeAuditRecord("installMarketplacePlugin", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -171,7 +171,7 @@ func getPlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) return } @@ -191,7 +191,7 @@ func getPluginStatuses(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) return } @@ -220,7 +220,7 @@ func removePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -272,7 +272,7 @@ func getMarketplacePlugins(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_PLUGINS) return } @@ -313,7 +313,7 @@ func enablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -342,7 +342,7 @@ func disablePlugin(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("plugin_id", c.Params.PluginId) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_PLUGINS) return } @@ -394,7 +394,7 @@ func setFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -422,7 +422,7 @@ func getFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/post.go b/api4/post.go index cc3c95bf1ee..305a7d9419a 100644 --- a/api4/post.go +++ b/api4/post.go @@ -42,18 +42,18 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - post.UserId = c.App.Session().UserId + post.UserId = c.AppContext.Session().UserId auditRec := c.MakeAuditRecord("createPost", audit.Fail) defer c.LogAuditRecWithLevel(auditRec, app.LevelContent) auditRec.AddMeta("post", post) hasPermission := false - if c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_CREATE_POST) { + if c.App.SessionHasPermissionToChannel(*c.AppContext.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.AppContext.Session(), channel.TeamId, model.PERMISSION_CREATE_POST_PUBLIC) { hasPermission = true } } @@ -63,7 +63,7 @@ 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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { post.CreateAt = 0 } @@ -78,7 +78,7 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { } } - rp, err := c.App.CreatePostAsUser(c.App.PostWithProxyRemovedFromImageURLs(post), c.App.Session().Id, setOnlineBool) + rp, err := c.App.CreatePostAsUser(c.AppContext, c.App.PostWithProxyRemovedFromImageURLs(post), c.AppContext.Session().Id, setOnlineBool) if err != nil { c.Err = err return @@ -87,10 +87,10 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("post", rp) // overwrite meta if setOnlineBool { - c.App.SetStatusOnline(c.App.Session().UserId, false) + c.App.SetStatusOnline(c.AppContext.Session().UserId, false) } - c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) + c.App.UpdateLastActivityAtIfNeeded(*c.AppContext.Session()) c.ExtendSessionExpiryIfNeeded(w, r) w.WriteHeader(http.StatusCreated) @@ -113,10 +113,10 @@ func createEphemeralPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - ephRequest.Post.UserId = c.App.Session().UserId + ephRequest.Post.UserId = c.AppContext.Session().UserId ephRequest.Post.CreateAt = model.GetMillis() - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_POST_EPHEMERAL) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_CREATE_POST_EPHEMERAL) { c.SetPermissionError(model.PERMISSION_CREATE_POST_EPHEMERAL) return } @@ -164,7 +164,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.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -174,7 +174,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { etag := "" if since > 0 { - list, err = c.App.GetPostsSince(model.GetPostsSinceOptions{ChannelId: channelId, Time: since, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.App.Session().UserId}) + list, err = c.App.GetPostsSince(model.GetPostsSinceOptions{ChannelId: channelId, Time: since, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.AppContext.Session().UserId}) } else if afterPost != "" { etag = c.App.GetPostsEtag(channelId, collapsedThreads) @@ -182,7 +182,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - list, err = c.App.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: afterPost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, UserId: c.App.Session().UserId}) + list, err = c.App.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: afterPost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, UserId: c.AppContext.Session().UserId}) } else if beforePost != "" { etag = c.App.GetPostsEtag(channelId, collapsedThreads) @@ -190,7 +190,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - list, err = c.App.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: beforePost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.App.Session().UserId}) + list, err = c.App.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: beforePost, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.AppContext.Session().UserId}) } else { etag = c.App.GetPostsEtag(channelId, collapsedThreads) @@ -198,7 +198,7 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - list, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.App.Session().UserId}) + list, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: page, PerPage: perPage, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.AppContext.Session().UserId}) } if err != nil { @@ -223,13 +223,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.AppContext.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.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -257,7 +257,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht return } - postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PageDefault, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.App.Session().UserId}) + postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PageDefault, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads, CollapsedThreads: collapsedThreads, CollapsedThreadsExtended: collapsedThreadsExtended, UserId: c.AppContext.Session().UserId}) if err != nil { c.Err = err return @@ -281,7 +281,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -313,7 +313,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.AppContext.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { allowed = true } @@ -350,9 +350,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.AppContext.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.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } @@ -389,19 +389,19 @@ func deletePost(c *Context, w http.ResponseWriter, _ *http.Request) { } auditRec.AddMeta("post", post) - if c.App.Session().UserId == post.UserId { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_DELETE_POST) { + if c.AppContext.Session().UserId == post.UserId { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PERMISSION_DELETE_POST) { c.SetPermissionError(model.PERMISSION_DELETE_POST) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), post.ChannelId, model.PERMISSION_DELETE_OTHERS_POSTS) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.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.AppContext.Session().UserId); err != nil { c.Err = err return } @@ -418,7 +418,7 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { skipFetchThreads := r.URL.Query().Get("skipFetchThreads") == "true" collapsedThreads := r.URL.Query().Get("collapsedThreads") == "true" collapsedThreadsExtended := r.URL.Query().Get("collapsedThreadsExtended") == "true" - list, err := c.App.GetPostThread(c.Params.PostId, skipFetchThreads, collapsedThreads, collapsedThreadsExtended, c.App.Session().UserId) + list, err := c.App.GetPostThread(c.Params.PostId, skipFetchThreads, collapsedThreads, collapsedThreadsExtended, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -436,9 +436,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.AppContext.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.AppContext.Session(), channel.TeamId, model.PERMISSION_READ_PUBLIC_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_PUBLIC_CHANNEL) return } @@ -465,7 +465,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -509,7 +509,7 @@ 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(c.AppContext, terms, c.AppContext.Session().UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) elapsedTime := float64(time.Since(startTime)) / float64(time.Second) metrics := c.App.Metrics() @@ -553,7 +553,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.AppContext.Session(), c.Params.PostId, model.PERMISSION_EDIT_POST) { c.SetPermissionError(model.PERMISSION_EDIT_POST) return } @@ -568,8 +568,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.AppContext.Session().UserId != originalPost.UserId { + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, model.PERMISSION_EDIT_OTHERS_POSTS) { c.SetPermissionError(model.PERMISSION_EDIT_OTHERS_POSTS) return } @@ -577,7 +577,7 @@ func updatePost(c *Context, w http.ResponseWriter, r *http.Request) { post.Id = c.Params.PostId - rpost, err := c.App.UpdatePost(c.App.PostWithProxyRemovedFromImageURLs(post), false) + rpost, err := c.App.UpdatePost(c.AppContext, c.App.PostWithProxyRemovedFromImageURLs(post), false) if err != nil { c.Err = err return @@ -616,18 +616,18 @@ func patchPost(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("post", originalPost) var permission *model.Permission - if c.App.Session().UserId == originalPost.UserId { + if c.AppContext.Session().UserId == originalPost.UserId { permission = model.PERMISSION_EDIT_POST } else { permission = model.PERMISSION_EDIT_OTHERS_POSTS } - if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, permission) { + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.Session(), c.Params.PostId, permission) { c.SetPermissionError(permission) return } - patchedPost, err := c.App.PatchPost(c.Params.PostId, c.App.PostPatchWithProxyRemovedFromImageURLs(post)) + patchedPost, err := c.App.PatchPost(c.AppContext, c.Params.PostId, c.App.PostPatchWithProxyRemovedFromImageURLs(post)) if err != nil { c.Err = err return @@ -644,11 +644,11 @@ func setPostUnread(c *Context, w http.ResponseWriter, _ *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.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionToUser(*c.AppContext.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.AppContext.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -670,13 +670,13 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, isPinned bool) { auditRec := c.MakeAuditRecord("saveIsPinnedPost", audit.Fail) defer c.LogAuditRecWithLevel(auditRec, app.LevelContent) - if !c.App.SessionHasPermissionToChannelByPost(*c.App.Session(), c.Params.PostId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannelByPost(*c.AppContext.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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -706,7 +706,7 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, isPinned bool) { patch := &model.PostPatch{} patch.IsPinned = model.NewBool(isPinned) - patchedPost, err := c.App.PatchPost(c.Params.PostId, patch) + patchedPost, err := c.App.PatchPost(c.AppContext, c.Params.PostId, patch) if err != nil { c.Err = err return @@ -731,7 +731,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.AppContext.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 57df5bc417b..6250aba0bb5 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -100,7 +100,7 @@ func TestCreatePost(t *testing.T) { }) t.Run("with file uploaded by nouser", func(t *testing.T) { - fileInfo, err := th.App.UploadFile([]byte("data"), th.BasicChannel.Id, "test") + fileInfo, err := th.App.UploadFile(th.Context, []byte("data"), th.BasicChannel.Id, "test") require.Nil(t, err) fileId := fileInfo.Id @@ -460,7 +460,7 @@ func TestCreatePostPublic(t *testing.T) { CheckForbiddenStatus(t, resp) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) - th.App.JoinUserToTeam(th.BasicTeam, ruser, "") + th.App.JoinUserToTeam(th.Context, th.BasicTeam, ruser, "") th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID) th.App.Srv().InvalidateAllCaches() @@ -484,7 +484,7 @@ func TestCreatePostAll(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID} - directChannel, _ := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + directChannel, _ := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) ruser, resp := Client.CreateUser(&user) CheckNoError(t, resp) @@ -511,7 +511,7 @@ func TestCreatePostAll(t *testing.T) { CheckNoError(t, resp) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) - th.App.JoinUserToTeam(th.BasicTeam, ruser, "") + th.App.JoinUserToTeam(th.Context, th.BasicTeam, ruser, "") th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID) th.App.Srv().InvalidateAllCaches() @@ -595,7 +595,7 @@ func TestCreatePostCheckOnlineStatus(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - api := Init(th.Server, th.Server.AppOptions, th.Server.Router) + api := Init(th.App, th.Server.Router) session, _ := th.App.GetSession(th.Client.AuthToken) cli := th.CreateClient() @@ -673,7 +673,7 @@ func TestUpdatePost(t *testing.T) { fileIds[i] = fileResp.FileInfos[0].Id } - rpost, appErr := th.App.CreatePost(&model.Post{ + rpost, appErr := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", @@ -729,7 +729,7 @@ func TestUpdatePost(t *testing.T) { }) t.Run("join/leave post", func(t *testing.T) { - rpost2, err := th.App.CreatePost(&model.Post{ + rpost2, err := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", Type: model.POST_JOIN_LEAVE, @@ -746,7 +746,7 @@ func TestUpdatePost(t *testing.T) { CheckBadRequestStatus(t, resp) }) - rpost3, appErr := th.App.CreatePost(&model.Post{ + rpost3, appErr := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id, @@ -1317,7 +1317,7 @@ func TestGetFlaggedPostsForUser(t *testing.T) { require.Len(t, rpl.Posts, 4, "should have returned 4 posts") require.Equal(t, opl.Posts, rpl.Posts, "posts should have matched") - err := th.App.RemoveUserFromChannel(user.Id, "", channel4) + err := th.App.RemoveUserFromChannel(th.Context, user.Id, "", channel4) assert.Nil(t, err, "unable to remove user from channel") rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10) @@ -2557,9 +2557,9 @@ func TestMarkUnreadCausesAutofollow(t *testing.T) { *cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON }) - rootPost, appErr := th.App.CreatePost(&model.Post{UserId: th.BasicUser2.Id, CreateAt: model.GetMillis(), ChannelId: th.BasicChannel.Id, Message: "hi"}, th.BasicChannel, false, false) + rootPost, appErr := th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser2.Id, CreateAt: model.GetMillis(), ChannelId: th.BasicChannel.Id, Message: "hi"}, th.BasicChannel, false, false) require.Nil(t, appErr) - replyPost, appErr := th.App.CreatePost(&model.Post{RootId: rootPost.Id, UserId: th.BasicUser2.Id, CreateAt: model.GetMillis(), ChannelId: th.BasicChannel.Id, Message: "hi"}, th.BasicChannel, false, false) + replyPost, appErr := th.App.CreatePost(th.Context, &model.Post{RootId: rootPost.Id, UserId: th.BasicUser2.Id, CreateAt: model.GetMillis(), ChannelId: th.BasicChannel.Id, Message: "hi"}, th.BasicChannel, false, false) require.Nil(t, appErr) threads, appErr := th.App.GetThreadsForUser(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{}) require.Nil(t, appErr) diff --git a/api4/preference.go b/api4/preference.go index a41742a5b5e..82f9ad22417 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -24,7 +24,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -44,7 +44,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -64,7 +64,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -87,7 +87,7 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("updatePreferences", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -108,7 +108,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.AppContext.Session(), post.ChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -135,7 +135,7 @@ func deletePreferences(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deletePreferences", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/reaction.go b/api4/reaction.go index eb2ea8902ea..e8528979294 100644 --- a/api4/reaction.go +++ b/api4/reaction.go @@ -28,17 +28,17 @@ func saveReaction(c *Context, w http.ResponseWriter, r *http.Request) { return } - if reaction.UserId != c.App.Session().UserId { + if reaction.UserId != c.AppContext.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.AppContext.Session(), reaction.PostId, model.PERMISSION_ADD_REACTION) { c.SetPermissionError(model.PERMISSION_ADD_REACTION) return } - reaction, err := c.App.SaveReactionForPost(reaction) + reaction, err := c.App.SaveReactionForPost(c.AppContext, reaction) if err != nil { c.Err = err 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.AppContext.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.AppContext.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.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_OTHERS_REACTIONS) { c.SetPermissionError(model.PERMISSION_REMOVE_OTHERS_REACTIONS) return } @@ -99,7 +99,7 @@ func deleteReaction(c *Context, w http.ResponseWriter, r *http.Request) { EmojiName: c.Params.EmojiName, } - err := c.App.DeleteReactionForPost(reaction) + err := c.App.DeleteReactionForPost(c.AppContext, reaction) if err != nil { c.Err = err 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.AppContext.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 e9fcf4462f7..52a2250173c 100644 --- a/api4/reaction_test.go +++ b/api4/reaction_test.go @@ -194,7 +194,7 @@ func TestSaveReaction(t *testing.T) { EmojiName: "smile", } - err := th.App.DeleteChannel(channel, userId) + err := th.App.DeleteChannel(th.Context, channel, userId) assert.Nil(t, err) _, resp := Client.SaveReaction(reaction) @@ -324,7 +324,7 @@ func TestDeleteReaction(t *testing.T) { }() t.Run("delete-reaction", func(t *testing.T) { - th.App.SaveReactionForPost(r1) + th.App.SaveReactionForPost(th.Context, r1) reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 1, len(reactions), "didn't save reaction correctly") @@ -340,8 +340,8 @@ func TestDeleteReaction(t *testing.T) { }) t.Run("delete-reaction-when-post-has-multiple-reactions", func(t *testing.T) { - th.App.SaveReactionForPost(r1) - th.App.SaveReactionForPost(r2) + th.App.SaveReactionForPost(th.Context, r1) + th.App.SaveReactionForPost(th.Context, r2) reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, len(reactions), 2, "didn't save reactions correctly") @@ -356,7 +356,7 @@ func TestDeleteReaction(t *testing.T) { }) t.Run("delete-reaction-when-plus-one-reaction-name", func(t *testing.T) { - th.App.SaveReactionForPost(r3) + th.App.SaveReactionForPost(th.Context, r3) reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 2, len(reactions), "didn't save reactions correctly") @@ -372,7 +372,7 @@ func TestDeleteReaction(t *testing.T) { t.Run("delete-reaction-made-by-another-user", func(t *testing.T) { th.LoginBasic2() - th.App.SaveReactionForPost(r4) + th.App.SaveReactionForPost(th.Context, r4) reactions, err := th.App.GetReactionsForPost(postId) require.Nil(t, err) require.Equal(t, 2, len(reactions), "didn't save reaction correctly") @@ -456,7 +456,7 @@ func TestDeleteReaction(t *testing.T) { th.LoginBasic() th.RemovePermissionFromRole(model.PERMISSION_REMOVE_REACTION.Id, model.CHANNEL_USER_ROLE_ID) - th.App.SaveReactionForPost(r1) + th.App.SaveReactionForPost(th.Context, r1) _, resp := Client.DeleteReaction(r1) CheckForbiddenStatus(t, resp) @@ -469,7 +469,7 @@ func TestDeleteReaction(t *testing.T) { t.Run("unable-to-delete-others-reactions-without-permissions", func(t *testing.T) { th.RemovePermissionFromRole(model.PERMISSION_REMOVE_OTHERS_REACTIONS.Id, model.SYSTEM_ADMIN_ROLE_ID) - th.App.SaveReactionForPost(r1) + th.App.SaveReactionForPost(th.Context, r1) _, resp := th.SystemAdminClient.DeleteReaction(r1) CheckForbiddenStatus(t, resp) @@ -534,7 +534,7 @@ func TestDeleteReaction(t *testing.T) { require.Nil(t, err) require.Equal(t, 1, len(reactions), "should have created a reaction") - err = th.App.DeleteChannel(channel, userId) + err = th.App.DeleteChannel(th.Context, channel, userId) assert.Nil(t, err) _, resp = Client.SaveReaction(r1) diff --git a/api4/remote_cluster.go b/api4/remote_cluster.go index 0b667e60b4d..0983dba0987 100644 --- a/api4/remote_cluster.go +++ b/api4/remote_cluster.go @@ -104,7 +104,7 @@ func remoteClusterAcceptMessage(c *Context, w http.ResponseWriter, r *http.Reque auditRec.AddMeta("remoteCluster", rc) // pass message to Remote Cluster Service and write response - resp := service.ReceiveIncomingMsg(rc, frame.Msg) + resp := service.ReceiveIncomingMsg(c.AppContext, rc, frame.Msg) b, errMarshall := json.Marshal(resp) if errMarshall != nil { diff --git a/api4/role.go b/api4/role.go index 4c179a172c9..5c1eba832be 100644 --- a/api4/role.go +++ b/api4/role.go @@ -118,7 +118,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { requiredPermission = model.PERMISSION_MANAGE_SYSTEM } } - if !c.App.SessionHasPermissionTo(*c.App.Session(), requiredPermission) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), requiredPermission) { c.SetPermissionError(requiredPermission) return } @@ -172,12 +172,12 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { } if oldRole.Name == model.TEAM_ADMIN_ROLE_ID || oldRole.Name == model.CHANNEL_ADMIN_ROLE_ID || oldRole.Name == model.SYSTEM_USER_ROLE_ID || oldRole.Name == model.TEAM_USER_ROLE_ID || oldRole.Name == model.CHANNEL_USER_ROLE_ID || oldRole.Name == model.SYSTEM_GUEST_ROLE_ID || oldRole.Name == model.TEAM_GUEST_ROLE_ID || oldRole.Name == model.CHANNEL_GUEST_ROLE_ID { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } } else { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES) return } diff --git a/api4/saml.go b/api4/saml.go index a9ff6dfe189..0cd98c6bdb5 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -69,7 +69,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_ADD_SAML_PUBLIC_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_PUBLIC_CERT) { c.SetPermissionError(model.PERMISSION_ADD_SAML_PUBLIC_CERT) return } @@ -93,7 +93,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_ADD_SAML_PRIVATE_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_PRIVATE_CERT) { c.SetPermissionError(model.PERMISSION_ADD_SAML_PRIVATE_CERT) return } @@ -117,7 +117,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_ADD_SAML_IDP_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_ADD_SAML_IDP_CERT) { c.SetPermissionError(model.PERMISSION_ADD_SAML_IDP_CERT) return } @@ -170,7 +170,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_REMOVE_SAML_PUBLIC_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_PUBLIC_CERT) { c.SetPermissionError(model.PERMISSION_REMOVE_SAML_PUBLIC_CERT) return } @@ -188,7 +188,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_REMOVE_SAML_PRIVATE_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_PRIVATE_CERT) { c.SetPermissionError(model.PERMISSION_REMOVE_SAML_PRIVATE_CERT) return } @@ -206,7 +206,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_REMOVE_SAML_IDP_CERT) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REMOVE_SAML_IDP_CERT) { c.SetPermissionError(model.PERMISSION_REMOVE_SAML_IDP_CERT) return } @@ -224,7 +224,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_GET_SAML_CERT_STATUS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_SAML_CERT_STATUS) { c.SetPermissionError(model.PERMISSION_GET_SAML_CERT_STATUS) return } @@ -234,7 +234,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_GET_SAML_METADATA_FROM_IDP) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_SAML_METADATA_FROM_IDP) { c.SetPermissionError(model.PERMISSION_GET_SAML_METADATA_FROM_IDP) return } @@ -256,7 +256,7 @@ func getSamlMetadataFromIdp(c *Context, w http.ResponseWriter, r *http.Request) } func resetAuthDataToEmail(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } diff --git a/api4/scheme.go b/api4/scheme.go index f764136107d..9bbaa2c079f 100644 --- a/api4/scheme.go +++ b/api4/scheme.go @@ -36,7 +36,7 @@ func createScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } @@ -60,7 +60,7 @@ func getScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) return } @@ -75,7 +75,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_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_PERMISSIONS) return } @@ -101,7 +101,7 @@ func getTeamsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_TEAMS) return } @@ -132,7 +132,7 @@ func getChannelsForScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_CHANNELS) return } @@ -184,7 +184,7 @@ func patchScheme(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("scheme", scheme) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } @@ -216,7 +216,7 @@ func deleteScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } diff --git a/api4/scheme_test.go b/api4/scheme_test.go index e492bed5396..2c25791d292 100644 --- a/api4/scheme_test.go +++ b/api4/scheme_test.go @@ -770,7 +770,7 @@ func TestUpdateTeamSchemeWithTeamMembers(t *testing.T) { th.App.SetPhase2PermissionsMigrationStatus(true) team := th.CreateTeam() - _, _, err := th.App.AddUserToTeam(team.Id, th.BasicUser.Id, th.SystemAdminUser.Id) + _, _, err := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, th.SystemAdminUser.Id) require.Nil(t, err) teamScheme := th.SetupTeamScheme() diff --git a/api4/shared_channel.go b/api4/shared_channel.go index 3baf6931e0d..306144355de 100644 --- a/api4/shared_channel.go +++ b/api4/shared_channel.go @@ -59,7 +59,7 @@ func getRemoteClusterInfo(c *Context, w http.ResponseWriter, r *http.Request) { // GetRemoteClusterForUser will only return a remote if the user is a member of at // least one channel shared by the remote. All other cases return error. - rc, appErr := c.App.GetRemoteClusterForUser(c.Params.RemoteId, c.App.Session().UserId) + rc, appErr := c.App.GetRemoteClusterForUser(c.Params.RemoteId, c.AppContext.Session().UserId) if appErr != nil { c.Err = appErr return diff --git a/api4/status.go b/api4/status.go index 32925d3eb8e..cf2e3590fa4 100644 --- a/api4/status.go +++ b/api4/status.go @@ -88,7 +88,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -132,7 +132,7 @@ func updateUserCustomStatus(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -158,7 +158,7 @@ func removeUserCustomStatus(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -188,7 +188,7 @@ func removeUserRecentCustomStatus(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/system.go b/api4/system.go index e5cf34298a3..4108ccc290a 100644 --- a/api4/system.go +++ b/api4/system.go @@ -76,7 +76,7 @@ func generateSupportPacket(c *Context, w http.ResponseWriter, r *http.Request) { // Checking to see if the user is a admin of any sort or not // If they are a admin, they should theoritcally have access to one or more of the system console read permissions - if !c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleReadPermissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleReadPermissions) { c.SetPermissionError(model.SysconsoleReadPermissions...) return } @@ -195,7 +195,7 @@ func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_TEST_EMAIL) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_EMAIL) { c.SetPermissionError(model.PERMISSION_TEST_EMAIL) return } @@ -205,7 +205,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.AppContext.Session().UserId, cfg) if err != nil { c.Err = err return @@ -215,7 +215,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_TEST_SITE_URL) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_SITE_URL) { c.SetPermissionError(model.PERMISSION_TEST_SITE_URL) return } @@ -245,7 +245,7 @@ func getAudits(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("getAudits", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_AUDITS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_AUDITS) { c.SetPermissionError(model.PERMISSION_READ_AUDITS) return } @@ -264,7 +264,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_RECYCLE_DATABASE_CONNECTIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS) { c.SetPermissionError(model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS) return } @@ -284,7 +284,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_INVALIDATE_CACHES) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_INVALIDATE_CACHES) { c.SetPermissionError(model.PERMISSION_INVALIDATE_CACHES) return } @@ -318,7 +318,7 @@ func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_GET_LOGS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_LOGS) { c.SetPermissionError(model.PERMISSION_GET_LOGS) return } @@ -339,12 +339,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.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { forceToDebug = true } } @@ -360,7 +360,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.AppContext.UserAgent()), } if !forceToDebug && lvl == "ERROR" { @@ -381,7 +381,7 @@ func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { name = "standard" } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_GET_ANALYTICS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_GET_ANALYTICS) { c.SetPermissionError(model.PERMISSION_GET_ANALYTICS) return } @@ -421,7 +421,7 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) { cfg = c.App.Config() } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_TEST_S3) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_TEST_S3) { c.SetPermissionError(model.PERMISSION_TEST_S3) return } @@ -533,7 +533,7 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { return } - msg, appError := notificationInterface.GetNotificationMessage(ack, c.App.Session().UserId) + msg, appError := notificationInterface.GetNotificationMessage(ack, c.AppContext.Session().UserId) if appError != nil { c.Err = model.NewAppError("pushNotificationAck", "api.push_notification.id_loaded.fetch.app_error", nil, appError.Error(), http.StatusInternalServerError) return @@ -551,7 +551,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -580,7 +580,7 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { } func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -596,7 +596,7 @@ func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { } func getServerBusyExpires(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -607,7 +607,7 @@ func upgradeToEnterprise(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("upgradeToEnterprise", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -663,7 +663,7 @@ func upgradeToEnterprise(c *Context, w http.ResponseWriter, r *http.Request) { } func upgradeToEnterpriseStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -691,7 +691,7 @@ func restart(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("restartServer", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -706,7 +706,7 @@ func restart(c *Context, w http.ResponseWriter, r *http.Request) { } func getWarnMetricsStatus(c *Context, w http.ResponseWriter, r *http.Request) { - if !c.App.SessionHasPermissionToAny(*c.App.Session(), model.SysconsoleReadPermissions) { + if !c.App.SessionHasPermissionToAny(*c.AppContext.Session(), model.SysconsoleReadPermissions) { c.SetPermissionError(model.SysconsoleReadPermissions...) return } @@ -731,7 +731,7 @@ func sendWarnMetricAckEmail(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -742,7 +742,7 @@ func sendWarnMetricAckEmail(c *Context, w http.ResponseWriter, r *http.Request) return } - user, appErr := c.App.GetUser(c.App.Session().UserId) + user, appErr := c.App.GetUser(c.AppContext.Session().UserId) if appErr != nil { c.Err = appErr return @@ -768,7 +768,7 @@ func requestTrialLicenseAndAckWarnMetric(c *Context, w http.ResponseWriter, r *h defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -784,7 +784,7 @@ func requestTrialLicenseAndAckWarnMetric(c *Context, w http.ResponseWriter, r *h return } - if err := c.App.RequestLicenseAndAckWarnMetric(c.Params.WarnMetricId, false); err != nil { + if err := c.App.RequestLicenseAndAckWarnMetric(c.AppContext, c.Params.WarnMetricId, false); err != nil { c.Err = err return } @@ -807,7 +807,7 @@ func getProductNotices(c *Context, w http.ResponseWriter, r *http.Request) { clientVersion := r.URL.Query().Get("clientVersion") locale := r.URL.Query().Get("locale") - notices, err := c.App.GetProductNotices(c.App.Session().UserId, c.Params.TeamId, client, clientVersion, locale) + notices, err := c.App.GetProductNotices(c.AppContext, c.AppContext.Session().UserId, c.Params.TeamId, client, clientVersion, locale) if err != nil { c.Err = err @@ -823,7 +823,7 @@ func updateViewedProductNotices(c *Context, w http.ResponseWriter, r *http.Reque c.LogAudit("attempt") ids := model.ArrayFromJson(r.Body) - err := c.App.UpdateViewedProductNotices(c.App.Session().UserId, ids) + err := c.App.UpdateViewedProductNotices(c.AppContext.Session().UserId, ids) if err != nil { c.Err = err return diff --git a/api4/system_test.go b/api4/system_test.go index c327a5955e5..6f87e2f65ee 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -734,7 +734,7 @@ func TestServerBusy503(t *testing.T) { func TestPushNotificationAck(t *testing.T) { th := Setup(t) - api := Init(th.Server, th.Server.AppOptions, th.Server.Router) + api := Init(th.App, th.Server.Router) session, _ := th.App.GetSession(th.Client.AuthToken) defer th.TearDown() t.Run("should return error when the ack body is not passed", func(t *testing.T) { diff --git a/api4/team.go b/api4/team.go index 64aa726e410..bf00ecc2034 100644 --- a/api4/team.go +++ b/api4/team.go @@ -88,12 +88,12 @@ func createTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_CREATE_TEAM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.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(c.AppContext, team, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -120,12 +120,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.AppContext.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.AppContext.Session(), team) w.Write([]byte(team.ToJson())) } @@ -141,12 +141,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.AppContext.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.AppContext.Session(), team) w.Write([]byte(team.ToJson())) } @@ -174,7 +174,7 @@ func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -188,7 +188,7 @@ func updateTeam(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.Success() auditRec.AddMeta("update", updatedTeam) - c.App.SanitizeTeam(*c.App.Session(), updatedTeam) + c.App.SanitizeTeam(*c.AppContext.Session(), updatedTeam) w.Write([]byte(updatedTeam.ToJson())) } @@ -208,7 +208,7 @@ func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchTeam", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -224,7 +224,7 @@ func patchTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeam(*c.App.Session(), patchedTeam) + c.App.SanitizeTeam(*c.AppContext.Session(), patchedTeam) auditRec.Success() auditRec.AddMeta("patched", patchedTeam) @@ -243,7 +243,7 @@ func restoreTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -295,7 +295,7 @@ func updateTeamPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("privacy", privacy) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { auditRec.AddMeta("team_id", c.Params.TeamId) c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return @@ -325,7 +325,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -339,7 +339,7 @@ func regenerateTeamInviteId(c *Context, w http.ResponseWriter, r *http.Request) return } - c.App.SanitizeTeam(*c.App.Session(), patchedTeam) + c.App.SanitizeTeam(*c.AppContext.Session(), patchedTeam) auditRec.Success() auditRec.AddMeta("team", patchedTeam) @@ -354,7 +354,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -392,7 +392,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_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { + if c.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) return } @@ -403,7 +403,7 @@ func getTeamsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(*c.App.Session(), teams) + c.App.SanitizeTeams(*c.AppContext.Session(), teams) w.Write([]byte(model.TeamListToJson(teams))) } @@ -413,7 +413,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.AppContext.Session().UserId != c.Params.UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -436,12 +436,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.AppContext.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.AppContext.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -471,12 +471,12 @@ func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { excludeDeletedUsers := r.URL.Query().Get("exclude_deleted_users") excludeDeletedUsersBool, _ := strconv.ParseBool(excludeDeletedUsers) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -503,12 +503,12 @@ func getTeamMembersForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_READ_OTHER_USERS_TEAMS) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_READ_OTHER_USERS_TEAMS) { c.SetPermissionError(model.PERMISSION_READ_OTHER_USERS_TEAMS) return } - canSee, err := c.App.UserCanSeeOtherUser(c.App.Session().UserId, c.Params.UserId) + canSee, err := c.App.UserCanSeeOtherUser(c.AppContext.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -541,12 +541,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.AppContext.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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -587,7 +587,7 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("member", member) - if member.UserId == c.App.Session().UserId { + if member.UserId == c.AppContext.Session().UserId { var team *model.Team team, err = c.App.GetTeam(member.TeamId) if err != nil { @@ -595,16 +595,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.AppContext.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.AppContext.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.AppContext.Session(), member.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_ADD_USER_TO_TEAM) return } @@ -633,7 +633,7 @@ func addTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - member, err = c.App.AddTeamMember(member.TeamId, member.UserId) + member, err = c.App.AddTeamMember(c.AppContext, member.TeamId, member.UserId) if err != nil { c.Err = err @@ -658,14 +658,14 @@ func addUserToTeamFromInvite(c *Context, w http.ResponseWriter, r *http.Request) auditRec.AddMeta("invite_id", inviteId) if tokenId != "" { - member, err = c.App.AddTeamMemberByToken(c.App.Session().UserId, tokenId) + member, err = c.App.AddTeamMemberByToken(c.AppContext, c.AppContext.Session().UserId, tokenId) } else if inviteId != "" { - if c.App.Session().Props[model.SESSION_PROP_IS_GUEST] == "true" { + if c.AppContext.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(c.AppContext, inviteId, c.AppContext.Session().UserId) } else { err = model.NewAppError("addTeamMember", "api.team.add_user_to_team.missing_parameter.app_error", nil, "", http.StatusBadRequest) } @@ -753,12 +753,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.AppContext.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.AppContext, c.Params.TeamId, userIds, c.AppContext.Session().UserId, graceful) if membersWithErrors != nil { errList := make([]string, 0, len(membersWithErrors)) @@ -796,8 +796,8 @@ func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("removeTeamMember", audit.Fail) defer c.LogAuditRec(auditRec) - 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.AppContext.Session().UserId != c.Params.UserId { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_REMOVE_USER_FROM_TEAM) { c.SetPermissionError(model.PERMISSION_REMOVE_USER_FROM_TEAM) return } @@ -817,12 +817,12 @@ func removeTeamMember(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("user", user) - if team.IsGroupConstrained() && (c.Params.UserId != c.App.Session().UserId) && !user.IsBot { + if team.IsGroupConstrained() && (c.Params.UserId != c.AppContext.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.AppContext, c.Params.TeamId, c.Params.UserId, c.AppContext.Session().UserId); err != nil { c.Err = err return } @@ -837,12 +837,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.AppContext.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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -862,12 +862,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.AppContext.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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -900,7 +900,7 @@ func updateTeamMemberRoles(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } @@ -933,7 +933,7 @@ func updateTeamMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.Requ defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", schemeRoles) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM_ROLES) return } @@ -957,18 +957,18 @@ func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { opts := &model.TeamSearch{} if c.Params.ExcludePolicyConstrained { - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } opts.ExcludePolicyConstrained = model.NewBool(true) } - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { opts.IncludePolicyID = model.NewBool(true) } - listPrivate := c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) - listPublic := c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) + listPrivate := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) + listPublic := c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) limit := c.Params.PerPage offset := limit * c.Params.Page if listPrivate && listPublic { @@ -992,7 +992,7 @@ func getAllTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(*c.App.Session(), teams) + c.App.SanitizeTeams(*c.AppContext.Session(), teams) var resBody []byte @@ -1012,13 +1012,13 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } // Only system managers may use the ExcludePolicyConstrained field - if props.ExcludePolicyConstrained != nil && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if props.ExcludePolicyConstrained != nil && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) return } // policy ID may only be used through the /data_retention/policies endpoint props.PolicyID = nil - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY) { props.IncludePolicyID = model.NewBool(true) } @@ -1026,15 +1026,15 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { var totalCount int64 var err *model.AppError - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS) && c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.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) - } else if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS) { + } else if c.App.SessionHasPermissionTo(*c.AppContext.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 @@ -1049,7 +1049,7 @@ func searchTeams(c *Context, w http.ResponseWriter, r *http.Request) { return } - c.App.SanitizeTeams(*c.App.Session(), teams) + c.App.SanitizeTeams(*c.AppContext.Session(), teams) var payload []byte if props.Page != nil && props.PerPage != nil { @@ -1078,7 +1078,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.AppContext.Session().UserId) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err return @@ -1086,8 +1086,8 @@ func teamExists(c *Context, w http.ResponseWriter, r *http.Request) { // Verify that the user can see the team (be a member or have the permission to list the team) if (teamMember != nil && teamMember.DeleteAt == 0) || - (team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.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.AppContext.Session(), model.PERMISSION_LIST_PUBLIC_TEAMS)) || + (!team.AllowOpenInvite && c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_LIST_PRIVATE_TEAMS)) { exists = true } } @@ -1107,7 +1107,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_IMPORT_TEAM) { c.SetPermissionError(model.PERMISSION_IMPORT_TEAM) return } @@ -1168,7 +1168,7 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) { switch importFrom { case "slack": var err *model.AppError - if err, log = c.App.SlackImport(fileData, fileSize, c.Params.TeamId); err != nil { + if err, log = c.App.SlackImport(c.AppContext, fileData, fileSize, c.Params.TeamId); err != nil { c.Err = err c.Err.StatusCode = http.StatusBadRequest } @@ -1193,12 +1193,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.AppContext.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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) { c.SetPermissionError(model.PERMISSION_INVITE_USER) return } @@ -1224,7 +1224,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { cloudUserLimit := *c.App.Config().ExperimentalSettings.CloudUserLimit var invitesOverLimit []*model.EmailInviteWithError if c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && cloudUserLimit > 0 { - subscription, subErr := c.App.Cloud().GetSubscription(c.App.Session().UserId) + subscription, subErr := c.App.Cloud().GetSubscription(c.AppContext.Session().UserId) if subErr != nil { c.Err = model.NewAppError( "Api4.inviteUsersToTeam", @@ -1245,7 +1245,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { jobData := map[string]string{ "emailList": model.ArrayToJson(emailList), "teamID": c.Params.TeamId, - "senderID": c.App.Session().UserId, + "senderID": c.AppContext.Session().UserId, "scheduledAt": strconv.FormatInt(scheduledAt, 10), } @@ -1259,7 +1259,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { var invitesWithError []*model.EmailInviteWithError var err *model.AppError if emailList != nil { - invitesWithError, err = c.App.InviteNewUsersToTeamGracefully(emailList, c.Params.TeamId, c.App.Session().UserId) + invitesWithError, err = c.App.InviteNewUsersToTeamGracefully(emailList, c.Params.TeamId, c.AppContext.Session().UserId) } if len(invitesOverLimit) > 0 { @@ -1282,7 +1282,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { // in graceful mode we return both the successful 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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -1313,7 +1313,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_INVITE_GUEST) { c.SetPermissionError(model.PERMISSION_INVITE_GUEST) return } @@ -1340,7 +1340,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) cloudUserLimit := *c.App.Config().ExperimentalSettings.CloudUserLimit var invitesOverLimit []*model.EmailInviteWithError if c.App.Srv().License() != nil && *c.App.Srv().License().Features.Cloud && cloudUserLimit > 0 && c.IsSystemAdmin() { - subscription, err := c.App.Cloud().GetSubscription(c.App.Session().UserId) + subscription, err := c.App.Cloud().GetSubscription(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError( "Api4.inviteGuestsToChannel", @@ -1359,7 +1359,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) var err *model.AppError if guestsInvite.Emails != nil { - invitesWithError, err = c.App.InviteGuestsToChannelsGracefully(c.Params.TeamId, guestsInvite, c.App.Session().UserId) + invitesWithError, err = c.App.InviteGuestsToChannelsGracefully(c.Params.TeamId, guestsInvite, c.AppContext.Session().UserId) } if len(invitesOverLimit) > 0 { @@ -1378,7 +1378,7 @@ func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) // in graceful mode we return both the successful 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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -1414,7 +1414,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_INVALIDATE_EMAIL_INVITE) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_INVALIDATE_EMAIL_INVITE) { c.SetPermissionError(model.PERMISSION_INVALIDATE_EMAIL_INVITE) return } @@ -1444,7 +1444,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.AppContext.Session(), c.Params.TeamId, model.PERMISSION_VIEW_TEAM) && (team.Type != model.TEAM_OPEN || !team.AllowOpenInvite) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return @@ -1480,7 +1480,7 @@ func setTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -1531,7 +1531,7 @@ func removeTeamIcon(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PERMISSION_MANAGE_TEAM) { c.SetPermissionError(model.PERMISSION_MANAGE_TEAM) return } @@ -1567,7 +1567,7 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_PERMISSIONS) return } @@ -1627,7 +1627,7 @@ func teamMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http.Req groupIDs = append(groupIDs, gid) } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } diff --git a/api4/team_local.go b/api4/team_local.go index 719a57bc155..fe5d7039b0f 100644 --- a/api4/team_local.go +++ b/api4/team_local.go @@ -193,7 +193,7 @@ func localCreateTeam(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("team", team) - rteam, err := c.App.CreateTeam(team) + rteam, err := c.App.CreateTeam(c.AppContext, team) if err != nil { c.Err = err return diff --git a/api4/team_test.go b/api4/team_test.go index 5a637f59451..ea5c39971e0 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -1359,7 +1359,7 @@ func TestSearchAllTeamsPaged(t *testing.T) { for i := 0; i < 3; i++ { uid := model.NewId() - newTeam, err := th.App.CreateTeam(&model.Team{ + newTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: fmt.Sprintf("%s %d %s", commonRandom, i, uid), Name: fmt.Sprintf("%s-%d-%s", commonRandom, i, uid), Type: model.TEAM_OPEN, @@ -1369,7 +1369,7 @@ func TestSearchAllTeamsPaged(t *testing.T) { teams[i] = newTeam } - foobarTeam, err := th.App.CreateTeam(&model.Team{ + foobarTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "FOOBARDISPLAYNAME", Name: "whatever", Type: model.TEAM_OPEN, @@ -1865,7 +1865,7 @@ func TestAddTeamMember(t *testing.T) { _, resp := th.SystemAdminClient.DemoteUserToGuest(guest.Id) CheckNoError(t, resp) - err := th.App.RemoveUserFromTeam(th.BasicTeam.Id, th.BasicUser2.Id, "") + err := th.App.RemoveUserFromTeam(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, "") if err != nil { require.FailNow(t, err.Error()) } @@ -2242,7 +2242,7 @@ func TestAddTeamMembers(t *testing.T) { }) bot := th.CreateBotWithSystemAdminClient() - err := th.App.RemoveUserFromTeam(th.BasicTeam.Id, th.BasicUser2.Id, "") + err := th.App.RemoveUserFromTeam(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, "") require.Nil(t, err) // Regular user can't add a member to a team they don't belong to. @@ -3339,9 +3339,9 @@ func TestTeamMembersMinusGroupMembers(t *testing.T) { team, err := th.App.UpdateTeam(team) require.Nil(t, err) - _, err = th.App.AddTeamMember(team.Id, user1.Id) + _, err = th.App.AddTeamMember(th.Context, team.Id, user1.Id) require.Nil(t, err) - _, err = th.App.AddTeamMember(team.Id, user2.Id) + _, err = th.App.AddTeamMember(th.Context, team.Id, user2.Id) require.Nil(t, err) group1 := th.CreateGroup() diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 46b8c5506f9..8367a864327 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -27,7 +27,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -42,7 +42,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.AppContext.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/upload.go b/api4/upload.go index 285bdccf78a..7e3b8c16ad0 100644 --- a/api4/upload.go +++ b/api4/upload.go @@ -47,7 +47,7 @@ func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { return } } else { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return } @@ -55,8 +55,8 @@ func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { } us.Id = model.NewId() - if c.App.Session().UserId != "" { - us.UserId = c.App.Session().UserId + if c.AppContext.Session().UserId != "" { + us.UserId = c.AppContext.Session().UserId } us, err := c.App.CreateUploadSession(us) if err != nil { @@ -81,7 +81,7 @@ func getUpload(c *Context, w http.ResponseWriter, r *http.Request) { return } - if us.UserId != c.App.Session().UserId && !c.IsSystemAdmin() { + if us.UserId != c.AppContext.Session().UserId && !c.IsSystemAdmin() { c.Err = model.NewAppError("getUpload", "api.upload.get_upload.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -117,7 +117,7 @@ func uploadData(c *Context, w http.ResponseWriter, r *http.Request) { return } } else { - if us.UserId != c.App.Session().UserId || !c.App.SessionHasPermissionToChannel(*c.App.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { + if us.UserId != c.AppContext.Session().UserId || !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PERMISSION_UPLOAD_FILE) { c.SetPermissionError(model.PERMISSION_UPLOAD_FILE) return } @@ -163,5 +163,5 @@ func doUploadData(c *Context, us *model.UploadSession, r *http.Request) (*model. rd = r.Body } - return c.App.UploadData(us, rd) + return c.App.UploadData(c.AppContext, us, rd) } diff --git a/api4/user.go b/api4/user.go index 0d1d6037229..bd97a5b7dc0 100644 --- a/api4/user.go +++ b/api4/user.go @@ -148,14 +148,14 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { return } } - ruser, err = c.App.CreateUserWithToken(user, token) + ruser, err = c.App.CreateUserWithToken(c.AppContext, user, token) } else if inviteId != "" { - ruser, err = c.App.CreateUserWithInviteId(user, inviteId, redirect) + ruser, err = c.App.CreateUserWithInviteId(c.AppContext, user, inviteId, redirect) } else if c.IsSystemAdmin() { - ruser, err = c.App.CreateUserAsAdmin(user, redirect) + ruser, err = c.App.CreateUserAsAdmin(c.AppContext, user, redirect) auditRec.AddMeta("admin", true) } else { - ruser, err = c.App.CreateUserFromSignup(user, redirect) + ruser, err = c.App.CreateUserFromSignup(c.AppContext, user, redirect) } if err != nil { @@ -166,7 +166,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { // New user created, check cloud limits and send emails if needed // Soft fail on error since user is already created if ruser != nil { - err = c.App.CheckAndSendUserLimitWarningEmails() + err = c.App.CheckAndSendUserLimitWarningEmails(c.AppContext) if err != nil { c.LogErrorByCode(err) } @@ -185,7 +185,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.AppContext.Session().UserId, c.Params.UserId) if err != nil { c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS) return @@ -202,7 +202,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.AppContext.Session().UserId == user.Id { userTermsOfService, err := c.App.GetUserTermsOfService(user.Id) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err @@ -221,12 +221,12 @@ func getUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session().UserId == user.Id { + if c.AppContext.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.AppContext.Session()) w.Header().Set(model.HEADER_ETAG_SERVER, etag) w.Write([]byte(user.ToJson())) } @@ -239,7 +239,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.AppContext.Session().UserId) if err2 != nil { c.Err = err2 return @@ -252,7 +252,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.AppContext.Session().UserId, user.Id) if err != nil { c.Err = err return @@ -263,7 +263,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.AppContext.Session().UserId == user.Id { userTermsOfService, err := c.App.GetUserTermsOfService(user.Id) if err != nil && err.StatusCode != http.StatusNotFound { c.Err = err @@ -282,7 +282,7 @@ func getUserByUsername(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session().UserId == user.Id { + if c.AppContext.Session().UserId == user.Id { user.Sanitize(map[string]bool{}) } else { c.App.SanitizeProfile(user, c.IsSystemAdmin()) @@ -299,13 +299,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.AppContext.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.AppContext.Session().UserId) if err2 != nil { c.Err = err2 return @@ -318,7 +318,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.AppContext.Session().UserId, user.Id) if err != nil { c.Err = err return @@ -346,7 +346,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.AppContext.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -380,7 +380,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.AppContext.Session().UserId, c.Params.UserId) if err != nil { c.Err = err return @@ -427,7 +427,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -498,7 +498,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -534,7 +534,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -597,7 +597,7 @@ func getFilteredUsersStats(c *Context, w http.ResponseWriter, r *http.Request) { TeamRoles: teamRoles, } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS) return } @@ -619,7 +619,7 @@ func getUsersByGroupChannelIds(c *Context, w http.ResponseWriter, r *http.Reques return } - usersByChannelId, err := c.App.GetUsersByGroupChannelIds(channelIds, c.IsSystemAdmin()) + usersByChannelId, err := c.App.GetUsersByGroupChannelIds(c.AppContext, channelIds, c.IsSystemAdmin()) if err != nil { c.Err = err return @@ -701,7 +701,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { } } - restrictions, err := c.App.GetViewUsersRestrictions(c.App.Session().UserId) + restrictions, err := c.App.GetViewUsersRestrictions(c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -732,21 +732,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.AppContext.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 notInChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), notInChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.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 notInTeamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), notInTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -758,7 +758,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 inTeamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), inTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -775,7 +775,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } } else if inChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), inChannelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } @@ -790,7 +790,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) { c.SetPermissionError(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_GROUPS) return } @@ -801,7 +801,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { return } } else { - userGetOptions, err = c.App.RestrictUsersGetByPermissions(c.App.Session().UserId, userGetOptions) + userGetOptions, err = c.App.RestrictUsersGetByPermissions(c.AppContext.Session().UserId, userGetOptions) if err != nil { c.Err = err return @@ -817,7 +817,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { if etag != "" { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } - c.App.UpdateLastActivityAtIfNeeded(*c.App.Session()) + c.App.UpdateLastActivityAtIfNeeded(*c.AppContext.Session()) w.Write([]byte(model.UserListToJson(profiles))) } @@ -844,7 +844,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -868,7 +868,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.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -884,7 +884,7 @@ func getUsersByNames(c *Context, w http.ResponseWriter, r *http.Request) { } func getKnownUsers(c *Context, w http.ResponseWriter, r *http.Request) { - userIds, err := c.App.GetKnownUsers(c.App.Session().UserId) + userIds, err := c.App.GetKnownUsers(c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -918,28 +918,28 @@ func searchUsers(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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } } - if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.App.Session(), props.InChannelId, model.PERMISSION_READ_CHANNEL) { + if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.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.AppContext.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.AppContext.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.AppContext.Session(), props.NotInTeamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -960,7 +960,7 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { TeamRoles: props.TeamRoles, } - if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { options.AllowEmails = true options.AllowFullNames = true } else { @@ -968,7 +968,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.AppContext.Session().UserId, options) if err != nil { c.Err = err return @@ -1002,21 +1002,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { options.AllowFullNames = true } else { options.AllowFullNames = *c.App.Config().PrivacySettings.ShowFullName } if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_READ_CHANNEL) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PERMISSION_READ_CHANNEL) { c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } } if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_VIEW_TEAM) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), teamId, model.PERMISSION_VIEW_TEAM) { c.SetPermissionError(model.PERMISSION_VIEW_TEAM) return } @@ -1025,7 +1025,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.AppContext.Session().UserId, options) if err != nil { c.Err = err return @@ -1094,12 +1094,12 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) // Cannot update a system admin unless user making request is a systemadmin also. - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), user.Id) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), user.Id) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1111,7 +1111,7 @@ func updateUser(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("user", ouser) - if c.App.Session().IsOAuth { + if c.AppContext.Session().IsOAuth { if ouser.Email != user.Email { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted email update by oauth app" @@ -1129,7 +1129,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.AppContext.Session().UserId == c.Params.UserId { err = c.App.DoubleCheckPassword(ouser, user.Password) if err != nil { c.SetInvalidParam("password") @@ -1165,7 +1165,7 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchUser", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1178,12 +1178,12 @@ func patchUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", ouser) // Cannot update a system admin unless user making request is a systemadmin also - if ouser.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if ouser.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } - if c.App.Session().IsOAuth && patch.Email != nil { + if c.AppContext.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" @@ -1200,7 +1200,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.AppContext.Session().UserId == c.Params.UserId { if patch.Password == nil { c.SetInvalidParam("password") return @@ -1238,13 +1238,13 @@ func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deleteUser", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), userId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.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.AppContext.Session().UserId && !*c.App.Config().TeamSettings.EnableUserDeactivation && !c.App.SessionHasPermissionTo(*c.AppContext.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 } @@ -1257,19 +1257,19 @@ func deleteUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) // Cannot update a system admin unless user making request is a systemadmin also - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } if c.Params.Permanent { if *c.App.Config().ServiceSettings.EnableAPIUserDeletion { - err = c.App.PermanentDeleteUser(user) + err = c.App.PermanentDeleteUser(c.AppContext, user) } else { err = model.NewAppError("deleteUser", "api.user.delete_user.not_enabled.app_error", nil, "userId="+c.Params.UserId, http.StatusUnauthorized) } } else { - _, err = c.App.UpdateActive(user, false) + _, err = c.App.UpdateActive(c.AppContext, user, false) } if err != nil { c.Err = err @@ -1310,7 +1310,7 @@ func updateUserRoles(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_ROLES) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_ROLES) { c.SetPermissionError(model.PERMISSION_MANAGE_ROLES) return } @@ -1347,9 +1347,9 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("active", active) // true when you're trying to de-activate yourself - isSelfDeactive := !active && c.Params.UserId == c.App.Session().UserId + isSelfDeactive := !active && c.Params.UserId == c.AppContext.Session().UserId - if !isSelfDeactive && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) { + if !isSelfDeactive && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) { c.Err = model.NewAppError("updateUserActive", "api.user.update_active.permissions.app_error", nil, "userId="+c.Params.UserId, http.StatusForbidden) return } @@ -1367,7 +1367,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("user", user) - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -1377,7 +1377,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { return } - if _, err = c.App.UpdateActive(user, active); err != nil { + if _, err = c.App.UpdateActive(c.AppContext, user, active); err != nil { c.Err = err } @@ -1397,7 +1397,7 @@ func updateUserActive(c *Context, w http.ResponseWriter, r *http.Request) { // If activating, run cloud check for limit overages if active { - emailErr := c.App.CheckAndSendUserLimitWarningEmails() + emailErr := c.App.CheckAndSendUserLimitWarningEmails(c.AppContext) if emailErr != nil { c.Err = emailErr return @@ -1492,13 +1492,13 @@ func updateUserMfa(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("updateUserMfa", audit.Fail) defer c.LogAuditRec(auditRec) - if c.App.Session().IsOAuth { + if c.AppContext.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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1543,13 +1543,13 @@ func generateMfaSecret(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session().IsOAuth { + if c.AppContext.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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1584,9 +1584,9 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) if user.IsSystemAdmin() { - canUpdatePassword = c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) + canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) } else { - canUpdatePassword = c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) + canUpdatePassword = c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_USERS) } } @@ -1597,13 +1597,13 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { if props["already_hashed"] == "true" { if canUpdatePassword { err = c.App.UpdateHashedPasswordByUserId(c.Params.UserId, newPassword) - } else if c.Params.UserId == c.App.Session().UserId { + } else if c.Params.UserId == c.AppContext.Session().UserId { err = model.NewAppError("updatePassword", "api.user.update_password.user_and_hashed.app_error", nil, "", http.StatusUnauthorized) } else { err = model.NewAppError("updatePassword", "api.user.update_password.context.app_error", nil, "", http.StatusForbidden) } } else { - if c.Params.UserId == c.App.Session().UserId { + if c.Params.UserId == c.AppContext.Session().UserId { currentPassword := props["current_password"] if currentPassword == "" { c.SetInvalidParam("current_password") @@ -1612,7 +1612,7 @@ func updatePassword(c *Context, w http.ResponseWriter, r *http.Request) { err = c.App.UpdatePasswordAsUser(c.Params.UserId, currentPassword, newPassword) } else if canUpdatePassword { - err = c.App.UpdatePasswordByUserIdSendEmail(c.Params.UserId, newPassword, c.App.T("api.user.reset_password.method")) + err = c.App.UpdatePasswordByUserIdSendEmail(c.Params.UserId, newPassword, c.AppContext.T("api.user.reset_password.method")) } else { err = model.NewAppError("updatePassword", "api.user.update_password.context.app_error", nil, "", http.StatusForbidden) } @@ -1782,7 +1782,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(id, "attempt - login_id="+loginId) - user, err := c.App.AuthenticateUserForLogin(id, loginId, password, mfaToken, "", ldapOnly) + user, err := c.App.AuthenticateUserForLogin(c.AppContext, id, loginId, password, mfaToken, "", ldapOnly) if err != nil { c.LogAuditWithUserId(id, "failure - login_id="+loginId) c.Err = err @@ -1803,7 +1803,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(user.Id, "authenticated") - err = c.App.DoLogin(w, r, user, deviceId, false, false, false) + err = c.App.DoLogin(c.AppContext, w, r, user, deviceId, false, false, false) if err != nil { c.Err = err return @@ -1812,7 +1812,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAuditWithUserId(user.Id, "success") if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML { - c.App.AttachSessionCookies(w, r) + c.App.AttachSessionCookies(c.AppContext, w, r) } userTermsOfService, err := c.App.GetUserTermsOfService(user.Id) @@ -1854,7 +1854,7 @@ func loginCWS(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("login", audit.Fail) defer c.LogAuditRec(auditRec) auditRec.AddMeta("login_id", loginID) - user, err := c.App.AuthenticateUserForLogin("", loginID, "", "", token, false) + user, err := c.App.AuthenticateUserForLogin(c.AppContext, "", loginID, "", "", token, false) if err != nil { c.LogAuditWithUserId("", "failure - login_id="+loginID) c.LogErrorByCode(err) @@ -1863,14 +1863,14 @@ func loginCWS(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("user", user) c.LogAuditWithUserId(user.Id, "authenticated") - err = c.App.DoLogin(w, r, user, "", false, false, false) + err = c.App.DoLogin(c.AppContext, w, r, user, "", false, false, false) if err != nil { c.LogErrorByCode(err) http.Redirect(w, r, *c.App.Config().ServiceSettings.SiteURL, 302) return } c.LogAuditWithUserId(user.Id, "success") - c.App.AttachSessionCookies(w, r) + c.App.AttachSessionCookies(c.AppContext, w, r) http.Redirect(w, r, *c.App.Config().ServiceSettings.SiteURL, 302) } @@ -1884,8 +1884,8 @@ 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.AppContext.Session().Id != "" { + if err := c.App.RevokeSessionById(c.AppContext.Session().Id); err != nil { c.Err = err return } @@ -1901,7 +1901,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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1928,7 +1928,7 @@ func revokeSession(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("revokeSession", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1973,7 +1973,7 @@ func revokeAllSessionsForUser(c *Context, w http.ResponseWriter, r *http.Request defer c.LogAuditRec(auditRec) auditRec.AddMeta("user_id", c.Params.UserId) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -1990,7 +1990,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2023,13 +2023,13 @@ func attachDeviceId(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("device_id", deviceId) // 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.AppContext.Session().UserId, deviceId, c.AppContext.Session().Id); err != nil { c.Err = err return } - c.App.ClearSessionCacheForUser(c.App.Session().UserId) - c.App.SetSessionExpireInDays(c.App.Session(), *c.App.Config().ServiceSettings.SessionLengthMobileInDays) + c.App.ClearSessionCacheForUser(c.AppContext.Session().UserId) + c.App.SetSessionExpireInDays(c.AppContext.Session(), *c.App.Config().ServiceSettings.SessionLengthMobileInDays) maxAge := *c.App.Config().ServiceSettings.SessionLengthMobileInDays * 60 * 60 * 24 @@ -2043,7 +2043,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.AppContext.Session().Token, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -2054,7 +2054,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.AppContext.Session().Id, deviceId, c.AppContext.Session().ExpiresAt); err != nil { c.Err = err return } @@ -2078,7 +2078,7 @@ func getUserAudits(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2177,7 +2177,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.AppContext.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() { @@ -2211,7 +2211,7 @@ func createUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) } - if c.App.Session().IsOAuth { + if c.AppContext.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) c.Err.DetailedError += ", attempted access by oauth app" return @@ -2230,12 +2230,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.AppContext.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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2257,7 +2257,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2282,7 +2282,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.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2302,12 +2302,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.AppContext.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.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2327,7 +2327,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.AppContext.Session(), model.PERMISSION_READ_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_READ_USER_ACCESS_TOKEN) return } @@ -2338,7 +2338,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.AppContext.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2359,7 +2359,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("token_id", tokenId) c.LogAudit("") - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) return } @@ -2374,7 +2374,7 @@ func revokeUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) } - if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2404,7 +2404,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.AppContext.Session(), model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_REVOKE_USER_ACCESS_TOKEN) return } @@ -2419,7 +2419,7 @@ func disableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) auditRec.AddMeta("user", user) } - if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2449,7 +2449,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.AppContext.Session(), model.PERMISSION_CREATE_USER_ACCESS_TOKEN) { c.SetPermissionError(model.PERMISSION_CREATE_USER_ACCESS_TOKEN) return } @@ -2464,7 +2464,7 @@ func enableUserAccessToken(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) } - if !c.App.SessionHasPermissionToUserOrBot(*c.App.Session(), accessToken.UserId) { + if !c.App.SessionHasPermissionToUserOrBot(*c.AppContext.Session(), accessToken.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2483,7 +2483,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.AppContext.Session().UserId termsOfServiceId, ok := props["termsOfServiceId"].(string) if !ok { c.SetInvalidParam("termsOfServiceId") @@ -2521,7 +2521,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.AppContext.Session().UserId result, err := c.App.GetUserTermsOfService(userId) if err != nil { c.Err = err @@ -2539,7 +2539,7 @@ func promoteGuestToUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("promoteGuestToUser", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_PROMOTE_GUEST) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_PROMOTE_GUEST) { c.SetPermissionError(model.PERMISSION_PROMOTE_GUEST) return } @@ -2556,7 +2556,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(c.AppContext, user, c.AppContext.Session().UserId); err != nil { c.Err = err return } @@ -2584,7 +2584,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("demoteUserToGuest", audit.Fail) defer c.LogAuditRec(auditRec) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_DEMOTE_TO_GUEST) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_DEMOTE_TO_GUEST) { c.SetPermissionError(model.PERMISSION_DEMOTE_TO_GUEST) return } @@ -2595,7 +2595,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { return } - if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2628,7 +2628,7 @@ func publishUserTyping(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.Params.UserId != c.App.Session().UserId && !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if c.Params.UserId != c.AppContext.Session().UserId && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2662,7 +2662,7 @@ func verifyUserEmailWithoutToken(c *Context, w http.ResponseWriter, r *http.Requ defer c.LogAuditRec(auditRec) auditRec.AddMeta("user_id", user.Id) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2694,7 +2694,7 @@ func convertUserToBot(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("user", user) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2717,7 +2717,7 @@ func getUploadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.Params.UserId != c.App.Session().UserId { + if c.Params.UserId != c.AppContext.Session().UserId { c.Err = model.NewAppError("getUploadsForUser", "api.user.get_uploads_for_user.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -2761,7 +2761,7 @@ func migrateAuthToLDAP(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("match_field", matchField) auditRec.AddMeta("force", force) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2820,7 +2820,7 @@ func migrateAuthToSaml(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("matches", matches) auditRec.AddMeta("auto", auto) - if !c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { + if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PERMISSION_MANAGE_SYSTEM) { c.SetPermissionError(model.PERMISSION_MANAGE_SYSTEM) return } @@ -2854,7 +2854,7 @@ func getThreadForUser(c *Context, w http.ResponseWriter, r *http.Request) { if c.Err != nil { return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2876,7 +2876,7 @@ func getThreadsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2947,7 +2947,7 @@ func updateReadStateThreadByUser(c *Context, w http.ResponseWriter, r *http.Requ auditRec.AddMeta("thread_id", c.Params.ThreadId) auditRec.AddMeta("team_id", c.Params.TeamId) auditRec.AddMeta("timestamp", c.Params.Timestamp) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -2975,7 +2975,7 @@ func unfollowThreadByUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("thread_id", c.Params.ThreadId) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -3003,7 +3003,7 @@ func followThreadByUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("thread_id", c.Params.ThreadId) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } @@ -3029,7 +3029,7 @@ func updateReadStateAllThreadsByUser(c *Context, w http.ResponseWriter, r *http. auditRec.AddMeta("user_id", c.Params.UserId) auditRec.AddMeta("team_id", c.Params.TeamId) - if !c.App.SessionHasPermissionToUser(*c.App.Session(), c.Params.UserId) { + if !c.App.SessionHasPermissionToUser(*c.AppContext.Session(), c.Params.UserId) { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) return } diff --git a/api4/user_local.go b/api4/user_local.go index ca8051c8bd8..71cc9a25e56 100644 --- a/api4/user_local.go +++ b/api4/user_local.go @@ -231,9 +231,9 @@ func localDeleteUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) if c.Params.Permanent { - err = c.App.PermanentDeleteUser(user) + err = c.App.PermanentDeleteUser(c.AppContext, user) } else { - _, err = c.App.UpdateActive(user, false) + _, err = c.App.UpdateActive(c.AppContext, user, false) } if err != nil { c.Err = err @@ -248,7 +248,7 @@ func localPermanentDeleteAllUsers(c *Context, w http.ResponseWriter, r *http.Req auditRec := c.MakeAuditRecord("localPermanentDeleteAllUsers", audit.Fail) defer c.LogAuditRec(auditRec) - if err := c.App.PermanentDeleteAllUsers(); err != nil { + if err := c.App.PermanentDeleteAllUsers(c.AppContext); err != nil { c.Err = err return } @@ -299,7 +299,7 @@ func localGetUserByEmail(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.AppContext.Session().UserId, http.StatusForbidden) return } diff --git a/api4/user_test.go b/api4/user_test.go index 4c4d5a80bde..b1dc5116197 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -22,6 +22,8 @@ import ( "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mail" "github.com/mattermost/mattermost-server/v5/utils/testutils" + + _ "github.com/mattermost/mattermost-server/v5/model/gitlab" ) func TestCreateUser(t *testing.T) { @@ -375,10 +377,10 @@ func TestCreateUserWebSocketEvent(t *testing.T) { EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, guest.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(guest, th.BasicChannel, false) @@ -996,7 +998,7 @@ func TestSearchUsers(t *testing.T) { require.True(t, findUserInList(th.BasicUser.Id, users), "should have found user") - _, err := th.App.UpdateActive(th.BasicUser2, false) + _, err := th.App.UpdateActive(th.Context, th.BasicUser2, false) require.Nil(t, err) search.Term = th.BasicUser2.Username @@ -1095,7 +1097,7 @@ func TestSearchUsers(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false }) - _, err = th.App.UpdateActive(th.BasicUser2, true) + _, err = th.App.UpdateActive(th.Context, th.BasicUser2, true) require.Nil(t, err) search.InChannelId = "" @@ -1294,7 +1296,7 @@ func TestAutocompleteUsersInChannel(t *testing.T) { CheckNoError(t, resp) assert.Empty(t, rusers.OutOfChannel) - th.App.GetOrCreateDirectChannel(permissionsUser.Id, otherUser.Id) + th.App.GetOrCreateDirectChannel(th.Context, permissionsUser.Id, otherUser.Id) rusers, resp = th.Client.AutocompleteUsersInChannel(teamId, channelId, "", model.USER_SEARCH_DEFAULT_LIMIT, "") CheckNoError(t, resp) @@ -1525,14 +1527,14 @@ func TestGetUsersByIdsWithOptions(t *testing.T) { defer th.TearDown() // Users before the timestamp shouldn't be returned - user1, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) require.Nil(t, err) - user2, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) + user2, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) require.Nil(t, err) // Users not in the list of IDs shouldn't be returned - _, err = th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) + _, err = th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Username: model.NewId(), Password: model.NewId()}) require.Nil(t, err) users, resp := th.Client.GetUsersByIdsWithOptions([]string{user1.Id, user2.Id}, &model.UserGetByIdsOptions{ @@ -2004,7 +2006,7 @@ func TestPermanentDeleteAllUsers(t *testing.T) { t.Run("The endpoint should permanently delete all users", func(t *testing.T) { // Basic user creates a team and a channel - team, err := th.App.CreateTeamWithUser(&model.Team{ + team, err := th.App.CreateTeamWithUser(th.Context, &model.Team{ DisplayName: "User Created Team", Name: "user-created-team", Email: "usercreatedteam@test.com", @@ -2012,7 +2014,7 @@ func TestPermanentDeleteAllUsers(t *testing.T) { }, th.BasicUser.Id) require.Nil(t, err) - channel, err := th.App.CreateChannelWithUser(&model.Channel{ + channel, err := th.App.CreateChannelWithUser(th.Context, &model.Channel{ DisplayName: "User Created Channel", Name: "user-created-channel", Type: model.CHANNEL_OPEN, @@ -2221,9 +2223,9 @@ func TestUpdateUserActive(t *testing.T) { Password: "Password1", EmailVerified: true, } - user, err := th.App.CreateGuest(guest) + user, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) - th.App.UpdateActive(user, false) + th.App.UpdateActive(th.Context, user, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = false }) defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) @@ -2246,9 +2248,9 @@ func TestUpdateUserActive(t *testing.T) { Password: "Password1", EmailVerified: true, } - user, err := th.App.CreateGuest(guest) + user, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) - th.App.UpdateActive(user, false) + th.App.UpdateActive(th.Context, user, false) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { @@ -2592,7 +2594,7 @@ func TestGetUsersInGroup(t *testing.T) { CheckForbiddenStatus(t, response) }) - user1, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) assert.Nil(t, err) _, err = th.App.UpsertGroupMember(group.Id, user1.Id) assert.Nil(t, err) @@ -4613,7 +4615,7 @@ func TestUserAccessTokenInactiveUser(t *testing.T) { _, resp = th.Client.GetMe("") CheckNoError(t, resp) - th.App.UpdateActive(th.BasicUser, false) + th.App.UpdateActive(th.Context, th.BasicUser, false) _, resp = th.Client.GetMe("") CheckUnauthorizedStatus(t, resp) @@ -4674,7 +4676,7 @@ func TestGetUsersByStatus(t *testing.T) { th := Setup(t) defer th.TearDown() - team, err := th.App.CreateTeam(&model.Team{ + team, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), @@ -4683,7 +4685,7 @@ func TestGetUsersByStatus(t *testing.T) { require.Nil(t, err, "failed to create team") - channel, err := th.App.CreateChannel(&model.Channel{ + channel, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, @@ -4695,7 +4697,7 @@ func TestGetUsersByStatus(t *testing.T) { createUserWithStatus := func(username string, status string) *model.User { id := model.NewId() - user, err := th.App.CreateUser(&model.User{ + user, err := th.App.CreateUser(th.Context, &model.User{ Email: "success+" + id + "@simulator.amazonses.com", Username: "un_" + username + "_" + id, Nickname: "nn_" + id, @@ -4943,7 +4945,7 @@ func TestDemoteUserToGuest(t *testing.T) { _, respErr = c.DemoteUserToGuest(user.Id) CheckNoError(t, respErr) - defer require.Nil(t, th.App.PromoteGuestToUser(user, "")) + defer require.Nil(t, th.App.PromoteGuestToUser(th.Context, user, "")) }, "demote a user to guest") t.Run("websocket update user event", func(t *testing.T) { @@ -5085,7 +5087,7 @@ func TestGetKnownUsers(t *testing.T) { th := Setup(t) defer th.TearDown() - t1, err := th.App.CreateTeam(&model.Team{ + t1, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), @@ -5093,7 +5095,7 @@ func TestGetKnownUsers(t *testing.T) { }) require.Nil(t, err, "failed to create team") - t2, err := th.App.CreateTeam(&model.Team{ + t2, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), @@ -5101,7 +5103,7 @@ func TestGetKnownUsers(t *testing.T) { }) require.Nil(t, err, "failed to create team") - t3, err := th.App.CreateTeam(&model.Team{ + t3, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), @@ -5109,7 +5111,7 @@ func TestGetKnownUsers(t *testing.T) { }) require.Nil(t, err, "failed to create team") - c1, err := th.App.CreateChannel(&model.Channel{ + c1, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, @@ -5118,7 +5120,7 @@ func TestGetKnownUsers(t *testing.T) { }, false) require.Nil(t, err, "failed to create channel") - c2, err := th.App.CreateChannel(&model.Channel{ + c2, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, @@ -5127,7 +5129,7 @@ func TestGetKnownUsers(t *testing.T) { }, false) require.Nil(t, err, "failed to create channel") - c3, err := th.App.CreateChannel(&model.Channel{ + c3, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, @@ -5137,13 +5139,13 @@ func TestGetKnownUsers(t *testing.T) { require.Nil(t, err, "failed to create channel") u1 := th.CreateUser() - defer th.App.PermanentDeleteUser(u1) + defer th.App.PermanentDeleteUser(th.Context, u1) u2 := th.CreateUser() - defer th.App.PermanentDeleteUser(u2) + defer th.App.PermanentDeleteUser(th.Context, u2) u3 := th.CreateUser() - defer th.App.PermanentDeleteUser(u3) + defer th.App.PermanentDeleteUser(th.Context, u3) u4 := th.CreateUser() - defer th.App.PermanentDeleteUser(u4) + defer th.App.PermanentDeleteUser(th.Context, u4) th.LinkUserToTeam(u1, t1) th.LinkUserToTeam(u1, t2) @@ -5537,7 +5539,7 @@ func TestThreadSocketEvents(t *testing.T) { CheckNoError(t, resp) CheckCreatedStatus(t, resp) - _, err = th.App.CreatePostAsUser(&model.Post{ChannelId: th.BasicChannel.Id, Message: "testReply", UserId: th.BasicUser2.Id, RootId: rpost.Id}, th.App.Session().Id, false) + _, err = th.App.CreatePostAsUser(th.Context, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testReply", UserId: th.BasicUser2.Id, RootId: rpost.Id}, th.Context.Session().Id, false) require.Nil(t, err) defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser2.Id) @@ -5978,9 +5980,9 @@ func TestMarkThreadUnreadMentionCount(t *testing.T) { channel := th.BasicChannel user := th.BasicUser user2 := th.BasicUser2 - appErr := th.App.JoinChannel(channel, user.Id) + appErr := th.App.JoinChannel(th.Context, channel, user.Id) require.Nil(t, appErr) - appErr = th.App.JoinChannel(channel, user2.Id) + appErr = th.App.JoinChannel(th.Context, channel, user2.Id) require.Nil(t, appErr) rpost, _ := postAndCheck(t, Client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsg @" + th.BasicUser2.Username}) diff --git a/api4/user_viewmembers_test.go b/api4/user_viewmembers_test.go index d638a73acd2..6c8409e699b 100644 --- a/api4/user_viewmembers_test.go +++ b/api4/user_viewmembers_test.go @@ -16,30 +16,30 @@ func TestApiResctrictedViewMembers(t *testing.T) { defer th.TearDown() // Create first account for system admin - _, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SYSTEM_USER_ROLE_ID}) + _, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - user1, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) + user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - user2, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SYSTEM_USER_ROLE_ID}) + user2, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - user3, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SYSTEM_USER_ROLE_ID}) + user3, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - user4, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SYSTEM_USER_ROLE_ID}) + user4, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - user5, err := th.App.CreateUser(&model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SYSTEM_USER_ROLE_ID}) + user5, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SYSTEM_USER_ROLE_ID}) require.Nil(t, err) - team1, err := th.App.CreateTeam(&model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) + team1, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) require.Nil(t, err) - team2, err := th.App.CreateTeam(&model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) + team2, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN}) require.Nil(t, err) - channel1, err := th.App.CreateChannel(&model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) + channel1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) - channel2, err := th.App.CreateChannel(&model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) + channel2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team1.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) - channel3, err := th.App.CreateChannel(&model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team2.Id, CreatorId: model.NewId()}, false) + channel3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, TeamId: team2.Id, CreatorId: model.NewId()}, false) require.Nil(t, err) th.LinkUserToTeam(user1, team1) diff --git a/api4/webhook.go b/api4/webhook.go index 9fb4aa8be4a..ca2b5d766a5 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -43,20 +43,20 @@ func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return } - userId := c.App.Session().UserId + userId := c.AppContext.Session().UserId if hook.UserId != "" && hook.UserId != userId { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - innapropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return @@ -119,7 +119,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.AppContext.Session().UserId, http.StatusBadRequest) return } @@ -136,18 +136,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.AppContext.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.AppContext.Session().UserId != oldHook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session(), channel.Id, model.PERMISSION_READ_CHANNEL) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PERMISSION_READ_CHANNEL) return @@ -168,31 +168,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.AppContext.Session().UserId var hooks []*model.IncomingWebhook var err *model.AppError if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.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.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { userId = "" } @@ -239,14 +239,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.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || + (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { 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.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return @@ -290,14 +290,14 @@ func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel_name", channel.Name) auditRec.AddMeta("team_id", hook.TeamId) - if !c.App.SessionHasPermissionToTeam(*c.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.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_INCOMING_WEBHOOKS) || + (channel.Type != model.CHANNEL_OPEN && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PERMISSION_READ_CHANNEL)) { 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.AppContext.Session().UserId != hook.UserId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS) return @@ -349,22 +349,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.AppContext.Session().UserId, http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), updatedHook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId != oldHook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId rhook, err := c.App.UpdateOutgoingWebhook(oldHook, updatedHook) if err != nil { @@ -390,15 +390,15 @@ func createOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("hook_id", hook.Id) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { c.SetPermissionError(model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) return } if hook.CreatorId == "" { - hook.CreatorId = c.App.Session().UserId + hook.CreatorId = c.AppContext.Session().UserId } else { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - innapropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return @@ -431,43 +431,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.AppContext.Session().UserId var hooks []*model.OutgoingWebhook var err *model.AppError if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.App.Session(), channelId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToChannel(*c.AppContext.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.AppContext.Session(), channelId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { userId = "" } hooks, err = c.App.GetOutgoingWebhooksForChannelPageByUser(channelId, userId, c.Params.Page, c.Params.PerPage) } else if teamId != "" { - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), teamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.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.AppContext.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.AppContext.Session(), model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { userId = "" } @@ -502,12 +502,12 @@ func getOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return @@ -539,12 +539,12 @@ func regenOutgoingHookToken(c *Context, w http.ResponseWriter, r *http.Request) auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) { c.LogAudit("fail - inappropriate permissions") c.SetPermissionError(model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS) return @@ -582,12 +582,12 @@ func deleteOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - if !c.App.SessionHasPermissionToTeam(*c.App.Session(), hook.TeamId, model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.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.AppContext.Session().UserId != hook.CreatorId && !c.App.SessionHasPermissionToTeam(*c.AppContext.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 6697abd4894..d0f3ff52edb 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -40,21 +40,21 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { // If the queues are empty, they are initialized in the constructor. cfg := &app.WebConnConfig{ WebSocket: ws, - Session: *c.App.Session(), - TFunc: c.App.T, + Session: *c.AppContext.Session(), + TFunc: c.AppContext.T, Locale: "", Active: true, } if *c.App.Config().ServiceSettings.EnableReliableWebSockets { cfg.ConnectionID = r.URL.Query().Get(connectionIDParam) - if cfg.ConnectionID == "" || c.App.Session().UserId == "" { + if cfg.ConnectionID == "" || c.AppContext.Session().UserId == "" { // If not present, we assume client is not capable yet, or it's a fresh connection. // We just create a new ID. cfg.ConnectionID = model.NewId() // In case of fresh connection id, sequence number is already zero. } else { - cfg, err = c.App.PopulateWebConnConfig(cfg, r.URL.Query().Get(sequenceNumberParam)) + cfg, err = c.App.PopulateWebConnConfig(c.AppContext.Session(), cfg, r.URL.Query().Get(sequenceNumberParam)) if err != nil { mlog.Warn("Error while populating webconn config", mlog.String("id", r.URL.Query().Get(connectionIDParam)), mlog.Err(err)) ws.Close() @@ -64,7 +64,7 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { } wc := c.App.NewWebConn(cfg) - if c.App.Session().UserId != "" { + if c.AppContext.Session().UserId != "" { c.App.HubRegister(wc) } diff --git a/app/app.go b/app/app.go index 31431b18d63..07364f48206 100644 --- a/app/app.go +++ b/app/app.go @@ -4,13 +4,13 @@ package app import ( - "context" "fmt" "net/http" "strconv" "strings" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/httpservice" @@ -31,16 +31,6 @@ type App struct { // to be registered in (h *MainHelper) setupStore, but that creates // a cyclic dependency as bleve tests themselves import testlib. searchEngine *searchengine.Broker - - t i18n.TranslateFunc - session model.Session - requestId string - ipAddress string - path string - userAgent string - acceptLanguage string - - context context.Context } func New(options ...AppOption) *App { @@ -53,103 +43,6 @@ func New(options ...AppOption) *App { return app } -func (a *App) InitServer() { - a.srv.AppInitializedOnce.Do(func() { - a.initEnterprise() - - a.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { - if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable { - if appErr := a.DeactivateGuests(); appErr != nil { - mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) - } - } - }) - - // Disable active guest accounts on first run if guest accounts are disabled - if !*a.Config().GuestAccountsSettings.Enable { - if appErr := a.DeactivateGuests(); appErr != nil { - mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) - } - } - - // Scheduler must be started before cluster. - a.initJobs() - - if a.srv.joinCluster && a.srv.Cluster != nil { - a.registerAppClusterMessageHandlers() - } - - a.DoAppMigrations() - - a.InitPostMetadata() - - a.InitPlugins(*a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) - a.AddConfigListener(func(prevCfg, cfg *model.Config) { - if *cfg.PluginSettings.Enable { - a.InitPlugins(*cfg.PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) - } else { - a.srv.ShutDownPlugins() - } - }) - if a.Srv().runEssentialJobs { - a.Srv().Go(func() { - runLicenseExpirationCheckJob(a) - runCheckWarnMetricStatusJob(a) - runDNDStatusExpireJob(a) - runCheckAdminSupportStatusJob(a) - }) - a.srv.runJobs() - } - }) -} - -func (a *App) initJobs() { - if jobsLdapSyncInterface != nil { - a.srv.Jobs.LdapSync = jobsLdapSyncInterface(a) - } - if jobsPluginsInterface != nil { - a.srv.Jobs.Plugins = jobsPluginsInterface(a) - } - if jobsExpiryNotifyInterface != nil { - a.srv.Jobs.ExpiryNotify = jobsExpiryNotifyInterface(a) - } - if productNoticesJobInterface != nil { - a.srv.Jobs.ProductNotices = productNoticesJobInterface(a) - } - if jobsImportProcessInterface != nil { - a.srv.Jobs.ImportProcess = jobsImportProcessInterface(a) - } - if jobsImportDeleteInterface != nil { - a.srv.Jobs.ImportDelete = jobsImportDeleteInterface(a) - } - if jobsExportDeleteInterface != nil { - a.srv.Jobs.ExportDelete = jobsExportDeleteInterface(a) - } - - if jobsExportProcessInterface != nil { - a.srv.Jobs.ExportProcess = jobsExportProcessInterface(a) - } - - if jobsExportProcessInterface != nil { - a.srv.Jobs.ExportProcess = jobsExportProcessInterface(a) - } - - if jobsActiveUsersInterface != nil { - a.srv.Jobs.ActiveUsers = jobsActiveUsersInterface(a) - } - - if jobsCloudInterface != nil { - a.srv.Jobs.Cloud = jobsCloudInterface(a.srv) - } - - if jobsResendInvitationEmailInterface != nil { - a.srv.Jobs.ResendInvitationEmails = jobsResendInvitationEmailInterface(a) - } - - a.srv.Jobs.InitWorkers() - a.srv.Jobs.InitSchedulers() -} - func (a *App) TelemetryId() string { return a.Srv().TelemetryId() } @@ -343,7 +236,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 } //nolint:golint,unused,deadcode -func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bool) *model.AppError { +func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId string, isE0Edition bool) *model.AppError { perPage := 25 userOptions := &model.UserGetOptions{ Page: 0, @@ -394,7 +287,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bo bot.DisplayName = T("app.system.warn_metric.bot_displayname") bot.Description = T("app.system.warn_metric.bot_description") - channel, appErr := a.GetOrCreateDirectChannel(bot.UserId, sysAdmin.Id) + channel, appErr := a.GetOrCreateDirectChannel(c, bot.UserId, sysAdmin.Id) if appErr != nil { return appErr } @@ -462,7 +355,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bo model.ParseSlackAttachment(botPost, attachments) mlog.Debug("Post admin advisory for metric", mlog.String("warnMetricId", warnMetricId), mlog.String("userid", botPost.UserId)) - if _, err := a.CreatePostAsUser(botPost, a.Session().Id, true); err != nil { + if _, err := a.CreatePostAsUser(c, botPost, c.Session().Id, true); err != nil { return err } } @@ -565,12 +458,12 @@ func (a *App) setWarnMetricsStatusForId(warnMetricId string, status string) *mod return nil } -func (a *App) RequestLicenseAndAckWarnMetric(warnMetricId string, isBot bool) *model.AppError { +func (a *App) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError { if *a.Config().ExperimentalSettings.RestrictSystemAdmin { return model.NewAppError("RequestLicenseAndAckWarnMetric", "api.restricted_system_admin", nil, "", http.StatusForbidden) } - currentUser, appErr := a.GetUser(a.Session().UserId) + currentUser, appErr := a.GetUser(c.Session().UserId) if appErr != nil { return appErr } @@ -620,27 +513,7 @@ func (a *App) Log() *mlog.Logger { func (a *App) NotificationsLog() *mlog.Logger { return a.srv.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.srv.AccountMigration } @@ -683,41 +556,6 @@ func (a *App) ImageProxy() *imageproxy.ImageProxy { func (a *App) Timezones() *timezones.Timezones { return a.srv.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 i18n.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() i18n.TranslateFunc { - return a.t -} func (a *App) DBHealthCheckWrite() error { currentTime := strconv.FormatInt(time.Now().Unix(), 10) @@ -737,6 +575,10 @@ func (a *App) dbHealthCheckKey() string { return fmt.Sprintf("health_check_%s", a.GetClusterId()) } +func (a *App) SetServer(srv *Server) { + a.srv = srv +} + func (a *App) UpdateExpiredDNDStatuses() ([]*model.Status, error) { return a.Srv().Store.Status().UpdateExpiredDNDStatuses() } diff --git a/app/app_iface.go b/app/app_iface.go index b559374e14c..d2a5e554432 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -18,6 +18,7 @@ import ( "time" "github.com/dyatlov/go-opengraph/opengraph" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" @@ -36,14 +37,14 @@ import ( // 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 { // @openTracingParams args - ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) + ExecuteCommand(c *request.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) // @openTracingParams teamID // previous ListCommands now ListAutocompleteCommands ListAutocompleteCommands(teamID string, T i18n.TranslateFunc) ([]*model.Command, *model.AppError) // @openTracingParams teamID, skipSlackParsing - CreateCommandPost(post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) + CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) // AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel. - AddChannelMember(userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) + AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) // AddCursorIdsForPostList adds NextPostId and PrevPostId as cursor to the PostList. // The conditional blocks ensure that it sets those cursor IDs immediately as afterPost, beforePost or empty, // and only query to database whenever necessary. @@ -78,23 +79,23 @@ type AppIface interface { // ConvertUserToBot converts a user to bot. ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError) // CreateBot creates the given bot and corresponding user. - CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) + CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError) // CreateChannelScheme creates a new Scheme of scope channel and assigns it to the channel. CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model.AppError) // CreateDefaultChannels creates channels in the given team for each channel returned by (*App).DefaultChannelNames. // - CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError) + CreateDefaultChannels(c *request.Context, teamID string) ([]*model.Channel, *model.AppError) // CreateDefaultMemberships adds users to teams and channels based on their group memberships and how those groups // are configured to sync with teams and channels for group members on or after the given timestamp. // If includeRemovedMembers is true, then members who left or were removed from a team/channel will // be re-added; otherwise, they will not be re-added. - CreateDefaultMemberships(since int64, includeRemovedMembers bool) error + CreateDefaultMemberships(c *request.Context, since int64, includeRemovedMembers bool) error // CreateGuest creates a guest and sets several fields of the returned User struct to // their zero values. - CreateGuest(user *model.User) (*model.User, *model.AppError) + CreateGuest(c *request.Context, user *model.User) (*model.User, *model.AppError) // CreateUser creates a user and sets several fields of the returned User struct to // their zero values. - CreateUser(user *model.User) (*model.User, *model.AppError) + CreateUser(c *request.Context, user *model.User) (*model.User, *model.AppError) // Creates and stores FileInfos for a post created before the FileInfos table existed. MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo // DefaultChannelNames returns the list of system-wide default channel names. @@ -112,7 +113,7 @@ type AppIface interface { DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) // DeleteGroupConstrainedMemberships deletes team and channel memberships of users who aren't members of the allowed // groups of all group-constrained teams and channels. - DeleteGroupConstrainedMemberships() error + DeleteGroupConstrainedMemberships(c *request.Context) error // DeletePublicKey will delete plugin public key from the config. DeletePublicKey(name string) *model.AppError // DemoteUserToGuest Convert user's roles and all his mermbership's roles from @@ -196,7 +197,7 @@ type AppIface interface { // lock instead. GetPluginsEnvironment() *plugin.Environment // GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller - GetProductNotices(userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) + GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) // GetPublicKey will return the actual public key saved in the `name` file. GetPublicKey(name string) ([]byte, *model.AppError) // GetSanitizedConfig gets the configuration for a system admin without any secrets. @@ -207,7 +208,7 @@ type AppIface interface { // based on the type of session (Mobile, SSO, Web/LDAP). GetSessionLengthInMillis(session *model.Session) int64 // GetSuggestions returns suggestions for user input. - GetSuggestions(commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion + GetSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion // GetTeamGroupUsers returns the users who are associated to the team via GroupTeams and GroupMembers. GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) // GetTeamSchemeChannelRoles Checks if a team has an override scheme and returns the scheme channel role names or default channel role names. @@ -249,7 +250,7 @@ type AppIface interface { MentionsToTeamMembers(message, teamID string) model.UserMentionMap // MoveChannel method is prone to data races if someone joins to channel during the move process. However this // function is only exposed to sysadmins and the possibility of this edge case is relatively small. - MoveChannel(team *model.Team, channel *model.Channel, user *model.User) *model.AppError + MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError // NewWebConn returns a new WebConn instance. NewWebConn(cfg *WebConnConfig) *WebConn // NewWebHub creates a new Hub. @@ -266,15 +267,15 @@ type AppIface interface { // Perform an HTTP POST request to an integration's action endpoint. // Caller must consume and close returned http.Response as necessary. // For internal requests, requests are routed directly to a plugin ServerHTTP hook - DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) + DoActionRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) // PermanentDeleteBot permanently deletes a bot and its corresponding user. PermanentDeleteBot(botUserId string) *model.AppError // PopulateWebConnConfig checks if the connection id already exists in the hub, // and if so, accordingly populates the other fields of the webconn. - PopulateWebConnConfig(cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) + PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) // PromoteGuestToUser Convert user's roles and all his mermbership's roles from // guest roles to regular user roles. - PromoteGuestToUser(user *model.User, requestorId string) *model.AppError + PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError // RenameChannel is used to rename the channel Name and the DisplayName fields RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) // RenameTeam is used to rename the team Name and the DisplayName fields @@ -326,7 +327,7 @@ type AppIface interface { SyncPlugins() *model.AppError // SyncRolesAndMembership updates the SchemeAdmin status and membership of all of the members of the given // syncable. - SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) + SyncRolesAndMembership(c *request.Context, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) // SyncSyncableRoles updates the SchemeAdmin field value of the given syncable's members based on the configuration of // 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. @@ -352,7 +353,7 @@ type AppIface interface { // This to be used for places we check the users password when they are already logged in DoubleCheckPassword(user *model.User, password string) *model.AppError // UpdateBotActive marks a bot as active or inactive, along with its corresponding user. - UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) + UpdateBotActive(c *request.Context, botUserId string, active bool) (*model.Bot, *model.AppError) // UpdateBotOwner changes a bot's owner to the given value. UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) // UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event. @@ -372,17 +373,17 @@ type AppIface interface { // UpdateWebConnUserActivity sets the LastUserActivityAt of the hub for the given session. UpdateWebConnUserActivity(session model.Session, activityAt int64) // UploadFile uploads a single file in form of a completely constructed byte array for a channel. - UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) + UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) // 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. - UploadFileX(channelID, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) + UploadFileX(c *request.Context, channelID, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) // 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. - UploadFiles(teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) + UploadFiles(c *request.Context, teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) // UserIsInAdminRoleGroup returns true at least one of the user's groups are configured to set the members as // admins in the given syncable. UserIsInAdminRoleGroup(userID, syncableID string, syncableType model.GroupSyncableType) (bool, *model.AppError) @@ -390,7 +391,6 @@ type AppIface interface { VerifyPlugin(plugin, signature io.ReadSeeker) *model.AppError //GetUserStatusesByIds used by apiV4 GetUserStatusesByIds(userIDs []string) ([]*model.Status, *model.AppError) - AcceptLanguage() string AccountMigration() einterfaces.AccountMigrationInterface ActivateMfa(userID, token string) *model.AppError AddChannelsToRetentionPolicy(policyID string, channelIDs []string) *model.AppError @@ -405,22 +405,22 @@ type AppIface interface { 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) + AddTeamMember(c *request.Context, teamID, userID string) (*model.TeamMember, *model.AppError) + AddTeamMemberByInviteId(c *request.Context, inviteId, userID string) (*model.TeamMember, *model.AppError) + AddTeamMemberByToken(c *request.Context, userID, tokenID string) (*model.TeamMember, *model.AppError) + AddTeamMembers(c *request.Context, teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) AddTeamsToRetentionPolicy(policyID string, teamIDs []string) *model.AppError - AddUserToTeam(teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) - AddUserToTeamByInviteId(inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) - AddUserToTeamByTeamId(teamID string, user *model.User) *model.AppError - AddUserToTeamByToken(userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) + AddUserToTeam(c *request.Context, teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) + AddUserToTeamByInviteId(c *request.Context, inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) + AddUserToTeamByTeamId(c *request.Context, teamID string, user *model.User) *model.AppError + AddUserToTeamByToken(c *request.Context, userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) AdjustImage(file io.Reader) (*bytes.Buffer, *model.AppError) AllowOAuthAppAccessToUser(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError) AppendFile(fr io.Reader, path string) (int64, *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, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) + AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) + AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) AutocompleteChannels(teamID string, term string) (*model.ChannelList, *model.AppError) AutocompleteChannelsForSearch(teamID string, userID string, term string) (*model.ChannelList, *model.AppError) @@ -431,11 +431,11 @@ type AppIface interface { 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, outPath string, opts BulkExportOpts) *model.AppError - BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) - BulkImportWithPath(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) + BulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) + BulkImportWithPath(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) CancelJob(jobId string) *model.AppError ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *model.AppError) - CheckAndSendUserLimitWarningEmails() *model.AppError + CheckAndSendUserLimitWarningEmails(c *request.Context) *model.AppError CheckCanInviteToSharedChannel(channelId string) error CheckForClientSideCert(r *http.Request) (string, string, string) CheckMandatoryS3Fields(settings *model.FileSettings) *model.AppError @@ -459,14 +459,13 @@ type AppIface interface { 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, tokenUser *model.User) (*model.User, *model.AppError) + CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) CompleteSwitchWithOAuth(service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError) Compliance() einterfaces.ComplianceInterface Config() *model.Config - Context() context.Context CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError) - CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) - CreateChannelWithUser(channel *model.Channel, userID string) (*model.Channel, *model.AppError) + CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) + CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) CreateCommandWebhook(commandID string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) @@ -476,37 +475,37 @@ type AppIface interface { 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, tokenUser *model.User) (*model.User, *model.AppError) + CreateOAuthUser(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*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, setOnline bool) (savedPost *model.Post, err *model.AppError) - CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) - CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) + CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) + CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) + CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) CreateRetentionPolicy(policy *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError) CreateRole(role *model.Role) (*model.Role, *model.AppError) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) CreateSession(session *model.Session) (*model.Session, *model.AppError) CreateSidebarCategory(userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) - CreateTeam(team *model.Team) (*model.Team, *model.AppError) - CreateTeamWithUser(team *model.Team, userID string) (*model.Team, *model.AppError) + CreateTeam(c *request.Context, team *model.Team) (*model.Team, *model.AppError) + CreateTeamWithUser(c *request.Context, team *model.Team, userID string) (*model.Team, *model.AppError) CreateTermsOfService(text, userID string) (*model.TermsOfService, *model.AppError) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) - CreateUserAsAdmin(user *model.User, redirect string) (*model.User, *model.AppError) - CreateUserFromSignup(user *model.User, redirect string) (*model.User, *model.AppError) - CreateUserWithInviteId(user *model.User, inviteId, redirect string) (*model.User, *model.AppError) - CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) - CreateWebhookPost(userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) + CreateUserAsAdmin(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) + CreateUserFromSignup(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) + CreateUserWithInviteId(c *request.Context, user *model.User, inviteId, redirect string) (*model.User, *model.AppError) + CreateUserWithToken(c *request.Context, user *model.User, token *model.Token) (*model.User, *model.AppError) + CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) DBHealthCheckDelete() error DBHealthCheckWrite() error DataRetention() einterfaces.DataRetentionInterface - DeactivateGuests() *model.AppError + DeactivateGuests(c *request.Context) *model.AppError DeactivateMfa(userID string) *model.AppError DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError DeleteAllExpiredPluginKeys() *model.AppError DeleteAllKeysForPlugin(pluginID string) *model.AppError DeleteBrandImage() *model.AppError - DeleteChannel(channel *model.Channel, userID string) *model.AppError + DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError DeleteCommand(commandID string) *model.AppError DeleteEmoji(emoji *model.Emoji) *model.AppError DeleteEphemeralPost(userID, postID string) @@ -522,7 +521,7 @@ type AppIface interface { DeletePost(postID, deleteByID string) (*model.Post, *model.AppError) DeletePostFiles(post *model.Post) DeletePreferences(userID string, preferences model.Preferences) *model.AppError - DeleteReactionForPost(reaction *model.Reaction) *model.AppError + DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError) DeleteRetentionPolicy(policyID string) *model.AppError DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) @@ -536,13 +535,13 @@ type AppIface interface { DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command, *model.CommandResponse, *model.AppError) DoEmojisPermissionsMigration() DoGuestRolesCreationMigration() - DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) - DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError - DoPostAction(postID, actionId, userID, selectedOption string) (string, *model.AppError) - DoPostActionWithCookie(postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) + DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) + DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError + DoPostAction(c *request.Context, postID, actionId, userID, selectedOption string) (string, *model.AppError) + DoPostActionWithCookie(c *request.Context, postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) DoSystemConsoleRolesCreationMigration() - 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) + DoUploadFile(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) + DoUploadFileExpectModification(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) DownloadFromURL(downloadURL string) ([]byte, error) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{} @@ -671,7 +670,7 @@ type AppIface interface { 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, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) + GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*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) @@ -679,7 +678,7 @@ type AppIface interface { 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) + GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) GetPinnedPosts(channelID string) (*model.PostList, *model.AppError) GetPluginKey(pluginID string, key string) ([]byte, *model.AppError) GetPlugins() (*model.PluginsResponse, *model.AppError) @@ -743,7 +742,6 @@ type AppIface interface { GetStatus(userID string) (*model.Status, *model.AppError) GetStatusFromCache(userID string) *model.Status GetStatusesByIds(userIDs []string) (map[string]interface{}, *model.AppError) - GetT() i18n.TranslateFunc GetTeam(teamID string) (*model.Team, *model.AppError) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) GetTeamByName(name string) (*model.Team, *model.AppError) @@ -778,7 +776,7 @@ type AppIface interface { GetUserForLogin(id, loginId string) (*model.User, *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) + GetUsersByGroupChannelIds(c *request.Context, 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 @@ -804,11 +802,11 @@ type AppIface interface { GetWarnMetricsStatus() (map[string]*model.WarnMetricStatus, *model.AppError) 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 + HandleCommandResponse(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) + HandleCommandResponsePost(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) + HandleCommandWebhook(c *request.Context, hookID string, response *model.CommandResponse) *model.AppError HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte) - HandleIncomingWebhook(hookID string, req *model.IncomingWebhookRequest) *model.AppError + HandleIncomingWebhook(c *request.Context, 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 @@ -821,9 +819,7 @@ type AppIface interface { ImageProxyAdder() func(string) string ImageProxyRemover() (f func(string) string) ImportPermissions(jsonl io.Reader) error - InitPlugins(pluginDir, webappPluginDir string) - InitPostMetadata() - InitServer() + InitPlugins(c *request.Context, pluginDir, webappPluginDir string) InstallPluginFromData(data model.PluginEventData) InvalidateAllEmailInvites() *model.AppError InvalidateCacheForUser(userID string) @@ -831,19 +827,18 @@ type AppIface interface { 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 IsFirstUserAccount() bool IsLeader() bool IsPasswordValid(password string) *model.AppError IsPhase2MigrationCompleted() *model.AppError IsUserAway(lastActivityAt int64) bool IsUserSignUpAllowed() *model.AppError - 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.TeamMember, *model.AppError) + JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError + JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError + JoinUserToTeam(c *request.Context, team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) Ldap() einterfaces.LdapInterface - LeaveChannel(channelID string, userID string) *model.AppError - LeaveTeam(team *model.Team, user *model.User, requestorId string) *model.AppError + LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError + LeaveTeam(c *request.Context, team *model.Team, user *model.User, requestorId string) *model.AppError LimitedClientConfig() map[string]string ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Command, *model.AppError) ListDirectory(path string) ([]string, *model.AppError) @@ -852,8 +847,8 @@ type AppIface interface { ListPluginKeys(pluginID string, page, perPage int) ([]string, *model.AppError) ListTeamCommands(teamID string) ([]*model.Command, *model.AppError) Log() *mlog.Logger - LoginByOAuth(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) - MakePermissionError(permissions []*model.Permission) *model.AppError + LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) + MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError MarkChannelsAsViewed(channelIDs []string, userID string, currentSessionId string) (map[string]int64, *model.AppError) MaxPostSize() int MessageExport() einterfaces.MessageExportInterface @@ -862,34 +857,32 @@ type AppIface interface { MoveCommand(team *model.Team, command *model.Command) *model.AppError MoveFile(oldPath, newPath string) *model.AppError NewClusterDiscoveryService() *ClusterDiscoveryService - NewPluginAPI(manifest *model.Manifest) plugin.API + NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API Notification() einterfaces.NotificationInterface NotificationsLog() *mlog.Logger NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, forceAck bool, isBot bool) *model.AppError NotifySharedChannelUserUpdate(user *model.User) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError OriginChecker() func(*http.Request) bool - PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) - PatchPost(postID string, patch *model.PostPatch) (*model.Post, *model.AppError) + PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) + PatchPost(c *request.Context, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) PatchRetentionPolicy(patch *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *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 + PermanentDeleteAllUsers(c *request.Context) *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 + PermanentDeleteUser(c *request.Context, 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 + PostAddToChannelMessage(c *request.Context, 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 + PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError + PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError + PostUpdateChannelPurposeMessage(c *request.Context, 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 @@ -922,17 +915,16 @@ type AppIface interface { RemoveSamlPrivateCertificate() *model.AppError RemoveSamlPublicCertificate() *model.AppError RemoveTeamIcon(teamID string) *model.AppError - RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId string) *model.AppError + RemoveTeamMemberFromTeam(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError RemoveTeamsFromRetentionPolicy(policyID string, teamIDs []string) *model.AppError - RemoveUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError - RemoveUserFromTeam(teamID string, userID string, requestorId string) *model.AppError - RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel *model.Channel, team *model.Team) *model.AppError - RequestId() string - RequestLicenseAndAckWarnMetric(warnMetricId string, isBot bool) *model.AppError + RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError + RemoveUserFromTeam(c *request.Context, teamID string, userID string, requestorId string) *model.AppError + RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError + RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError ResetPermissionsSystem() *model.AppError ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs []string) (numAffected int, appErr *model.AppError) - RestoreChannel(channel *model.Channel, userID string) (*model.Channel, *model.AppError) + RestoreChannel(c *request.Context, 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) @@ -950,7 +942,7 @@ type AppIface interface { SaveAndBroadcastStatus(status *model.Status) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) - SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) + SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) SaveSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model.SharedChannelRemote, error) SaveUserTermsOfService(userID, termsOfServiceId string, accepted bool) *model.AppError @@ -961,10 +953,10 @@ type AppIface interface { SearchChannelsUserNotIn(teamID string, userID string, term string) (*model.ChannelList, *model.AppError) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) SearchEngine() *searchengine.Broker - SearchFilesInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError) + SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *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) + SearchPostsInTeamForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError) SearchPublicTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError) SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError) @@ -976,8 +968,8 @@ type AppIface interface { 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, post *model.Post) (bool, *model.AppError) - SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) + SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) + SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) SendCloudTrialEndWarningEmail(trialEndDate, siteURL string) *model.AppError SendCloudTrialEndedEmail() *model.AppError SendEmailVerification(user *model.User, newEmail, redirect string) *model.AppError @@ -987,7 +979,6 @@ type AppIface interface { SendPaymentFailedEmail(failedPayment *model.FailedPayment) *model.AppError ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, sourcePluginId, destinationPluginId string) ServePluginRequest(w http.ResponseWriter, r *http.Request) - Session() *model.Session SessionCacheLength() int SessionHasPermissionTo(session model.Session, permission *model.Permission) bool SessionHasPermissionToAny(session model.Session, permissions []*model.Permission) bool @@ -999,14 +990,10 @@ type AppIface interface { 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) - SetContext(c context.Context) SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError SetDefaultProfileImage(user *model.User) *model.AppError - SetIpAddress(s string) - 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 @@ -1016,31 +1003,26 @@ type AppIface interface { SetProfileImageFromFile(userID string, file io.Reader) *model.AppError SetProfileImageFromMultiPartFile(userID string, file multipart.File) *model.AppError SetRemoteClusterLastPingAt(remoteClusterId string) *model.AppError - SetRequestId(s string) SetSamlIdpCertificateFromMetadata(data []byte) *model.AppError SetSearchEngine(se *searchengine.Broker) SetServer(srv *Server) - SetSession(s *model.Session) SetStatusAwayIfNeeded(userID string, manual bool) SetStatusDoNotDisturb(userID string) SetStatusOffline(userID string, manual bool) SetStatusOnline(userID string, manual bool) SetStatusOutOfOffice(userID string) - SetT(t i18n.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) - SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) + SlackImport(c *request.Context, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) SoftDeleteTeam(teamID string) *model.AppError Srv() *Server - SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) + SubmitInteractiveDialog(c *request.Context, 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) SyncPluginsActiveState() - T(translationID string, args ...interface{}) string TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError) TelemetryId() string TestElasticsearch(cfg *model.Config) *model.AppError @@ -1052,15 +1034,15 @@ type AppIface interface { Timezones() *timezones.Timezones ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, *model.AppError) TotalWebsocketConnections() int - TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) + TriggerWebhook(c *request.Context, 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) + UpdateActive(c *request.Context, user *model.User, active bool) (*model.User, *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) + UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*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 @@ -1080,7 +1062,7 @@ type AppIface interface { 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) + UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) UpdatePreferences(userID string, preferences model.Preferences) *model.AppError UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError) @@ -1100,18 +1082,17 @@ type AppIface interface { UpdateThreadReadForUser(userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) UpdateThreadsReadForUser(userID, teamID string) *model.AppError UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) - UpdateUserActive(userID string, active bool) *model.AppError + UpdateUserActive(c *request.Context, 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, sendNotifications bool) (*model.User, *model.AppError) UpdateUserRoles(userID string, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError) UpdateUserRolesWithUser(user *model.User, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError) - UploadData(us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) + UploadData(c *request.Context, us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError - UploadMultipartFiles(teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) + UploadMultipartFiles(c *request.Context, 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) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError VerifyUserEmail(userID, email string) *model.AppError diff --git a/app/authentication.go b/app/authentication.go index 7d9b142c1b8..98f1bf95008 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -7,6 +7,7 @@ import ( "net/http" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mfa" "github.com/mattermost/mattermost-server/v5/utils" @@ -126,13 +127,13 @@ func (a *App) checkUserPassword(user *model.User, password string) *model.AppErr return nil } -func (a *App) checkLdapUserPasswordAndAllCriteria(ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) { +func (a *App) checkLdapUserPasswordAndAllCriteria(c *request.Context, ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) { 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(c, *ldapId, password) if err != nil { err.StatusCode = http.StatusUnauthorized return nil, err @@ -229,7 +230,7 @@ func checkUserNotBot(user *model.User) *model.AppError { return nil } -func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) { +func (a *App) authenticateUser(c *request.Context, user *model.User, password, mfaToken string) (*model.User, *model.AppError) { license := a.Srv().License() ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP @@ -239,7 +240,7 @@ func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*mo return user, err } - ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(user.AuthData, password, mfaToken) + ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(c, user.AuthData, password, mfaToken) if err != nil { err.StatusCode = http.StatusUnauthorized return user, err diff --git a/app/authorization.go b/app/authorization.go index 93664e2f84d..eb3d44e9534 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -12,13 +12,13 @@ import ( "github.com/mattermost/mattermost-server/v5/shared/mlog" ) -func (a *App) MakePermissionError(permissions []*model.Permission) *model.AppError { +func (a *App) MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError { permissionsStr := "permission=" for _, permission := range permissions { permissionsStr += permission.Id permissionsStr += "," } - return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+a.Session().UserId+", "+permissionsStr, http.StatusForbidden) + return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+s.UserId+", "+permissionsStr, http.StatusForbidden) } func (a *App) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool { @@ -263,7 +263,7 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s // the bot doesn't exist at all. return model.MakeBotNotFoundError(botUserId) } - return a.MakePermissionError([]*model.Permission{model.PERMISSION_MANAGE_BOTS}) + return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_BOTS}) } } else { if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_OTHERS_BOTS) { @@ -272,7 +272,7 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s // pretend as if the bot doesn't exist at all. return model.MakeBotNotFoundError(botUserId) } - return a.MakePermissionError([]*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS}) + return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS}) } } diff --git a/app/auto_responder.go b/app/auto_responder.go index 60ee894a00c..c52af937fde 100644 --- a/app/auto_responder.go +++ b/app/auto_responder.go @@ -7,6 +7,7 @@ import ( "net/http" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" ) @@ -20,7 +21,7 @@ func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) ( ) } -func (a *App) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { +func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { if channel.Type != model.CHANNEL_DIRECT { return false, nil } @@ -48,10 +49,10 @@ func (a *App) SendAutoResponseIfNecessary(channel *model.Channel, sender *model. return false, nil } - return a.SendAutoResponse(channel, receiver, post) + return a.SendAutoResponse(c, channel, receiver, post) } -func (a *App) SendAutoResponse(channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { +func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { if receiver == nil || receiver.NotifyProps == nil { return false, nil } @@ -76,7 +77,7 @@ func (a *App) SendAutoResponse(channel *model.Channel, receiver *model.User, pos UserId: receiver.Id, } - if _, err := a.CreatePost(autoResponderPost, channel, false, false); err != nil { + if _, err := a.CreatePost(c, autoResponderPost, channel, false, false); err != nil { return false, err } diff --git a/app/auto_responder_test.go b/app/auto_responder_test.go index def9ca48b0e..3e9909a7bbd 100644 --- a/app/auto_responder_test.go +++ b/app/auto_responder_test.go @@ -17,7 +17,7 @@ func TestSetAutoResponderStatus(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) th.App.SetStatusOnline(user.Id, true) @@ -56,7 +56,7 @@ func TestDisableAutoResponder(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) th.App.SetStatusOnline(user.Id, true) @@ -98,14 +98,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { channel := th.CreateDmChannel(receiver) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost) + sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost) assert.Nil(t, err) assert.True(t, sent) @@ -128,14 +128,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { channel := th.CreateDmChannel(receiver) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost) + sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost) assert.Nil(t, err) assert.False(t, sent) @@ -145,14 +145,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponseIfNecessary(th.BasicChannel, th.BasicUser, savedPost) + sent, err := th.App.SendAutoResponseIfNecessary(th.Context, th.BasicChannel, th.BasicUser, savedPost) assert.Nil(t, err) assert.False(t, sent) @@ -175,7 +175,7 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { channel := th.CreateDmChannel(receiver) - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "botusername", Description: "bot", OwnerId: th.BasicUser.Id, @@ -185,14 +185,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { botUser, err := th.App.GetUser(bot.UserId) assert.Nil(t, err) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: "zz" + model.NewId() + "a", UserId: botUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponseIfNecessary(channel, botUser, savedPost) + sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, botUser, savedPost) assert.Nil(t, err) assert.False(t, sent) @@ -215,7 +215,7 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { channel := th.CreateDmChannel(receiver) - savedPost, err := th.App.CreatePost(&model.Post{ + savedPost, err := th.App.CreatePost(th.Context, &model.Post{ ChannelId: channel.Id, Message: NewTestId(), UserId: th.BasicUser.Id}, @@ -224,12 +224,12 @@ func TestSendAutoResponseIfNecessary(t *testing.T) { assert.Nil(t, err) - sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost) + sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost) require.Nil(t, err) assert.True(t, sent) - sent, err = th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost) + sent, err = th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost) require.Nil(t, err) assert.False(t, sent) @@ -241,7 +241,7 @@ func TestSendAutoResponseSuccess(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) patch := &model.UserPatch{} patch.NotifyProps = make(map[string]string) @@ -251,14 +251,14 @@ func TestSendAutoResponseSuccess(t *testing.T) { userUpdated1, err := th.App.PatchUser(user.Id, patch, true) require.Nil(t, err) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost) + sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost) assert.Nil(t, err) assert.True(t, sent) @@ -282,7 +282,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) patch := &model.UserPatch{} patch.NotifyProps = make(map[string]string) @@ -292,14 +292,14 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) { userUpdated1, err := th.App.PatchUser(user.Id, patch, true) require.Nil(t, err) - parentPost, _ := th.App.CreatePost(&model.Post{ + parentPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id, @@ -308,7 +308,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) { th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost) + sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost) assert.Nil(t, err) assert.True(t, sent) @@ -332,7 +332,7 @@ func TestSendAutoResponseFailure(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) patch := &model.UserPatch{} patch.NotifyProps = make(map[string]string) @@ -342,14 +342,14 @@ func TestSendAutoResponseFailure(t *testing.T) { userUpdated1, err := th.App.PatchUser(user.Id, patch, true) require.Nil(t, err) - savedPost, _ := th.App.CreatePost(&model.Post{ + savedPost, _ := th.App.CreatePost(th.Context, &model.Post{ ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", UserId: th.BasicUser.Id}, th.BasicChannel, false, true) - sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost) + sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost) assert.Nil(t, err) assert.False(t, sent) diff --git a/app/bot.go b/app/bot.go index 4c10f3cfb28..68c260f7dea 100644 --- a/app/bot.go +++ b/app/bot.go @@ -11,6 +11,7 @@ import ( "mime/multipart" "net/http" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -18,7 +19,7 @@ import ( ) // CreateBot creates the given bot and corresponding user. -func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { +func (a *App) CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError) { user, nErr := a.Srv().Store.User().Save(model.UserFromBot(bot)) if nErr != nil { var appErr *model.AppError @@ -67,7 +68,7 @@ func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { if err != nil { return nil, err } - channel, err := a.getOrCreateDirectChannelWithUser(user, botOwner) + channel, err := a.getOrCreateDirectChannelWithUser(c, user, botOwner) if err != nil { return nil, err } @@ -80,7 +81,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, true); err != nil { + if _, err := a.CreatePostAsUser(c, botAddPost, c.Session().Id, true); err != nil { return nil, err } } @@ -240,7 +241,7 @@ func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppEr } // 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) { +func (a *App) UpdateBotActive(c *request.Context, botUserId string, active bool) (*model.Bot, *model.AppError) { user, nErr := a.Srv().Store.User().Get(context.Background(), botUserId) if nErr != nil { var nfErr *store.ErrNotFound @@ -252,7 +253,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model } } - if _, err := a.UpdateActive(user, active); err != nil { + if _, err := a.UpdateActive(c, user, active); err != nil { return nil, err } @@ -347,7 +348,7 @@ func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.A } // disableUserBots disables all bots owned by the given user. -func (a *App) disableUserBots(userID string) *model.AppError { +func (a *App) disableUserBots(c *request.Context, userID string) *model.AppError { perPage := 20 for { options := &model.BotGetOptions{ @@ -363,7 +364,7 @@ func (a *App) disableUserBots(userID string) *model.AppError { } for _, bot := range userBots { - _, err := a.UpdateBotActive(bot.UserId, false) + _, err := a.UpdateBotActive(c, bot.UserId, false) if err != nil { mlog.Warn("Unable to deactivate bot.", mlog.String("bot_user_id", bot.UserId), mlog.Err(err)) } @@ -380,7 +381,7 @@ func (a *App) disableUserBots(userID string) *model.AppError { return nil } -func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError { +func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID string) *model.AppError { perPage := 25 botOptions := &model.BotGetOptions{ OwnerId: userID, @@ -442,7 +443,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError // for each sysadmin, notify user that owns bots was disabled for _, sysAdmin := range sysAdmins { - channel, appErr := a.GetOrCreateDirectChannel(sysAdmin.Id, sysAdmin.Id) + channel, appErr := a.GetOrCreateDirectChannel(c, sysAdmin.Id, sysAdmin.Id) if appErr != nil { return appErr } @@ -454,7 +455,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError Type: model.POST_SYSTEM_GENERIC, } - _, appErr = a.CreatePost(post, channel, false, true) + _, appErr = a.CreatePost(c, post, channel, false, true) if appErr != nil { return appErr } diff --git a/app/bot_test.go b/app/bot_test.go index 6088e1eb997..d0d333ab362 100644 --- a/app/bot_test.go +++ b/app/bot_test.go @@ -24,7 +24,7 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.CreateBot(&model.Bot{ + _, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "invalid username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -37,7 +37,7 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.CreateBot(&model.Bot{ + _, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: strings.Repeat("x", 1025), OwnerId: th.BasicUser.Id, @@ -50,7 +50,7 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username.", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -65,7 +65,7 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -80,7 +80,7 @@ func TestCreateBot(t *testing.T) { require.Nil(t, err) // Check that a post was created to add bot to team and channels - channel, err := th.App.getOrCreateDirectChannelWithUser(user, th.BasicUser) + channel, err := th.App.getOrCreateDirectChannelWithUser(th.Context, user, th.BasicUser) require.Nil(t, err) posts, err := th.App.GetPosts(channel.Id, 0, 1) require.Nil(t, err) @@ -94,7 +94,7 @@ func TestCreateBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.CreateBot(&model.Bot{ + _, err := th.App.CreateBot(th.Context, &model.Bot{ Username: th.BasicUser.Username, Description: "a bot", OwnerId: th.BasicUser.Id, @@ -109,7 +109,7 @@ func TestPatchBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -132,7 +132,7 @@ func TestPatchBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -162,7 +162,7 @@ func TestPatchBot(t *testing.T) { OwnerId: th.BasicUser.Id, } - createdBot, err := th.App.CreateBot(bot) + createdBot, err := th.App.CreateBot(th.Context, bot) require.Nil(t, err) defer th.App.PermanentDeleteBot(createdBot.UserId) @@ -189,7 +189,7 @@ func TestPatchBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", DisplayName: "bot", Description: "a bot", @@ -212,7 +212,7 @@ func TestGetBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot1, err := th.App.CreateBot(&model.Bot{ + bot1, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -220,7 +220,7 @@ func TestGetBot(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot1.UserId) - bot2, err := th.App.CreateBot(&model.Bot{ + bot2, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username2", Description: "a second bot", OwnerId: th.BasicUser.Id, @@ -228,13 +228,13 @@ func TestGetBot(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot2.UserId) - deletedBot, err := th.App.CreateBot(&model.Bot{ + deletedBot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username3", Description: "a deleted bot", OwnerId: th.BasicUser.Id, }) require.Nil(t, err) - deletedBot, err = th.App.UpdateBotActive(deletedBot.UserId, false) + deletedBot, err = th.App.UpdateBotActive(th.Context, deletedBot.UserId, false) require.Nil(t, err) defer th.App.PermanentDeleteBot(deletedBot.UserId) @@ -276,7 +276,7 @@ func TestGetBots(t *testing.T) { OwnerId1 := model.NewId() OwnerId2 := model.NewId() - bot1, err := th.App.CreateBot(&model.Bot{ + bot1, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: OwnerId1, @@ -284,17 +284,17 @@ func TestGetBots(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot1.UserId) - deletedBot1, err := th.App.CreateBot(&model.Bot{ + deletedBot1, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username4", Description: "a deleted bot", OwnerId: OwnerId1, }) require.Nil(t, err) - deletedBot1, err = th.App.UpdateBotActive(deletedBot1.UserId, false) + deletedBot1, err = th.App.UpdateBotActive(th.Context, deletedBot1.UserId, false) require.Nil(t, err) defer th.App.PermanentDeleteBot(deletedBot1.UserId) - bot2, err := th.App.CreateBot(&model.Bot{ + bot2, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username2", Description: "a second bot", OwnerId: OwnerId1, @@ -302,7 +302,7 @@ func TestGetBots(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot2.UserId) - bot3, err := th.App.CreateBot(&model.Bot{ + bot3, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username3", Description: "a third bot", OwnerId: OwnerId1, @@ -310,7 +310,7 @@ func TestGetBots(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot3.UserId) - bot4, err := th.App.CreateBot(&model.Bot{ + bot4, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username5", Description: "a fourth bot", OwnerId: OwnerId2, @@ -318,13 +318,13 @@ func TestGetBots(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot4.UserId) - deletedBot2, err := th.App.CreateBot(&model.Bot{ + deletedBot2, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username6", Description: "a deleted bot", OwnerId: OwnerId2, }) require.Nil(t, err) - deletedBot2, err = th.App.UpdateBotActive(deletedBot2.UserId, false) + deletedBot2, err = th.App.UpdateBotActive(th.Context, deletedBot2.UserId, false) require.Nil(t, err) defer th.App.PermanentDeleteBot(deletedBot2.UserId) @@ -466,7 +466,7 @@ func TestUpdateBotActive(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.UpdateBotActive(model.NewId(), false) + _, err := th.App.UpdateBotActive(th.Context, model.NewId(), false) require.NotNil(t, err) require.Equal(t, "app.user.missing_account.const", err.Id) }) @@ -475,7 +475,7 @@ func TestUpdateBotActive(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -483,21 +483,21 @@ func TestUpdateBotActive(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(bot.UserId) - disabledBot, err := th.App.UpdateBotActive(bot.UserId, false) + disabledBot, err := th.App.UpdateBotActive(th.Context, bot.UserId, false) require.Nil(t, err) require.NotEqual(t, 0, disabledBot.DeleteAt) // Disabling should be idempotent - disabledBotAgain, err := th.App.UpdateBotActive(bot.UserId, false) + disabledBotAgain, err := th.App.UpdateBotActive(th.Context, bot.UserId, false) require.Nil(t, err) require.Equal(t, disabledBot.DeleteAt, disabledBotAgain.DeleteAt) - reenabledBot, err := th.App.UpdateBotActive(bot.UserId, true) + reenabledBot, err := th.App.UpdateBotActive(th.Context, bot.UserId, true) require.Nil(t, err) require.EqualValues(t, 0, reenabledBot.DeleteAt) // Re-enabling should be idempotent - reenabledBotAgain, err := th.App.UpdateBotActive(bot.UserId, true) + reenabledBotAgain, err := th.App.UpdateBotActive(th.Context, bot.UserId, true) require.Nil(t, err) require.Equal(t, reenabledBot.DeleteAt, reenabledBotAgain.DeleteAt) }) @@ -507,7 +507,7 @@ func TestPermanentDeleteBot(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -536,7 +536,7 @@ func TestDisableUserBots(t *testing.T) { }() for i := 0; i < 46; i++ { - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: fmt.Sprintf("username%v", i), Description: "a bot", OwnerId: ownerId1, @@ -546,7 +546,7 @@ func TestDisableUserBots(t *testing.T) { } require.Len(t, bots, 46) - u2bot1, err := th.App.CreateBot(&model.Bot{ + u2bot1, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username_nodisable", Description: "a bot", OwnerId: ownerId2, @@ -554,7 +554,7 @@ func TestDisableUserBots(t *testing.T) { require.Nil(t, err) defer th.App.PermanentDeleteBot(u2bot1.UserId) - err = th.App.disableUserBots(ownerId1) + err = th.App.disableUserBots(th.Context, ownerId1) require.Nil(t, err) // Check all bots and corrensponding users are disabled for creator 1 @@ -574,7 +574,7 @@ func TestDisableUserBots(t *testing.T) { require.Zero(t, user.DeleteAt) // Bad id doesn't do anything or break horribly - err = th.App.disableUserBots(model.NewId()) + err = th.App.disableUserBots(th.Context, model.NewId()) require.Nil(t, err) } @@ -596,7 +596,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { Password: "hello1", Username: "un_sysadmin1", Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} - _, err := th.App.CreateUser(&sysadmin1) + _, err := th.App.CreateUser(th.Context, &sysadmin1) require.Nil(t, err, "failed to create user") th.App.UpdateUserRoles(sysadmin1.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) @@ -606,12 +606,12 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { Password: "hello1", Username: "un_sysadmin2", Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} - _, err = th.App.CreateUser(&sysadmin2) + _, err = th.App.CreateUser(th.Context, &sysadmin2) require.Nil(t, err, "failed to create user") th.App.UpdateUserRoles(sysadmin2.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) // create user to be disabled - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: "user1@example.com", Username: "user1_disabled", Nickname: "user1", @@ -620,7 +620,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { require.Nil(t, err, "failed to create user") // create user that doesn't own any bots - user2, err := th.App.CreateUser(&model.User{ + user2, err := th.App.CreateUser(th.Context, &model.User{ Email: "user2@example.com", Username: "user2_disabled", Nickname: "user2", @@ -633,7 +633,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { // create bots owned by user (equal to numBotsToPrint) var bot *model.Bot for i := 0; i < numBotsToPrint; i++ { - bot, err = th.App.CreateBot(&model.Bot{ + bot, err = th.App.CreateBot(th.Context, &model.Bot{ Username: fmt.Sprintf("bot%v", i), Description: "a bot", OwnerId: user1.Id, @@ -644,13 +644,13 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { assert.Len(t, userBots, 10) // get DM channels for sysadmin1 and sysadmin2 - channelSys1, appErr := th.App.GetOrCreateDirectChannel(sysadmin1.Id, sysadmin1.Id) + channelSys1, appErr := th.App.GetOrCreateDirectChannel(th.Context, sysadmin1.Id, sysadmin1.Id) require.Nil(t, appErr) - channelSys2, appErr := th.App.GetOrCreateDirectChannel(sysadmin2.Id, sysadmin2.Id) + channelSys2, appErr := th.App.GetOrCreateDirectChannel(th.Context, sysadmin2.Id, sysadmin2.Id) require.Nil(t, appErr) // send notification for user without bots - err = th.App.notifySysadminsBotOwnerDeactivated(user2.Id) + err = th.App.notifySysadminsBotOwnerDeactivated(th.Context, user2.Id) require.Nil(t, err) // get posts from sysadmin1 and sysadmin2 DM channels @@ -663,7 +663,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { assert.Empty(t, posts2.Order) // send notification for user with bots - err = th.App.notifySysadminsBotOwnerDeactivated(user1.Id) + err = th.App.notifySysadminsBotOwnerDeactivated(th.Context, user1.Id) require.Nil(t, err) // get posts from sysadmin1 and sysadmin2 DM channels @@ -690,7 +690,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) { // create additional bot to go over the printable limit for i := numBotsToPrint; i < numBotsToPrint+1; i++ { - bot, err = th.App.CreateBot(&model.Bot{ + bot, err = th.App.CreateBot(th.Context, &model.Bot{ Username: fmt.Sprintf("bot%v", i), Description: "a bot", OwnerId: user1.Id, diff --git a/app/channel.go b/app/channel.go index d35538990a7..6d19e253c73 100644 --- a/app/channel.go +++ b/app/channel.go @@ -10,6 +10,7 @@ import ( "net/http" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -21,7 +22,7 @@ import ( // CreateDefaultChannels creates channels in the given team for each channel returned by (*App).DefaultChannelNames. // -func (a *App) CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError) { +func (a *App) CreateDefaultChannels(c *request.Context, teamID string) ([]*model.Channel, *model.AppError) { displayNames := map[string]string{ "town-square": i18n.T("api.channel.create_default_channels.town_square"), "off-topic": i18n.T("api.channel.create_default_channels.off_topic"), @@ -31,7 +32,7 @@ func (a *App) CreateDefaultChannels(teamID string) ([]*model.Channel, *model.App for _, name := range defaultChannelNames { displayName := i18n.TDefault(displayNames[name], name) channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.CHANNEL_OPEN, TeamId: teamID} - if _, err := a.CreateChannel(channel, false); err != nil { + if _, err := a.CreateChannel(c, channel, false); err != nil { return nil, err } channels = append(channels, channel) @@ -65,7 +66,7 @@ func (a *App) DefaultChannelNames() []string { return names } -func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { +func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { var requestor *model.User var nErr error if userRequestorId != "" { @@ -114,7 +115,7 @@ func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin } if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { - if aErr := a.postJoinMessageForDefaultChannel(user, requestor, channel); aErr != nil { + if aErr := a.postJoinMessageForDefaultChannel(c, user, requestor, channel); aErr != nil { mlog.Warn("Failed to post join/leave message", mlog.Err(aErr)) } } @@ -145,24 +146,24 @@ func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin return nil } -func (a *App) postJoinMessageForDefaultChannel(user *model.User, requestor *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError { if channel.Name == model.DEFAULT_CHANNEL { if requestor == nil { - if err := a.postJoinTeamMessage(user, channel); err != nil { + if err := a.postJoinTeamMessage(c, user, channel); err != nil { return err } } else { - if err := a.postAddToTeamMessage(requestor, user, channel, ""); err != nil { + if err := a.postAddToTeamMessage(c, requestor, user, channel, ""); err != nil { return err } } } else { if requestor == nil { - if err := a.postJoinChannelMessage(user, channel); err != nil { + if err := a.postJoinChannelMessage(c, user, channel); err != nil { return err } } else { - if err := a.PostAddToChannelMessage(requestor, user, channel, ""); err != nil { + if err := a.PostAddToChannelMessage(c, requestor, user, channel, ""); err != nil { return err } } @@ -171,7 +172,7 @@ func (a *App) postJoinMessageForDefaultChannel(user *model.User, requestor *mode return nil } -func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { if channel.IsGroupOrDirect() { return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest) } @@ -192,7 +193,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*mod channel.CreatorId = userID - rchannel, err := a.CreateChannel(channel, true) + rchannel, err := a.CreateChannel(c, channel, true) if err != nil { return nil, err } @@ -202,7 +203,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*mod return nil, err } - a.postJoinChannelMessage(user, channel) + a.postJoinChannelMessage(c, user, channel) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CREATED, "", "", userID, nil) message.Add("channel_id", channel.Id) @@ -235,7 +236,7 @@ func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDi return newChannel, nil } -func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { +func (a *App) CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { channel.DisplayName = strings.TrimSpace(channel.DisplayName) sc, nErr := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) if nErr != nil { @@ -310,7 +311,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ChannelHasBeenCreated(pluginContext, sc) return true @@ -321,7 +322,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan return sc, nil } -func (a *App) GetOrCreateDirectChannel(userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { channel, nErr := a.getDirectChannel(userID, otherUserID) if nErr != nil { return nil, nErr @@ -339,11 +340,11 @@ func (a *App) GetOrCreateDirectChannel(userID, otherUserID string, channelOption return nil, err } - a.handleCreationEvent(userID, otherUserID, channel) + a.handleCreationEvent(c, userID, otherUserID, channel) return channel, nil } -func (a *App) getOrCreateDirectChannelWithUser(user, otherUser *model.User) (*model.Channel, *model.AppError) { +func (a *App) getOrCreateDirectChannelWithUser(c *request.Context, user, otherUser *model.User) (*model.Channel, *model.AppError) { channel, nErr := a.getDirectChannel(user.Id, otherUser.Id) if nErr != nil { return nil, nErr @@ -361,17 +362,17 @@ func (a *App) getOrCreateDirectChannelWithUser(user, otherUser *model.User) (*mo return nil, err } - a.handleCreationEvent(user.Id, otherUser.Id, channel) + a.handleCreationEvent(c, user.Id, otherUser.Id, channel) return channel, nil } -func (a *App) handleCreationEvent(userID, otherUserID string, channel *model.Channel) { +func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string, channel *model.Channel) { a.InvalidateCacheForUser(userID) a.InvalidateCacheForUser(otherUserID) if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ChannelHasBeenCreated(pluginContext, channel) return true @@ -671,13 +672,13 @@ func (a *App) UpdateChannelScheme(channel *model.Channel) (*model.Channel, *mode return a.UpdateChannel(oldChannel) } -func (a *App) UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { +func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { channel, err := a.UpdateChannel(oldChannel) if err != nil { return channel, err } - if err := a.postChannelPrivacyMessage(user, channel); err != nil { + if err := a.postChannelPrivacyMessage(c, user, channel); err != nil { if channel.Type == model.CHANNEL_OPEN { channel.Type = model.CHANNEL_PRIVATE } else { @@ -697,7 +698,7 @@ func (a *App) UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) return channel, nil } -func (a *App) postChannelPrivacyMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { message := (map[string]string{ model.CHANNEL_OPEN: i18n.T("api.channel.change_channel_privacy.private_to_public"), model.CHANNEL_PRIVATE: i18n.T("api.channel.change_channel_privacy.public_to_private"), @@ -712,14 +713,14 @@ func (a *App) postChannelPrivacyMessage(user *model.User, channel *model.Channel }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postChannelPrivacyMessage", "api.channel.post_channel_privacy_message.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { if channel.DeleteAt == 0 { return nil, model.NewAppError("restoreChannel", "api.channel.restore_channel.restored.app_error", nil, "", http.StatusBadRequest) } @@ -758,7 +759,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Chan }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { mlog.Warn("Failed to post unarchive message", mlog.Err(err)) } } @@ -766,7 +767,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Chan return channel, nil } -func (a *App) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { +func (a *App) PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { oldChannelDisplayName := channel.DisplayName oldChannelHeader := channel.Header oldChannelPurpose := channel.Purpose @@ -778,19 +779,19 @@ func (a *App) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, us } if oldChannelDisplayName != channel.DisplayName { - if err = a.PostUpdateChannelDisplayNameMessage(userID, channel, oldChannelDisplayName, channel.DisplayName); err != nil { + if err = a.PostUpdateChannelDisplayNameMessage(c, userID, channel, oldChannelDisplayName, channel.DisplayName); err != nil { mlog.Warn(err.Error()) } } if channel.Header != oldChannelHeader { - if err = a.PostUpdateChannelHeaderMessage(userID, channel, oldChannelHeader, channel.Header); err != nil { + if err = a.PostUpdateChannelHeaderMessage(c, userID, channel, oldChannelHeader, channel.Header); err != nil { mlog.Warn(err.Error()) } } if channel.Purpose != oldChannelPurpose { - if err = a.PostUpdateChannelPurposeMessage(userID, channel, oldChannelPurpose, channel.Purpose); err != nil { + if err = a.PostUpdateChannelPurposeMessage(c, userID, channel, oldChannelPurpose, channel.Purpose); err != nil { mlog.Warn(err.Error()) } } @@ -1215,7 +1216,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe return member, nil } -func (a *App) DeleteChannel(channel *model.Channel, userID string) *model.AppError { +func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { ihc := make(chan store.StoreResult, 1) ohc := make(chan store.StoreResult, 1) @@ -1282,7 +1283,7 @@ func (a *App) DeleteChannel(channel *model.Channel, userID string) *model.AppErr }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { mlog.Warn("Failed to post archive message", mlog.Err(err)) } } @@ -1416,7 +1417,7 @@ type ChannelMemberOpts struct { } // AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel. -func (a *App) AddChannelMember(userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { +func (a *App) AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { if member, err := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, userID); err != nil { var nfErr *store.ErrNotFound if !errors.As(err, &nfErr) { @@ -1447,7 +1448,7 @@ func (a *App) AddChannelMember(userID string, channel *model.Channel, opts Chann if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedChannel(pluginContext, cm, userRequestor) return true @@ -1456,10 +1457,10 @@ func (a *App) AddChannelMember(userID string, channel *model.Channel, opts Chann } if opts.UserRequestorID == "" || userID == opts.UserRequestorID { - a.postJoinChannelMessage(user, channel) + a.postJoinChannelMessage(c, user, channel) } else { a.Srv().Go(func() { - a.PostAddToChannelMessage(userRequestor, user, channel, opts.PostRootID) + a.PostAddToChannelMessage(c, userRequestor, user, channel, opts.PostRootID) }) } @@ -1502,7 +1503,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError return nil } -func (a *App) PostUpdateChannelHeaderMessage(userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { +func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), 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) @@ -1529,14 +1530,14 @@ func (a *App) PostUpdateChannelHeaderMessage(userID string, channel *model.Chann }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("", "api.channel.post_update_channel_header_message_and_forget.post.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) PostUpdateChannelPurposeMessage(userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { +func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) @@ -1562,14 +1563,14 @@ func (a *App) PostUpdateChannelPurposeMessage(userID string, channel *model.Chan "new_purpose": newChannelPurpose, }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("", "app.channel.post_update_channel_purpose_message.post.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) PostUpdateChannelDisplayNameMessage(userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { +func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), 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) @@ -1589,7 +1590,7 @@ func (a *App) PostUpdateChannelDisplayNameMessage(userID string, channel *model. }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.create_post.error", nil, err.Error(), http.StatusInternalServerError) } @@ -1914,7 +1915,7 @@ func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread, return channelUnread, nil } -func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError { +func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { userChan := make(chan store.StoreResult, 1) memberChan := make(chan store.StoreResult, 1) go func() { @@ -1958,7 +1959,7 @@ func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedChannel(pluginContext, cm, nil) return true @@ -1966,14 +1967,14 @@ func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError }) } - if err := a.postJoinChannelMessage(user, channel); err != nil { + if err := a.postJoinChannelMessage(c, user, channel); err != nil { return err } return nil } -func (a *App) postJoinChannelMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.join_channel.post_and_forget"), user.Username) postType := model.POST_JOIN_CHANNEL @@ -1992,14 +1993,14 @@ func (a *App) postJoinChannelMessage(user *model.User, channel *model.Channel) * }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postJoinChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) postJoinTeamMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.join_team.post_and_forget"), user.Username), @@ -2010,14 +2011,14 @@ func (a *App) postJoinTeamMessage(user *model.User, channel *model.Channel) *mod }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postJoinTeamMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) LeaveChannel(channelID string, userID string) *model.AppError { +func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError { sc := make(chan store.StoreResult, 1) go func() { channel, err := a.Srv().Store.Channel().Get(channelID, true) @@ -2078,7 +2079,7 @@ func (a *App) LeaveChannel(channelID string, userID string) *model.AppError { return err } - if err := a.removeUserFromChannel(userID, userID, channel); err != nil { + if err := a.removeUserFromChannel(c, userID, userID, channel); err != nil { return err } @@ -2087,13 +2088,13 @@ func (a *App) LeaveChannel(channelID string, userID string) *model.AppError { } a.Srv().Go(func() { - a.postLeaveChannelMessage(user, channel) + a.postLeaveChannelMessage(c, user, channel) }) return nil } -func (a *App) postLeaveChannelMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, // Message here embeds `@username`, not just `username`, to ensure that mentions @@ -2107,14 +2108,14 @@ func (a *App) postLeaveChannelMessage(user *model.User, channel *model.Channel) }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postLeaveChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.add_member.added"), addedUser.Username, user.Username) postType := model.POST_ADD_TO_CHANNEL @@ -2137,14 +2138,14 @@ func (a *App) PostAddToChannelMessage(user *model.User, addedUser *model.User, c }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postAddToChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) postAddToTeamMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.add_user_to_team.added"), addedUser.Username, user.Username), @@ -2159,14 +2160,14 @@ func (a *App) postAddToTeamMessage(user *model.User, addedUser *model.User, chan }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postAddToTeamMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) postRemoveFromChannelMessage(removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { +func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, // Message here embeds `@username`, not just `username`, to ensure that mentions @@ -2181,14 +2182,14 @@ func (a *App) postRemoveFromChannelMessage(removerUserId string, removedUser *mo }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postRemoveFromChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { user, nErr := a.Srv().Store.User().Get(context.Background(), userIDToRemove) if nErr != nil { var nfErr *store.ErrNotFound @@ -2240,7 +2241,7 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string, return model.NewAppError("removeUserFromChannel", "api.team.remove_user_from_team.missing.app_error", nil, err.Error(), http.StatusBadRequest) } - if err = a.RemoveTeamMemberFromTeam(teamMember, removerUserId); err != nil { + if err = a.RemoveTeamMemberFromTeam(c, teamMember, removerUserId); err != nil { return err } } @@ -2256,7 +2257,7 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string, } a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLeftChannel(pluginContext, cm, actorUser) return true @@ -2278,10 +2279,10 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string, return nil } -func (a *App) RemoveUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { var err *model.AppError - if err = a.removeUserFromChannel(userIDToRemove, removerUserId, channel); err != nil { + if err = a.removeUserFromChannel(c, userIDToRemove, removerUserId, channel); err != nil { return err } @@ -2291,12 +2292,12 @@ func (a *App) RemoveUserFromChannel(userIDToRemove string, removerUserId string, } if userIDToRemove == removerUserId { - if err := a.postLeaveChannelMessage(user, channel); err != nil { + if err := a.postLeaveChannelMessage(c, user, channel); err != nil { return err } } else { a.Srv().Go(func() { - a.postRemoveFromChannelMessage(removerUserId, user, channel) + a.postRemoveFromChannelMessage(c, removerUserId, user, channel) }) } @@ -2689,7 +2690,7 @@ func (a *App) RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *mo // MoveChannel method is prone to data races if someone joins to channel during the move process. However this // function is only exposed to sysadmins and the possibility of this edge case is relatively small. -func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *App) MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { // Check that all channel members are in the destination team. channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000) if err != nil { @@ -2777,12 +2778,12 @@ func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model. } } - if err := a.RemoveUsersFromChannelNotMemberOfTeam(user, channel, team); err != nil { + if err := a.RemoveUsersFromChannelNotMemberOfTeam(c, user, channel, team); err != nil { mlog.Warn("error while removing non-team member users", mlog.Err(err)) } if user != nil { - if err := a.postChannelMoveMessage(user, channel, previousTeam); err != nil { + if err := a.postChannelMoveMessage(c, user, channel, previousTeam); err != nil { mlog.Warn("error while posting move channel message", mlog.Err(err)) } } @@ -2790,7 +2791,7 @@ func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model. return nil } -func (a *App) postChannelMoveMessage(user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError { +func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError { post := &model.Post{ ChannelId: channel.Id, @@ -2802,14 +2803,14 @@ func (a *App) postChannelMoveMessage(user *model.User, channel *model.Channel, p }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postChannelMoveMessage", "api.team.move_channel.post.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { +func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000) if err != nil { return err @@ -2838,7 +2839,7 @@ func (a *App) RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel removerId = remover.Id } for userID := range channelMemberMap { - if err := a.removeUserFromChannel(userID, removerId, channel); err != nil { + if err := a.removeUserFromChannel(c, userID, removerId, channel); err != nil { return err } } diff --git a/app/channel_test.go b/app/channel_test.go index a840a6c6e5d..4b7e8d25f56 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -28,7 +28,7 @@ func TestPermanentDeleteChannel(t *testing.T) { *cfg.ServiceSettings.EnableOutgoingWebhooks = true }) - channel, err := th.App.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.NotNil(t, channel, "Channel shouldn't be nil") require.Nil(t, err) defer func() { @@ -81,18 +81,18 @@ func TestRemoveAllDeactivatedMembersFromChannel(t *testing.T) { th.App.PermanentDeleteTeam(team) }() - _, _, err = th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "") require.Nil(t, err) deacivatedUser := th.CreateUser() - _, _, err = th.App.AddUserToTeam(team.Id, deacivatedUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, team.Id, deacivatedUser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(deacivatedUser, channel, false) require.Nil(t, err) channelMembers, err := th.App.GetChannelMembersPage(channel.Id, 0, 10000000) require.Nil(t, err) require.Len(t, *channelMembers, 2) - _, err = th.App.UpdateActive(deacivatedUser, false) + _, err = th.App.UpdateActive(th.Context, deacivatedUser, false) require.Nil(t, err) err = th.App.RemoveAllDeactivatedMembersFromChannel(channel) @@ -118,13 +118,13 @@ func TestMoveChannel(t *testing.T) { th.App.PermanentDeleteTeam(targetTeam) }() - _, _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, th.BasicUser.Id, "") require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, th.BasicUser2.Id, "") require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, targetTeam.Id, th.BasicUser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(th.BasicUser, channel1, false) @@ -133,13 +133,13 @@ func TestMoveChannel(t *testing.T) { _, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false) require.Nil(t, err) - err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser) + err = th.App.MoveChannel(th.Context, targetTeam, channel1, th.BasicUser) require.NotNil(t, err, "Should have failed due to mismatched members.") - _, _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, targetTeam.Id, th.BasicUser2.Id, "") require.Nil(t, err) - err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser) + err = th.App.MoveChannel(th.Context, targetTeam, channel1, th.BasicUser) require.Nil(t, err) // Test moving a channel with a deactivated user who isn't in the destination team. @@ -148,7 +148,7 @@ func TestMoveChannel(t *testing.T) { channel2 := th.CreateChannel(sourceTeam) defer th.App.PermanentDeleteChannel(channel2) - _, _, err = th.App.AddUserToTeam(sourceTeam.Id, deacivatedUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, deacivatedUser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(th.BasicUser, channel2, false) require.Nil(t, err) @@ -156,10 +156,10 @@ func TestMoveChannel(t *testing.T) { _, err = th.App.AddUserToChannel(deacivatedUser, channel2, false) require.Nil(t, err) - _, err = th.App.UpdateActive(deacivatedUser, false) + _, err = th.App.UpdateActive(th.Context, deacivatedUser, false) require.Nil(t, err) - err = th.App.MoveChannel(targetTeam, channel2, th.BasicUser) + err = th.App.MoveChannel(th.Context, targetTeam, channel2, th.BasicUser) require.NotNil(t, err, "Should have failed due to mismatched deacivated member.") // Test moving a channel with no members. @@ -171,11 +171,11 @@ func TestMoveChannel(t *testing.T) { CreatorId: th.BasicUser.Id, } - channel3, err = th.App.CreateChannel(channel3, false) + channel3, err = th.App.CreateChannel(th.Context, channel3, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channel3) - err = th.App.MoveChannel(targetTeam, channel3, th.BasicUser) + err = th.App.MoveChannel(th.Context, targetTeam, channel3, th.BasicUser) assert.Nil(t, err) }) @@ -201,7 +201,7 @@ func TestMoveChannel(t *testing.T) { require.Nil(t, err) require.Equal(t, []string{channel.Id}, category.Channels) - err = th.App.MoveChannel(targetTeam, channel, th.BasicUser) + err = th.App.MoveChannel(th.Context, targetTeam, channel, th.BasicUser) require.Nil(t, err) moved, err := th.App.GetChannel(channel.Id) @@ -234,11 +234,11 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) { th.App.PermanentDeleteTeam(team2) }() - _, _, err := th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "") require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(team2.Id, th.BasicUser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, team2.Id, th.BasicUser.Id, "") require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(team.Id, th.BasicUser2.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser2.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(th.BasicUser, channel1, false) @@ -246,7 +246,7 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) { _, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false) require.Nil(t, err) - err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.SystemAdminUser, channel1, team2) + err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.Context, th.SystemAdminUser, channel1, team2) require.Nil(t, err) channelMembers, err := th.App.GetChannelMembersPage(channel1.Id, 0, 10000000) @@ -273,7 +273,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi // create a new user that joins the default channels user := th.CreateUser() - th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") + th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) @@ -304,7 +304,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing // create a new user that joins the default channels user := th.CreateUser() - th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") + th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) @@ -331,7 +331,7 @@ func TestJoinDefaultChannelsExperimentalDefaultChannels(t *testing.T) { th.App.Config().TeamSettings.ExperimentalDefaultChannels = defaultChannelList user := th.CreateUser() - th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "") + th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") for _, channelName := range defaultChannelList { channel, err := th.App.GetChannelByName(channelName, th.BasicTeam.Id, false) @@ -377,7 +377,7 @@ func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel, err := th.App.CreateChannel(&model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) defer th.App.PermanentDeleteChannel(channel) require.Nil(t, err) require.Equal(t, channel.DisplayName, "Public 1") @@ -390,7 +390,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) privateChannel.Type = model.CHANNEL_OPEN - publicChannel, err := th.App.UpdateChannelPrivacy(privateChannel, th.BasicUser) + publicChannel, err := th.App.UpdateChannelPrivacy(th.Context, privateChannel, th.BasicUser) require.Nil(t, err, "Failed to update channel privacy.") assert.Equal(t, publicChannel.Id, privateChannel.Id) assert.Equal(t, publicChannel.Type, model.CHANNEL_OPEN) @@ -433,7 +433,7 @@ func TestCreateDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { user1 := th.CreateUser() user2 := th.CreateUser() - channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id) + channel, err := th.App.GetOrCreateDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err, "Failed to create direct channel.") histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) @@ -460,7 +460,7 @@ func TestGetDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { user2 := th.CreateUser() // this function call implicitly creates a direct channel between the two users if one doesn't already exist - channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id) + channel, err := th.App.GetOrCreateDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err, "Failed to create direct channel.") // there should be a ChannelMemberHistory record for both users @@ -486,7 +486,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { // create a user and add it to a channel user := th.CreateUser() - _, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id) + _, err := th.App.AddTeamMember(th.Context, th.BasicTeam.Id, user.Id) require.Nil(t, err, "Failed to add user to team.") groupUserIds := make([]string, 0) @@ -523,7 +523,7 @@ func TestLeaveDefaultChannel(t *testing.T) { th.AddUserToChannel(th.BasicUser, townSquare) t.Run("User tries to leave the default channel", func(t *testing.T) { - err = th.App.LeaveChannel(townSquare.Id, th.BasicUser.Id) + err = th.App.LeaveChannel(th.Context, townSquare.Id, th.BasicUser.Id) assert.NotNil(t, err, "It should fail to remove a regular user from the default channel") assert.Equal(t, err.Id, "api.channel.remove.default.app_error") _, err = th.App.GetChannelMember(context.Background(), townSquare.Id, th.BasicUser.Id) @@ -531,7 +531,7 @@ func TestLeaveDefaultChannel(t *testing.T) { }) t.Run("Guest leaves the default channel", func(t *testing.T) { - err = th.App.LeaveChannel(townSquare.Id, guest.Id) + err = th.App.LeaveChannel(th.Context, townSquare.Id, guest.Id) assert.Nil(t, err, "It should allow to remove a guest user from the default channel") _, err = th.App.GetChannelMember(context.Background(), townSquare.Id, guest.Id) assert.NotNil(t, err) @@ -551,14 +551,14 @@ func TestLeaveLastChannel(t *testing.T) { th.AddUserToChannel(guest, th.BasicChannel) t.Run("Guest leaves not last channel", func(t *testing.T) { - err = th.App.LeaveChannel(townSquare.Id, guest.Id) + err = th.App.LeaveChannel(th.Context, townSquare.Id, guest.Id) require.Nil(t, err) _, err = th.App.GetTeamMember(th.BasicTeam.Id, guest.Id) assert.Nil(t, err, "It should maintain the team membership") }) t.Run("Guest leaves last channel", func(t *testing.T) { - err = th.App.LeaveChannel(th.BasicChannel.Id, guest.Id) + err = th.App.LeaveChannel(th.Context, th.BasicChannel.Id, guest.Id) assert.Nil(t, err, "It should allow to remove a guest user from the default channel") _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, guest.Id) assert.NotNil(t, err) @@ -573,7 +573,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { // create a user and add it to a channel user := th.CreateUser() - _, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id) + _, err := th.App.AddTeamMember(th.Context, th.BasicTeam.Id, user.Id) require.Nil(t, err) groupUserIds := make([]string, 0) @@ -582,7 +582,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN) - _, err = th.App.AddChannelMember(user.Id, channel, ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, user.Id, channel, ChannelMemberOpts{}) require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user @@ -679,15 +679,15 @@ func TestFillInChannelProps(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channelPublic1, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPublic1) - channelPublic2, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPublic2) - channelPrivate, err := th.App.CreateChannel(&model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false) + channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelPrivate) @@ -698,11 +698,11 @@ func TestFillInChannelProps(t *testing.T) { Email: "success+" + otherTeamId + "@simulator.amazonses.com", Type: model.TEAM_OPEN, } - otherTeam, err = th.App.CreateTeam(otherTeam) + otherTeam, err = th.App.CreateTeam(th.Context, otherTeam) require.Nil(t, err) defer th.App.PermanentDeleteTeam(otherTeam) - channelOtherTeam, err := th.App.CreateChannel(&model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false) + channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false) require.Nil(t, err) defer th.App.PermanentDeleteChannel(channelOtherTeam) @@ -951,7 +951,7 @@ func TestGetChannelMembersTimezones(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.AddChannelMember(th.BasicUser2.Id, th.BasicChannel, ChannelMemberOpts{}) + _, err := th.App.AddChannelMember(th.Context, th.BasicUser2.Id, th.BasicChannel, ChannelMemberOpts{}) require.Nil(t, err, "Failed to add user to channel.") user := th.BasicUser @@ -964,14 +964,14 @@ func TestGetChannelMembersTimezones(t *testing.T) { th.App.UpdateUser(user2, false) user3 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user3) + ruser, _ := th.App.CreateUser(th.Context, &user3) th.App.AddUserToChannel(ruser, th.BasicChannel, false) ruser.Timezone["automaticTimezone"] = "NoWhere/Island" th.App.UpdateUser(ruser, false) user4 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ = th.App.CreateUser(&user4) + ruser, _ = th.App.CreateUser(th.Context, &user4) th.App.AddUserToChannel(ruser, th.BasicChannel, false) timezones, err := th.App.GetChannelMembersTimezones(th.BasicChannel.Id) @@ -989,7 +989,7 @@ func TestGetChannelsForUser(t *testing.T) { CreatorId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, } - th.App.CreateChannel(channel, true) + th.App.CreateChannel(th.Context, channel, true) defer th.App.PermanentDeleteChannel(channel) defer th.TearDown() @@ -997,7 +997,7 @@ func TestGetChannelsForUser(t *testing.T) { require.Nil(t, err) require.Len(t, *channelList, 4) - th.App.DeleteChannel(channel, th.BasicUser.Id) + th.App.DeleteChannel(th.Context, channel, th.BasicUser.Id) // Now we get all the non-archived channels for the user channelList, err = th.App.GetChannelsForUser(th.BasicTeam.Id, th.BasicUser.Id, false, 0) @@ -1035,7 +1035,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) { TeamId: team.Id, } var rchannel *model.Channel - rchannel, err = th.App.CreateChannel(&channel, false) + rchannel, err = th.App.CreateChannel(th.Context, &channel, false) require.Nil(t, err) require.NotNil(t, rchannel) defer th.App.PermanentDeleteChannel(rchannel) @@ -1068,7 +1068,7 @@ func TestGetPrivateChannelsForTeam(t *testing.T) { TeamId: team.Id, } var rchannel *model.Channel - rchannel, err := th.App.CreateChannel(&channel, false) + rchannel, err := th.App.CreateChannel(th.Context, &channel, false) require.Nil(t, err) require.NotNil(t, rchannel) defer th.App.PermanentDeleteChannel(rchannel) @@ -1093,9 +1093,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { t.Run("from guest to user", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) @@ -1107,9 +1107,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { t.Run("from user to guest", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) @@ -1121,9 +1121,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { t.Run("from user to admin", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) @@ -1135,9 +1135,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { t.Run("from guest to guest plus custom", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) @@ -1152,9 +1152,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { t.Run("a guest cant have user role", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) @@ -1186,13 +1186,13 @@ func TestSearchChannelsForUser(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - c1, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - c2, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - c3, err := th.App.CreateChannel(&model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) defer func() { @@ -1332,7 +1332,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { _, err := th.App.AddUserToChannel(u2, c2, false) require.Nil(t, err) - p4, err := th.App.CreatePost(&model.Post{ + p4, err := th.App.CreatePost(th.Context, &model.Post{ UserId: u2.Id, ChannelId: c2.Id, Message: "@" + u1.Username, @@ -1340,7 +1340,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { require.Nil(t, err) th.CreatePost(c2) - th.App.CreatePost(&model.Post{ + th.App.CreatePost(th.Context, &model.Post{ UserId: u2.Id, ChannelId: c2.Id, RootId: p4.Id, @@ -1367,7 +1367,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { th.CreatePost(dc) th.CreatePost(dc) - _, err := th.App.CreatePost(&model.Post{ChannelId: dc.Id, UserId: th.BasicUser.Id, Message: "testReply", RootId: dm1.Id}, dc, false, false) + _, err := th.App.CreatePost(th.Context, &model.Post{ChannelId: dc.Id, UserId: th.BasicUser.Id, Message: "testReply", RootId: dm1.Id}, dc, false, false) assert.Nil(t, err) response, err := th.App.MarkChannelAsUnreadFromPost(dm1.Id, u2.Id) @@ -1395,14 +1395,14 @@ func TestAddUserToChannel(t *testing.T) { defer th.TearDown() user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser1, _ := th.App.CreateUser(&user1) - defer th.App.PermanentDeleteUser(&user1) + ruser1, _ := th.App.CreateUser(th.Context, &user1) + defer th.App.PermanentDeleteUser(th.Context, &user1) bot := th.CreateBot() botUser, _ := th.App.GetUser(bot.UserId) defer th.App.PermanentDeleteBot(botUser.Id) - th.App.AddTeamMember(th.BasicTeam.Id, ruser1.Id) - th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId) + th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser1.Id) + th.App.AddTeamMember(th.Context, th.BasicTeam.Id, bot.UserId) group := th.CreateGroup() @@ -1418,7 +1418,7 @@ func TestAddUserToChannel(t *testing.T) { }) require.Nil(t, err) - err = th.App.JoinChannel(th.BasicChannel, ruser1.Id) + err = th.App.JoinChannel(th.Context, th.BasicChannel, ruser1.Id) require.Nil(t, err) // verify user was added as a non-admin @@ -1427,9 +1427,9 @@ func TestAddUserToChannel(t *testing.T) { require.False(t, cm1.SchemeAdmin) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser2, _ := th.App.CreateUser(&user2) - defer th.App.PermanentDeleteUser(&user2) - th.App.AddTeamMember(th.BasicTeam.Id, ruser2.Id) + ruser2, _ := th.App.CreateUser(th.Context, &user2) + defer th.App.PermanentDeleteUser(th.Context, &user2) + th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser2.Id) _, err = th.App.UpsertGroupMember(group.Id, user2.Id) require.Nil(t, err) @@ -1438,7 +1438,7 @@ func TestAddUserToChannel(t *testing.T) { _, err = th.App.UpdateGroupSyncable(gs) require.Nil(t, err) - err = th.App.JoinChannel(th.BasicChannel, ruser2.Id) + err = th.App.JoinChannel(th.Context, th.BasicChannel, ruser2.Id) require.Nil(t, err) // Should allow a bot to be added to a public group synced channel @@ -1476,15 +1476,15 @@ func TestRemoveUserFromChannel(t *testing.T) { defer th.TearDown() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(ruser) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, ruser) bot := th.CreateBot() botUser, _ := th.App.GetUser(bot.UserId) defer th.App.PermanentDeleteBot(botUser.Id) - th.App.AddTeamMember(th.BasicTeam.Id, ruser.Id) - th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId) + th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser.Id) + th.App.AddTeamMember(th.Context, th.BasicTeam.Id, bot.UserId) privateChannel := th.CreatePrivateChannel(th.BasicTeam) @@ -1509,15 +1509,15 @@ func TestRemoveUserFromChannel(t *testing.T) { require.Nil(t, err) // Should not allow a group synced user to be removed from channel - err = th.App.RemoveUserFromChannel(ruser.Id, th.SystemAdminUser.Id, privateChannel) + err = th.App.RemoveUserFromChannel(th.Context, ruser.Id, th.SystemAdminUser.Id, privateChannel) assert.Equal(t, err.Id, "api.channel.remove_members.denied") // Should allow a user to remove themselves from group synced channel - err = th.App.RemoveUserFromChannel(ruser.Id, ruser.Id, privateChannel) + err = th.App.RemoveUserFromChannel(th.Context, ruser.Id, ruser.Id, privateChannel) require.Nil(t, err) // Should allow a bot to be removed from a group synced channel - err = th.App.RemoveUserFromChannel(botUser.Id, th.SystemAdminUser.Id, privateChannel) + err = th.App.RemoveUserFromChannel(th.Context, botUser.Id, th.SystemAdminUser.Id, privateChannel) require.Nil(t, err) } @@ -1969,7 +1969,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) { mockStore.On("User").Return(&mockUserStore) mockStore.On("Channel").Return(&mockChannelStore) - _, err := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.App.Session().Id) + _, err := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.Context.Session().Id) require.Nil(t, err) } diff --git a/app/cloud.go b/app/cloud.go index 2c70d3b63ed..fca316b5f77 100644 --- a/app/cloud.go +++ b/app/cloud.go @@ -8,6 +8,7 @@ import ( "net/http" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) @@ -78,13 +79,13 @@ func (a *App) SendAdminUpgradeRequestEmail(username string, subscription *model. return nil } -func (a *App) CheckAndSendUserLimitWarningEmails() *model.AppError { +func (a *App) CheckAndSendUserLimitWarningEmails(c *request.Context) *model.AppError { if a.Srv().License() == nil || (a.Srv().License() != nil && !*a.Srv().License().Features.Cloud) { // Not cloud instance, do nothing return nil } - subscription, err := a.Cloud().GetSubscription(a.Session().UserId) + subscription, err := a.Cloud().GetSubscription(c.Session().UserId) if err != nil { return model.NewAppError( "app.CheckAndSendUserLimitWarningEmails", diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index a6ac6067e86..81a35954bb4 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -7,36 +7,20 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) -// registerAppClusterMessageHandlers registers the cluster message handlers that are handled by the App layer. -// -// The cluster event handlers are spread across this function, Server.registerClusterHandlers and -// NewLocalCacheLayer. Be careful to not have duplicated handlers here and -// there. -func (a *App) registerAppClusterMessageHandlers() { - 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_PLUGIN_EVENT, a.clusterPluginEventHandler) +func (s *Server) clusterInstallPluginHandler(msg *model.ClusterMessage) { + s.installPluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data))) } -func (a *App) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) { - a.ClearSessionCacheForUserSkipClusterSend(msg.Data) +func (s *Server) clusterRemovePluginHandler(msg *model.ClusterMessage) { + s.removePluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data))) } -func (a *App) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) { - a.ClearSessionCacheForAllUsersSkipClusterSend() -} - -func (a *App) clusterInstallPluginHandler(msg *model.ClusterMessage) { - a.InstallPluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data))) -} - -func (a *App) clusterPluginEventHandler(msg *model.ClusterMessage) { - env := a.GetPluginsEnvironment() +func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) { + env := s.GetPluginsEnvironment() if env == nil { return } @@ -58,17 +42,16 @@ func (a *App) clusterPluginEventHandler(msg *model.ClusterMessage) { return } - hooks.OnPluginClusterEvent(a.PluginContext(), model.PluginClusterEvent{ + hooks.OnPluginClusterEvent(&plugin.Context{}, model.PluginClusterEvent{ Id: eventID, Data: []byte(msg.Data), }) } -func (a *App) clusterRemovePluginHandler(msg *model.ClusterMessage) { - a.RemovePluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data))) -} - // registerClusterHandlers registers the cluster message handlers that are handled by the server. +// +// The cluster event handlers are spread across this function and NewLocalCacheLayer. +// Be careful to not have duplicated handlers here and there. func (s *Server) registerClusterHandlers() { s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, s.clusterPublishHandler) s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, s.clusterUpdateStatusHandler) @@ -78,6 +61,11 @@ func (s *Server) registerClusterHandlers() { s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, s.clusterInvalidateCacheForUserHandler) s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, s.clusterInvalidateCacheForUserTeamsHandler) s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, s.clusterBusyStateChgHandler) + s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, s.clusterClearSessionCacheForUserHandler) + s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, s.clusterClearSessionCacheForAllUsersHandler) + s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, s.clusterInstallPluginHandler) + s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, s.clusterRemovePluginHandler) + s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PLUGIN_EVENT, s.clusterPluginEventHandler) } func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) { @@ -136,6 +124,14 @@ func (s *Server) clearSessionCacheForAllUsersSkipClusterSend() { s.sessionCache.Purge() } +func (s *Server) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) { + s.clearSessionCacheForUserSkipClusterSend(msg.Data) +} + +func (s *Server) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) { + s.clearSessionCacheForAllUsersSkipClusterSend() +} + func (s *Server) clusterBusyStateChgHandler(msg *model.ClusterMessage) { s.serverBusyStateChanged(model.ServerBusyStateFromJson(strings.NewReader(msg.Data))) } diff --git a/app/command.go b/app/command.go index 590b11b8ec2..2ead77253b4 100644 --- a/app/command.go +++ b/app/command.go @@ -14,6 +14,7 @@ import ( "sync" "unicode" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -27,7 +28,7 @@ const ( type CommandProvider interface { GetTrigger() string GetCommand(a *App, T i18n.TranslateFunc) *model.Command - DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse + DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse } var commandProviders = make(map[string]CommandProvider) @@ -46,7 +47,7 @@ func GetCommandProvider(name string) CommandProvider { } // @openTracingParams teamID, skipSlackParsing -func (a *App) CreateCommandPost(post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) { +func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) { if skipSlackParsing { post.Message = response.Text } else { @@ -65,7 +66,7 @@ func (a *App) CreateCommandPost(post *model.Post, teamID string, response *model } if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL { - return a.CreatePostMissingChannel(post, true) + return a.CreatePostMissingChannel(c, post, true) } if (response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL) && (response.Text != "" || response.Attachments != nil) { @@ -175,7 +176,7 @@ func (a *App) ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Com } // @openTracingParams args -func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { +func (a *App) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { trigger := "" message := "" index := strings.IndexFunc(args.Command, unicode.IsSpace) @@ -199,12 +200,12 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, * args.TriggerId = triggerId // Plugins can override built in and custom commands - cmd, response, appErr := a.tryExecutePluginCommand(args) + cmd, response, appErr := a.tryExecutePluginCommand(c, args) if appErr != nil { return nil, appErr } else if cmd != nil && response != nil { response.TriggerId = clientTriggerId - return a.HandleCommandResponse(cmd, args, response, true) + return a.HandleCommandResponse(c, cmd, args, response, true) } // Custom commands can override built ins @@ -213,12 +214,12 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, * return nil, appErr } else if cmd != nil && response != nil { response.TriggerId = clientTriggerId - return a.HandleCommandResponse(cmd, args, response, false) + return a.HandleCommandResponse(c, cmd, args, response, false) } - cmd, response = a.tryExecuteBuiltInCommand(args, trigger, message) + cmd, response = a.tryExecuteBuiltInCommand(c, args, trigger, message) if cmd != nil && response != nil { - return a.HandleCommandResponse(cmd, args, response, true) + return a.HandleCommandResponse(c, cmd, args, response, true) } return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound) @@ -338,7 +339,7 @@ func (a *App) MentionsToPublicChannels(message, teamID string) model.ChannelMent // tryExecuteBuiltInCommand attempts to run a built in command based on the given arguments. If no such command can be // found, returns nil for all arguments. -func (a *App) tryExecuteBuiltInCommand(args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse) { +func (a *App) tryExecuteBuiltInCommand(c *request.Context, args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse) { provider := GetCommandProvider(trigger) if provider == nil { return nil, nil @@ -349,7 +350,7 @@ func (a *App) tryExecuteBuiltInCommand(args *model.CommandArgs, trigger string, return nil, nil } - return cmd, provider.DoCommand(a, args, message) + return cmd, provider.DoCommand(a, c, args, message) } // tryExecuteCustomCommand attempts to run a custom command based on the given arguments. If no such command can be @@ -527,7 +528,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command return cmd, response, nil } -func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { +func (a *App) HandleCommandResponse(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { trigger := "" if args.Command != "" { parts := strings.Split(args.Command, " ") @@ -536,7 +537,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA } var lastError *model.AppError - _, err := a.HandleCommandResponsePost(command, args, response, builtIn) + _, err := a.HandleCommandResponsePost(c, command, args, response, builtIn) if err != nil { mlog.Debug("Error occurred in handling command response post", mlog.Err(err)) @@ -545,7 +546,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA if response.ExtraResponses != nil { for _, resp := range response.ExtraResponses { - _, err := a.HandleCommandResponsePost(command, args, resp, builtIn) + _, err := a.HandleCommandResponsePost(c, command, args, resp, builtIn) if err != nil { mlog.Debug("Error occurred in handling command response post", mlog.Err(err)) @@ -561,7 +562,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA return response, nil } -func (a *App) HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) { +func (a *App) HandleCommandResponsePost(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) { post := &model.Post{} post.ChannelId = args.ChannelId post.RootId = args.RootId @@ -613,7 +614,7 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm response.Attachments = a.ProcessSlackAttachments(response.Attachments) } - if _, err := a.CreateCommandPost(post, args.TeamId, response, response.SkipSlackParsing); err != nil { + if _, err := a.CreateCommandPost(c, post, args.TeamId, response, response.SkipSlackParsing); err != nil { return post, err } diff --git a/app/command_autocomplete.go b/app/command_autocomplete.go index 1ccf440dcb9..a5e28e6a4aa 100644 --- a/app/command_autocomplete.go +++ b/app/command_autocomplete.go @@ -10,6 +10,7 @@ import ( "sort" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) @@ -20,7 +21,7 @@ type AutocompleteDynamicArgProvider interface { } // GetSuggestions returns suggestions for user input. -func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion { +func (a *App) GetSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion { sort.Slice(commands, func(i, j int) bool { return strings.Compare(strings.ToLower(commands[i].Trigger), strings.ToLower(commands[j].Trigger)) < 0 }) @@ -34,7 +35,7 @@ func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.C } userInput := commandArgs.Command - suggestions := a.getSuggestions(commandArgs, autocompleteData, "", userInput, roleID) + suggestions := a.getSuggestions(c, commandArgs, autocompleteData, "", userInput, roleID) for i, suggestion := range suggestions { for _, command := range commands { if strings.HasPrefix(suggestion.Complete, command.Trigger) { @@ -47,7 +48,7 @@ func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.C return suggestions } -func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.AutocompleteData, inputParsed, inputToBeParsed, roleID string) []model.AutocompleteSuggestion { +func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.AutocompleteData, inputParsed, inputToBeParsed, roleID string) []model.AutocompleteSuggestion { suggestions := []model.AutocompleteSuggestion{} index := strings.Index(inputToBeParsed, " ") @@ -78,12 +79,12 @@ func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.A if len(command.Arguments) == 0 { // Seek recursively in subcommands - subSuggestions := a.getSuggestions(commandArgs, command.SubCommands, parsed, toBeParsed, roleID) + subSuggestions := a.getSuggestions(c, commandArgs, command.SubCommands, parsed, toBeParsed, roleID) suggestions = append(suggestions, subSuggestions...) continue } - found, _, _, suggestion := a.parseArguments(commandArgs, command.Arguments, parsed, toBeParsed) + found, _, _, suggestion := a.parseArguments(c, commandArgs, command.Arguments, parsed, toBeParsed) if found { suggestions = append(suggestions, suggestion...) } @@ -92,27 +93,27 @@ func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.A return suggestions } -func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { +func (a *App) parseArguments(c *request.Context, commandArgs *model.CommandArgs, args []*model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { if len(args) == 0 { return false, parsed, toBeParsed, suggestions } if args[0].Required { - found, changedParsed, changedToBeParsed, suggestion := a.parseArgument(commandArgs, args[0], parsed, toBeParsed) + found, changedParsed, changedToBeParsed, suggestion := a.parseArgument(c, commandArgs, args[0], parsed, toBeParsed) if found { suggestions = append(suggestions, suggestion...) return true, changedParsed, changedToBeParsed, suggestions } - return a.parseArguments(commandArgs, args[1:], changedParsed, changedToBeParsed) + return a.parseArguments(c, commandArgs, args[1:], changedParsed, changedToBeParsed) } // Handling optional arguments. Optional argument can be inputted or not, // so we have to pase both cases recursively and output combined suggestions. - foundWithOptional, changedParsedWithOptional, changedToBeParsedWithOptional, suggestionsWithOptional := a.parseArgument(commandArgs, args[0], parsed, toBeParsed) + foundWithOptional, changedParsedWithOptional, changedToBeParsedWithOptional, suggestionsWithOptional := a.parseArgument(c, commandArgs, args[0], parsed, toBeParsed) if foundWithOptional { suggestions = append(suggestions, suggestionsWithOptional...) } else { - foundWithOptionalRest, changedParsedWithOptionalRest, changedToBeParsedWithOptionalRest, suggestionsWithOptionalRest := a.parseArguments(commandArgs, args[1:], changedParsedWithOptional, changedToBeParsedWithOptional) + foundWithOptionalRest, changedParsedWithOptionalRest, changedToBeParsedWithOptionalRest, suggestionsWithOptionalRest := a.parseArguments(c, commandArgs, args[1:], changedParsedWithOptional, changedToBeParsedWithOptional) if foundWithOptionalRest { suggestions = append(suggestions, suggestionsWithOptionalRest...) } @@ -121,7 +122,7 @@ func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.Autoc changedToBeParsedWithOptional = changedToBeParsedWithOptionalRest } - foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestionsWithoutOptional := a.parseArguments(commandArgs, args[1:], parsed, toBeParsed) + foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestionsWithoutOptional := a.parseArguments(c, commandArgs, args[1:], parsed, toBeParsed) if foundWithoutOptional { suggestions = append(suggestions, suggestionsWithoutOptional...) } @@ -140,7 +141,7 @@ func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.Autoc return foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestions } -func (a *App) parseArgument(commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { +func (a *App) parseArgument(c *request.Context, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { if arg.Name != "" { //Parse the --name first found, changedParsed, changedToBeParsed, suggestion := parseNamedArgument(arg, parsed, toBeParsed) if found { @@ -174,7 +175,7 @@ func (a *App) parseArgument(commandArgs *model.CommandArgs, arg *model.Autocompl parsed = changedParsed toBeParsed = changedToBeParsed } else if arg.Type == model.AutocompleteArgTypeDynamicList { - found, changedParsed, changedToBeParsed, dynamicListSuggestions := a.getDynamicListArgument(commandArgs, arg, parsed, toBeParsed) + found, changedParsed, changedToBeParsed, dynamicListSuggestions := a.getDynamicListArgument(c, commandArgs, arg, parsed, toBeParsed) if found { suggestions = append(suggestions, dynamicListSuggestions...) return true, changedParsed, changedToBeParsed, suggestions @@ -237,7 +238,7 @@ func parseStaticListArgument(arg *model.AutocompleteArg, parsed, toBeParsed stri return parseListItems(a.PossibleArguments, parsed, toBeParsed) } -func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { +func (a *App) getDynamicListArgument(c *request.Context, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) { dynamicArg := arg.Data.(*model.AutocompleteDynamicListArg) if strings.HasPrefix(dynamicArg.FetchURL, "builtin:") { @@ -255,7 +256,7 @@ func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model. // Encode the information normally provided to a plugin slash command handler into the request parameters // Encode PluginContext: - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) params.Add("request_id", pluginContext.RequestId) params.Add("session_id", pluginContext.SessionId) params.Add("ip_address", pluginContext.IpAddress) @@ -270,7 +271,7 @@ func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model. params.Add("user_id", commandArgs.UserId) params.Add("site_url", commandArgs.SiteURL) - resp, err := a.doPluginRequest("GET", dynamicArg.FetchURL, params, nil) + resp, err := a.doPluginRequest(c, "GET", dynamicArg.FetchURL, params, nil) if err != nil { a.Log().Error("Can't fetch dynamic list arguments for", mlog.String("url", dynamicArg.FetchURL), mlog.Err(err)) diff --git a/app/command_autocomplete_test.go b/app/command_autocomplete_test.go index d099374f610..49b379064e9 100644 --- a/app/command_autocomplete_test.go +++ b/app/command_autocomplete_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/assert" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -207,21 +208,21 @@ func TestSuggestions(t *testing.T) { jira := createJiraAutocompleteData() emptyCmdArgs := &model.CommandArgs{} - suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, jira.Trigger, suggestions[0].Complete) assert.Equal(t, jira.Trigger, suggestions[0].Suggestion) assert.Equal(t, "[command]", suggestions[0].Hint) assert.Equal(t, jira.HelpText, suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create", suggestions[0].Complete) assert.Equal(t, "create", suggestions[0].Suggestion) assert.Equal(t, "[issue text]", suggestions[0].Hint) assert.Equal(t, "Create a new Issue", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "jira create", suggestions[1].Complete) assert.Equal(t, "create", suggestions[1].Suggestion) @@ -232,27 +233,27 @@ func TestSuggestions(t *testing.T) { assert.Equal(t, "[url]", suggestions[0].Hint) assert.Equal(t, "Connect your Mattermost account to your Jira account", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create some", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "jira settings notifications On", suggestions[0].Complete) assert.Equal(t, "On", suggestions[0].Suggestion) @@ -263,48 +264,48 @@ func TestSuggestions(t *testing.T) { assert.Equal(t, "Turn notifications off", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 11) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID) assert.Len(t, suggestions, 9) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira create \"some issue text", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[text]", suggestions[0].Hint) assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "--zone", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "--zone", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "jira timezone --zone bla", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint) assert.Equal(t, "Set timezone", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 0) commandA := &model.Command{ @@ -319,7 +320,7 @@ func TestSuggestions(t *testing.T) { Trigger: "charles", AutocompleteData: model.NewAutocompleteData("charles", "", ""), } - suggestions = th.App.GetSuggestions(emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "alice", suggestions[0].Complete) assert.Equal(t, "bob", suggestions[1].Complete) @@ -333,14 +334,14 @@ func TestCommandWithOptionalArgs(t *testing.T) { command := createCommandWithOptionalArgs() emptyCmdArgs := &model.CommandArgs{} - suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, command.Trigger, suggestions[0].Complete) assert.Equal(t, command.Trigger, suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, command.HelpText, suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 4) assert.Equal(t, "command subcommand1", suggestions[0].Complete) assert.Equal(t, "subcommand1", suggestions[0].Suggestion) @@ -355,7 +356,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "", suggestions[2].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -366,21 +367,21 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand1 item1 --name2 ", suggestions[0].Complete) assert.Equal(t, "--name2", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand1 item1 --name2 bla", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -391,7 +392,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "arg2", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -402,7 +403,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "arg2", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -417,7 +418,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -432,24 +433,24 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand2 --name1 item1 ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg2", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand2 --name1 item1 bla ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) assert.Equal(t, "", suggestions[0].Hint) assert.Equal(t, "arg3", suggestions[0].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 0) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -464,7 +465,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete) assert.Equal(t, "--name1", suggestions[0].Suggestion) @@ -479,7 +480,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[2].Hint) assert.Equal(t, "arg3", suggestions[2].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand3 --name1 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -490,7 +491,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "", suggestions[1].Hint) assert.Equal(t, "", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 2) assert.Equal(t, "command subcommand4 item1", suggestions[0].Complete) assert.Equal(t, "item1", suggestions[0].Suggestion) @@ -501,7 +502,7 @@ func TestCommandWithOptionalArgs(t *testing.T) { assert.Equal(t, "message", suggestions[1].Hint) assert.Equal(t, "help4", suggestions[1].Description) - suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 1) assert.Equal(t, "command subcommand4 item1 ", suggestions[0].Complete) assert.Equal(t, "", suggestions[0].Suggestion) @@ -624,7 +625,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) { emptyCmdArgs := &model.CommandArgs{} t.Run("GetAutoCompleteListItems", func(t *testing.T) { - suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID) assert.Len(t, suggestions, 3) assert.Equal(t, "this is hint 1", suggestions[0].Hint) assert.Equal(t, "this is hint 2", suggestions[1].Hint) @@ -632,7 +633,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) { }) t.Run("GetAutoCompleteListItems bad arg", func(t *testing.T) { - suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID) + suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID) assert.Empty(t, suggestions) }) } @@ -658,7 +659,7 @@ func (p *testCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model.Co } } -func (p *testCommandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { +func (p *testCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return &model.CommandResponse{ Text: "I do nothing!", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, diff --git a/app/context.go b/app/context.go index 7713c512660..c3448d355df 100644 --- a/app/context.go +++ b/app/context.go @@ -6,6 +6,8 @@ package app import ( "context" + "github.com/mattermost/mattermost-server/v5/app/request" + "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/store/sqlstore" ) @@ -13,3 +15,14 @@ import ( func WithMaster(ctx context.Context) context.Context { return sqlstore.WithMaster(ctx) } + +func pluginContext(c *request.Context) *plugin.Context { + context := &plugin.Context{ + RequestId: c.RequestId(), + SessionId: c.Session().Id, + IpAddress: c.IpAddress(), + AcceptLanguage: c.AcceptLanguage(), + UserAgent: c.UserAgent(), + } + return context +} diff --git a/app/download.go b/app/download.go index cdfc9b8a984..7dcb556e81f 100644 --- a/app/download.go +++ b/app/download.go @@ -23,6 +23,10 @@ const ( ) func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { + return a.Srv().downloadFromURL(downloadURL) +} + +func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { if !model.IsValidHttpUrl(downloadURL) { return nil, errors.Errorf("invalid url %s", downloadURL) } @@ -31,11 +35,11 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { if err != nil { return nil, errors.Errorf("failed to parse url %s", downloadURL) } - if !*a.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" { + if !*s.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" { return nil, errors.Errorf("insecure url not allowed %s", downloadURL) } - client := a.HTTPService().MakeClient(true) + client := s.HTTPService.MakeClient(true) client.Timeout = HTTPRequestTimeout var resp *http.Response diff --git a/app/enterprise.go b/app/enterprise.go index ba4fea08afe..a98d0737d97 100644 --- a/app/enterprise.go +++ b/app/enterprise.go @@ -12,9 +12,9 @@ import ( "github.com/mattermost/mattermost-server/v5/shared/mlog" ) -var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface +var accountMigrationInterface func(*Server) einterfaces.AccountMigrationInterface -func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigrationInterface) { +func RegisterAccountMigrationInterface(f func(*Server) einterfaces.AccountMigrationInterface) { accountMigrationInterface = f } @@ -66,9 +66,9 @@ func RegisterJobsElasticsearchIndexerInterface(f func(*Server) tjobs.IndexerJobI jobsElasticsearchIndexerInterface = f } -var jobsLdapSyncInterface func(*App) ejobs.LdapSyncInterface +var jobsLdapSyncInterface func(*Server) ejobs.LdapSyncInterface -func RegisterJobsLdapSyncInterface(f func(*App) ejobs.LdapSyncInterface) { +func RegisterJobsLdapSyncInterface(f func(*Server) ejobs.LdapSyncInterface) { jobsLdapSyncInterface = f } @@ -78,9 +78,9 @@ func RegisterJobsMigrationsJobInterface(f func(*Server) tjobs.MigrationsJobInter jobsMigrationsInterface = f } -var jobsPluginsInterface func(*App) tjobs.PluginsJobInterface +var jobsPluginsInterface func(*Server) tjobs.PluginsJobInterface -func RegisterJobsPluginsJobInterface(f func(*App) tjobs.PluginsJobInterface) { +func RegisterJobsPluginsJobInterface(f func(*Server) tjobs.PluginsJobInterface) { jobsPluginsInterface = f } @@ -90,16 +90,16 @@ func RegisterJobsBleveIndexerInterface(f func(*Server) tjobs.IndexerJobInterface jobsBleveIndexerInterface = f } -var jobsActiveUsersInterface func(*App) tjobs.ActiveUsersJobInterface +var jobsActiveUsersInterface func(*Server) tjobs.ActiveUsersJobInterface -func RegisterJobsActiveUsersInterface(f func(*App) tjobs.ActiveUsersJobInterface) { +func RegisterJobsActiveUsersInterface(f func(*Server) tjobs.ActiveUsersJobInterface) { jobsActiveUsersInterface = f } -var jobsResendInvitationEmailInterface func(*App) ejobs.ResendInvitationEmailJobInterface +var jobsResendInvitationEmailInterface func(*Server) ejobs.ResendInvitationEmailJobInterface // RegisterJobsResendInvitationEmailInterface is used to register or initialize the jobsResendInvitationEmailInterface -func RegisterJobsResendInvitationEmailInterface(f func(*App) ejobs.ResendInvitationEmailJobInterface) { +func RegisterJobsResendInvitationEmailInterface(f func(*Server) ejobs.ResendInvitationEmailJobInterface) { jobsResendInvitationEmailInterface = f } @@ -109,45 +109,45 @@ func RegisterJobsCloudInterface(f func(*Server) ejobs.CloudJobInterface) { jobsCloudInterface = f } -var jobsExpiryNotifyInterface func(*App) tjobs.ExpiryNotifyJobInterface +var jobsExpiryNotifyInterface func(*Server) tjobs.ExpiryNotifyJobInterface -func RegisterJobsExpiryNotifyJobInterface(f func(*App) tjobs.ExpiryNotifyJobInterface) { +func RegisterJobsExpiryNotifyJobInterface(f func(*Server) tjobs.ExpiryNotifyJobInterface) { jobsExpiryNotifyInterface = f } -var jobsImportProcessInterface func(*App) tjobs.ImportProcessInterface +var jobsImportProcessInterface func(*Server) tjobs.ImportProcessInterface -func RegisterJobsImportProcessInterface(f func(*App) tjobs.ImportProcessInterface) { +func RegisterJobsImportProcessInterface(f func(*Server) tjobs.ImportProcessInterface) { jobsImportProcessInterface = f } -var jobsImportDeleteInterface func(*App) tjobs.ImportDeleteInterface +var jobsImportDeleteInterface func(*Server) tjobs.ImportDeleteInterface -func RegisterJobsImportDeleteInterface(f func(*App) tjobs.ImportDeleteInterface) { +func RegisterJobsImportDeleteInterface(f func(*Server) tjobs.ImportDeleteInterface) { jobsImportDeleteInterface = f } -var jobsExportProcessInterface func(*App) tjobs.ExportProcessInterface +var jobsExportProcessInterface func(*Server) tjobs.ExportProcessInterface -func RegisterJobsExportProcessInterface(f func(*App) tjobs.ExportProcessInterface) { +func RegisterJobsExportProcessInterface(f func(*Server) tjobs.ExportProcessInterface) { jobsExportProcessInterface = f } -var jobsExportDeleteInterface func(*App) tjobs.ExportDeleteInterface +var jobsExportDeleteInterface func(*Server) tjobs.ExportDeleteInterface -func RegisterJobsExportDeleteInterface(f func(*App) tjobs.ExportDeleteInterface) { +func RegisterJobsExportDeleteInterface(f func(*Server) tjobs.ExportDeleteInterface) { jobsExportDeleteInterface = f } -var productNoticesJobInterface func(*App) tjobs.ProductNoticesJobInterface +var productNoticesJobInterface func(*Server) tjobs.ProductNoticesJobInterface -func RegisterProductNoticesJobInterface(f func(*App) tjobs.ProductNoticesJobInterface) { +func RegisterProductNoticesJobInterface(f func(*Server) tjobs.ProductNoticesJobInterface) { productNoticesJobInterface = f } -var ldapInterface func(*App) einterfaces.LdapInterface +var ldapInterface func(*Server) einterfaces.LdapInterface -func RegisterLdapInterface(f func(*App) einterfaces.LdapInterface) { +func RegisterLdapInterface(f func(*Server) einterfaces.LdapInterface) { ldapInterface = f } @@ -169,15 +169,15 @@ func RegisterMetricsInterface(f func(*Server) einterfaces.MetricsInterface) { metricsInterface = f } -var samlInterfaceNew func(*App) einterfaces.SamlInterface +var samlInterfaceNew func(*Server) einterfaces.SamlInterface -func RegisterNewSamlInterface(f func(*App) einterfaces.SamlInterface) { +func RegisterNewSamlInterface(f func(*Server) einterfaces.SamlInterface) { samlInterfaceNew = f } -var notificationInterface func(*App) einterfaces.NotificationInterface +var notificationInterface func(*Server) einterfaces.NotificationInterface -func RegisterNotificationInterface(f func(*App) einterfaces.NotificationInterface) { +func RegisterNotificationInterface(f func(*Server) einterfaces.NotificationInterface) { notificationInterface = f } @@ -200,26 +200,23 @@ func (s *Server) initEnterprise() { if elasticsearchInterface != nil { s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s)) } -} - -func (a *App) initEnterprise() { if accountMigrationInterface != nil { - a.srv.AccountMigration = accountMigrationInterface(a) + s.AccountMigration = accountMigrationInterface(s) } if ldapInterface != nil { - a.srv.Ldap = ldapInterface(a) + s.Ldap = ldapInterface(s) } if notificationInterface != nil { - a.srv.Notification = notificationInterface(a) + s.Notification = notificationInterface(s) } if samlInterfaceNew != nil { mlog.Debug("Loading SAML2 library") - a.srv.Saml = samlInterfaceNew(a) - if err := a.srv.Saml.ConfigureSP(); err != nil { + s.Saml = samlInterfaceNew(s) + if err := s.Saml.ConfigureSP(); err != nil { mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } - a.AddConfigListener(func(_, cfg *model.Config) { - if err := a.srv.Saml.ConfigureSP(); err != nil { + s.AddConfigListener(func(_, cfg *model.Config) { + if err := s.Saml.ConfigureSP(); err != nil { mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } }) diff --git a/app/enterprise_test.go b/app/enterprise_test.go index 7b46552a7ba..a7ec1b5fdd2 100644 --- a/app/enterprise_test.go +++ b/app/enterprise_test.go @@ -57,7 +57,7 @@ func TestSAMLSettings(t *testing.T) { saml2.Mock.On("ConfigureSP").Return(nil) saml2.Mock.On("GetMetadata").Return("samlTwo", nil) if tc.setNewInterface { - RegisterNewSamlInterface(func(a *App) einterfaces.SamlInterface { + RegisterNewSamlInterface(func(s *Server) einterfaces.SamlInterface { return saml2 }) } else { @@ -65,6 +65,7 @@ func TestSAMLSettings(t *testing.T) { } th := SetupEnterpriseWithStoreMock(t) + defer th.TearDown() mockStore := th.App.Srv().Store.(*storemocks.Store) @@ -87,8 +88,6 @@ func TestSAMLSettings(t *testing.T) { }) } - th.Server.initEnterprise() - th.App.initEnterprise() if tc.isNil { assert.Nil(t, th.App.Srv().Saml) } else { diff --git a/app/export_test.go b/app/export_test.go index 9eda9d238ca..1cf3dec3796 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -39,8 +39,8 @@ func TestReactionsOfPost(t *testing.T) { CreateAt: model.GetMillis(), } - th.App.SaveReactionForPost(&reactionObject) - th.App.SaveReactionForPost(&reactionObjectDeleted) + th.App.SaveReactionForPost(th.Context, &reactionObject) + th.App.SaveReactionForPost(th.Context, &reactionObjectDeleted) reactionsOfPost, err := th.App.BuildPostReactions(post.Id) require.Nil(t, err) @@ -174,7 +174,7 @@ func TestExportAllUsers(t *testing.T) { // Adding a user and deactivating it to check whether it gets included in bulk export user := th1.CreateUser() - _, err := th1.App.UpdateActive(user, false) + _, err := th1.App.UpdateActive(th1.Context, user, false) require.Nil(t, err) var b bytes.Buffer @@ -183,7 +183,7 @@ func TestExportAllUsers(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - err, i := th2.App.BulkImport(&b, false, 5) + err, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, err) assert.Equal(t, 0, i) @@ -241,7 +241,7 @@ func TestExportDMChannel(t *testing.T) { assert.Equal(t, 0, len(channels)) // import the exported channel - err, i := th2.App.BulkImport(&b, false, 5) + err, i := th2.App.BulkImport(th2.Context, &b, false, 5) require.Nil(t, err) assert.Equal(t, 0, i) @@ -263,8 +263,8 @@ func TestExportDMChannel(t *testing.T) { require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) - th1.App.PermanentDeleteUser(th1.BasicUser2) - th1.App.PermanentDeleteUser(th1.BasicUser) + th1.App.PermanentDeleteUser(th1.Context, th1.BasicUser2) + th1.App.PermanentDeleteUser(th1.Context, th1.BasicUser) var b bytes.Buffer err := th1.App.BulkExport(&b, "somePath", BulkExportOpts{}) @@ -274,7 +274,7 @@ func TestExportDMChannel(t *testing.T) { defer th2.TearDown() // import the exported channel - err, _ = th2.App.BulkImport(&b, true, 5) + err, _ = th2.App.BulkImport(th2.Context, &b, true, 5) require.Nil(t, err) channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") @@ -306,7 +306,7 @@ func TestExportDMChannelToSelf(t *testing.T) { assert.Equal(t, 0, len(channels)) // import the exported channel - err, i := th2.App.BulkImport(&b, false, 5) + err, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, err) assert.Equal(t, 0, i) @@ -378,7 +378,7 @@ func TestExportGMandDMChannels(t *testing.T) { assert.Equal(t, 0, len(channels)) // import the exported channel - err, i := th2.App.BulkImport(&b, false, 5) + err, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, err) assert.Equal(t, 0, i) @@ -415,14 +415,14 @@ func TestExportDMandGMPost(t *testing.T) { Message: "aa" + model.NewId() + "a", UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p1, dmChannel, false, true) + th1.App.CreatePost(th1.Context, p1, dmChannel, false, true) p2 := &model.Post{ ChannelId: dmChannel.Id, Message: "bb" + model.NewId() + "a", UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p2, dmChannel, false, true) + th1.App.CreatePost(th1.Context, p2, dmChannel, false, true) // GM posts p3 := &model.Post{ @@ -430,14 +430,14 @@ func TestExportDMandGMPost(t *testing.T) { Message: "cc" + model.NewId() + "a", UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p3, gmChannel, false, true) + th1.App.CreatePost(th1.Context, p3, gmChannel, false, true) p4 := &model.Post{ ChannelId: gmChannel.Id, Message: "dd" + model.NewId() + "a", UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p4, gmChannel, false, true) + th1.App.CreatePost(th1.Context, p4, gmChannel, false, true) posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) @@ -457,7 +457,7 @@ func TestExportDMandGMPost(t *testing.T) { assert.Equal(t, 0, len(posts)) // import the exported posts - appErr, i := th2.App.BulkImport(&b, false, 5) + appErr, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, appErr) assert.Equal(t, 0, i) @@ -500,7 +500,7 @@ func TestExportPostWithProps(t *testing.T) { }, UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p1, dmChannel, false, true) + th1.App.CreatePost(th1.Context, p1, dmChannel, false, true) p2 := &model.Post{ ChannelId: gmChannel.Id, @@ -510,7 +510,7 @@ func TestExportPostWithProps(t *testing.T) { }, UserId: th1.BasicUser.Id, } - th1.App.CreatePost(p2, gmChannel, false, true) + th1.App.CreatePost(th1.Context, p2, gmChannel, false, true) posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) @@ -532,7 +532,7 @@ func TestExportPostWithProps(t *testing.T) { assert.Len(t, posts, 0) // import the exported posts - appErr, i := th2.App.BulkImport(&b, false, 5) + appErr, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, appErr) assert.Equal(t, 0, i) @@ -574,7 +574,7 @@ func TestExportDMPostWithSelf(t *testing.T) { assert.Equal(t, 0, len(posts)) // import the exported posts - err, i := th2.App.BulkImport(&b, false, 5) + err, i := th2.App.BulkImport(th2.Context, &b, false, 5) assert.Nil(t, err) assert.Equal(t, 0, i) @@ -614,7 +614,7 @@ func TestBulkExport(t *testing.T) { jsonFile := extractImportFile(filepath.Join(testsDir, "import_test.zip")) defer jsonFile.Close() - appErr, _ := th.App.BulkImportWithPath(jsonFile, false, 1, dir) + appErr, _ := th.App.BulkImportWithPath(th.Context, jsonFile, false, 1, dir) require.Nil(t, appErr) exportFile, err := os.Create(filepath.Join(dir, "export.zip")) @@ -635,6 +635,6 @@ func TestBulkExport(t *testing.T) { jsonFile = extractImportFile(filepath.Join(dir, "export.zip")) defer jsonFile.Close() - appErr, _ = th.App.BulkImportWithPath(jsonFile, false, 1, filepath.Join(dir, "data")) + appErr, _ = th.App.BulkImportWithPath(th.Context, jsonFile, false, 1, filepath.Join(dir, "data")) require.Nil(t, appErr) } diff --git a/app/file.go b/app/file.go index db9ed4c28bd..f4d970122f2 100644 --- a/app/file.go +++ b/app/file.go @@ -34,6 +34,7 @@ import ( _ "golang.org/x/image/bmp" _ "golang.org/x/image/tiff" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/services/docextractor" @@ -131,9 +132,8 @@ func (a *App) ReadFile(path string) ([]byte, *model.AppError) { return a.srv.ReadFile(path) } -// Caller must close the first return value -func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) { - backend, err := a.FileBackend() +func (s *Server) fileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) { + backend, err := s.FileBackend() if err != nil { return nil, err } @@ -144,8 +144,17 @@ func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppErro return result, nil } +// Caller must close the first return value +func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) { + return a.Srv().fileReader(path) +} + func (a *App) FileExists(path string) (bool, *model.AppError) { - backend, err := a.FileBackend() + return a.Srv().fileExists(path) +} + +func (s *Server) fileExists(path string) (bool, *model.AppError) { + backend, err := s.FileBackend() if err != nil { return false, err } @@ -194,7 +203,20 @@ func (a *App) MoveFile(oldPath, newPath string) *model.AppError { } func (a *App) WriteFile(fr io.Reader, path string) (int64, *model.AppError) { - return a.srv.WriteFile(fr, path) + return a.Srv().writeFile(fr, path) +} + +func (s *Server) writeFile(fr io.Reader, path string) (int64, *model.AppError) { + backend, err := s.FileBackend() + if err != nil { + return 0, err + } + + result, nErr := backend.WriteFile(fr, path) + if nErr != nil { + return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError) + } + return result, nil } func (a *App) AppendFile(fr io.Reader, path string) (int64, *model.AppError) { @@ -211,7 +233,11 @@ func (a *App) AppendFile(fr io.Reader, path string) (int64, *model.AppError) { } func (a *App) RemoveFile(path string) *model.AppError { - backend, err := a.FileBackend() + return a.Srv().removeFile(path) +} + +func (s *Server) removeFile(path string) *model.AppError { + backend, err := s.FileBackend() if err != nil { return err } @@ -223,7 +249,11 @@ func (a *App) RemoveFile(path string) *model.AppError { } func (a *App) ListDirectory(path string) ([]string, *model.AppError) { - backend, err := a.FileBackend() + return a.Srv().listDirectory(path) +} + +func (s *Server) listDirectory(path string) ([]string, *model.AppError) { + backend, err := s.FileBackend() if err != nil { return nil, err } @@ -474,7 +504,7 @@ func GeneratePublicLinkHash(fileID, salt string) string { 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) { +func (a *App) UploadMultipartFiles(c *request.Context, 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)) @@ -492,13 +522,13 @@ func (a *App) UploadMultipartFiles(teamID string, channelID string, userID strin filenames[i] = fileHeader.Filename } - return a.UploadFiles(teamID, channelID, userID, files, filenames, clientIds, now) + return a.UploadFiles(c, 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) { +func (a *App) UploadFiles(c *request.Context, teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { if *a.Config().FileSettings.DriverName == "" { return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -521,7 +551,7 @@ func (a *App) UploadFiles(teamID string, channelID string, userID string, files io.Copy(buf, file) data := buf.Bytes() - info, data, err := a.DoUploadFileExpectModification(now, teamID, channelID, userID, filenames[i], data) + info, data, err := a.DoUploadFileExpectModification(c, now, teamID, channelID, userID, filenames[i], data) if err != nil { return nil, err } @@ -545,14 +575,14 @@ func (a *App) UploadFiles(teamID string, channelID string, userID string, files } // 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) { +func (a *App) UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) { _, err := a.GetChannel(channelID) if err != nil && channelID != "" { return nil, model.NewAppError("UploadFile", "api.file.upload_file.incorrect_channelId.app_error", map[string]interface{}{"channelId": channelID}, "", http.StatusBadRequest) } - info, _, appError := a.DoUploadFileExpectModification(time.Now(), "noteam", channelID, "nouser", filename, data) + info, _, appError := a.DoUploadFileExpectModification(c, time.Now(), "noteam", channelID, "nouser", filename, data) if appError != nil { return nil, appError } @@ -568,8 +598,8 @@ func (a *App) UploadFile(data []byte, channelID string, filename string) (*model 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) +func (a *App) DoUploadFile(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { + info, _, err := a.DoUploadFileExpectModification(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) return info, err } @@ -691,7 +721,7 @@ func (t *UploadFileTask) init(a *App) { // 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, +func (a *App) UploadFileX(c *request.Context, channelID, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) { t := &UploadFileTask{ @@ -741,7 +771,7 @@ func (a *App) UploadFileX(channelID, name string, input io.Reader, } defer file.Close() - aerr = a.runPluginsHook(t.fileinfo, file) + aerr = a.runPluginsHook(c, t.fileinfo, file) if aerr != nil { return nil, aerr } @@ -942,7 +972,7 @@ func (t UploadFileTask) newAppError(id string, httpStatus int, extra ...interfac return model.NewAppError("uploadFileTask", id, params, "", httpStatus) } -func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) { +func (a *App) DoUploadFileExpectModification(c *request.Context, 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) @@ -986,7 +1016,7 @@ func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, ra if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { var rejectionError *model.AppError - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { var newBytes bytes.Buffer replacementInfo, rejectionReason := hooks.FileWillBeUploaded(pluginContext, info, bytes.NewReader(data), &newBytes) @@ -1322,7 +1352,7 @@ func populateZipfile(w *zip.Writer, fileDatas []model.FileData) error { return nil } -func (a *App) SearchFilesInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError) { +func (a *App) SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError) { paramsList := model.ParseSearchParams(strings.TrimSpace(terms), timeZoneOffset) includeDeleted := includeDeletedChannels && *a.Config().TeamSettings.ExperimentalViewArchivedChannels @@ -1338,8 +1368,8 @@ func (a *App) SearchFilesInTeamForUser(terms string, userId string, teamId strin // Don't allow users to search for "*" if params.Terms != "*" { // Convert channel names to channel IDs - params.InChannels = a.convertChannelNamesToChannelIds(params.InChannels, userId, teamId, includeDeletedChannels) - params.ExcludedChannels = a.convertChannelNamesToChannelIds(params.ExcludedChannels, userId, teamId, includeDeletedChannels) + params.InChannels = a.convertChannelNamesToChannelIds(c, params.InChannels, userId, teamId, includeDeletedChannels) + params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userId, teamId, includeDeletedChannels) // Convert usernames to user IDs params.FromUsers = a.convertUserNameToUserIds(params.FromUsers) diff --git a/app/file_bench_test.go b/app/file_bench_test.go index 87d7f99748e..d01d3c2de24 100644 --- a/app/file_bench_test.go +++ b/app/file_bench_test.go @@ -86,7 +86,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "raw-ish DoUploadFile", f: func(b *testing.B, n int, data []byte, ext string) { - info1, err := th.App.DoUploadFile(time.Now(), teamID, channelID, + info1, err := th.App.DoUploadFile(th.Context, time.Now(), teamID, channelID, userID, fmt.Sprintf("BenchmarkDoUploadFile-%d%s", n, ext), data) if err != nil { b.Fatal(err) @@ -99,7 +99,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "raw UploadFileX Content-Length", f: func(b *testing.B, n int, data []byte, ext string) { - info, aerr := th.App.UploadFileX(channelID, + info, aerr := th.App.UploadFileX(th.Context, channelID, fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext), bytes.NewReader(data), UploadFileSetTeamId(teamID), @@ -117,7 +117,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "raw UploadFileX chunked", f: func(b *testing.B, n int, data []byte, ext string) { - info, aerr := th.App.UploadFileX(channelID, + info, aerr := th.App.UploadFileX(th.Context, channelID, fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext), bytes.NewReader(data), UploadFileSetTeamId(teamID), @@ -135,7 +135,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "image UploadFiles", f: func(b *testing.B, n int, data []byte, ext string) { - resp, err := th.App.UploadFiles(teamID, channelID, userID, + resp, err := th.App.UploadFiles(th.Context, teamID, channelID, userID, []io.ReadCloser{ioutil.NopCloser(bytes.NewReader(data))}, []string{fmt.Sprintf("BenchmarkDoUploadFiles-%d%s", n, ext)}, []string{}, @@ -150,7 +150,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "image UploadFileX Content-Length", f: func(b *testing.B, n int, data []byte, ext string) { - info, aerr := th.App.UploadFileX(channelID, + info, aerr := th.App.UploadFileX(th.Context, channelID, fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext), bytes.NewReader(data), UploadFileSetTeamId(teamID), @@ -167,7 +167,7 @@ func BenchmarkUploadFile(b *testing.B) { { title: "image UploadFileX chunked", f: func(b *testing.B, n int, data []byte, ext string) { - info, aerr := th.App.UploadFileX(channelID, + info, aerr := th.App.UploadFileX(th.Context, channelID, fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext), bytes.NewReader(data), UploadFileSetTeamId(teamID), diff --git a/app/file_test.go b/app/file_test.go index 4938ac5354f..1e50644c564 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -50,7 +50,7 @@ func TestDoUploadFile(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) + info1, err := th.App.DoUploadFile(th.Context, 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) @@ -60,7 +60,7 @@ func TestDoUploadFile(t *testing.T) { value := fmt.Sprintf("20070204/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info1.Id, filename) assert.Equal(t, value, info1.Path, "stored file at incorrect path") - info2, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) + info2, err := th.App.DoUploadFile(th.Context, 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) @@ -70,7 +70,7 @@ func TestDoUploadFile(t *testing.T) { value = fmt.Sprintf("20070204/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info2.Id, filename) assert.Equal(t, value, info2.Path, "stored file at incorrect path") - info3, err := th.App.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) + info3, err := th.App.DoUploadFile(th.Context, 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) @@ -80,7 +80,7 @@ func TestDoUploadFile(t *testing.T) { value = fmt.Sprintf("20080305/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info3.Id, filename) assert.Equal(t, value, info3.Path, "stored file at incorrect path") - info4, err := th.App.DoUploadFile(time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamID, "../../"+channelID, "../../"+userID, "../../"+filename, data) + info4, err := th.App.DoUploadFile(th.Context, 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) @@ -99,15 +99,15 @@ func TestUploadFile(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := th.App.UploadFile(data, "wrong", filename) + info1, err := th.App.UploadFile(th.Context, data, "wrong", filename) require.NotNil(t, err, "Wrong Channel ID.") require.Nil(t, info1, "Channel ID does not exist.") - info1, err = th.App.UploadFile(data, "", filename) + info1, err = th.App.UploadFile(th.Context, data, "", filename) require.Nil(t, err, "empty channel IDs should be valid") require.NotNil(t, info1) - info1, err = th.App.UploadFile(data, channelID, filename) + info1, err = th.App.UploadFile(th.Context, data, channelID, filename) require.Nil(t, err, "UploadFile should succeed with valid data") defer func() { th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) @@ -234,7 +234,7 @@ func TestFindTeamIdForFilename(t *testing.T) { teamID := th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png") assert.Equal(t, th.BasicTeam.Id, teamID) - _, err := th.App.CreateTeamWithUser(&model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id) + _, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id) require.Nil(t, err) teamID = th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png") @@ -262,13 +262,13 @@ func TestMigrateFilenamesToFileInfos(t *testing.T) { fpath := fmt.Sprintf("/teams/%v/channels/%v/users/%v/%v/test.png", th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, fileID) _, err := th.App.WriteFile(file, fpath) require.Nil(t, err) - rpost, err := th.App.CreatePost(&model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true) require.Nil(t, err) infos = th.App.MigrateFilenamesToFileInfos(rpost) assert.Equal(t, 1, len(infos)) - rpost, err = th.App.CreatePost(&model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/../../test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true) + rpost, err = th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/../../test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true) require.Nil(t, err) infos = th.App.MigrateFilenamesToFileInfos(rpost) @@ -303,7 +303,7 @@ func TestCopyFileInfos(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) + info1, err := th.App.DoUploadFile(th.Context, 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) @@ -399,7 +399,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { page := 0 - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) require.NotNil(t, results) @@ -420,7 +420,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { page := 1 - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) require.NotNil(t, results) @@ -451,7 +451,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) require.NotNil(t, results) @@ -480,7 +480,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) require.NotNil(t, results) @@ -505,7 +505,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) require.NotNil(t, results) @@ -538,7 +538,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) require.Nil(t, err) assert.Equal(t, []string{}, results.Order) diff --git a/app/helper_test.go b/app/helper_test.go index 515fbb23701..a2e189e36e3 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -17,8 +17,10 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/mlog" "github.com/mattermost/mattermost-server/v5/store" "github.com/mattermost/mattermost-server/v5/store/localcachelayer" @@ -30,6 +32,7 @@ import ( type TestHelper struct { App *App + Context *request.Context Server *Server BasicTeam *model.Team BasicUser *model.User @@ -86,6 +89,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th := &TestHelper{ App: New(ServerConnector(s)), + Context: &request.Context{}, Server: s, LogBuffer: buffer, IncludeCacheLayer: includeCacheLayer, @@ -119,6 +123,8 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo if enterprise { th.App.Srv().SetLicense(model.NewTestLicense()) + th.App.Srv().Jobs.InitWorkers() + th.App.Srv().Jobs.InitSchedulers() } else { th.App.Srv().SetLicense(nil) } @@ -127,8 +133,6 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th.tempWorkspace = tempWorkspace } - th.App.InitServer() - return th } @@ -238,7 +242,7 @@ func (th *TestHelper) CreateTeam() *model.Team { utils.DisableDebugLogForTest() var err *model.AppError - if team, err = th.App.CreateTeam(team); err != nil { + if team, err = th.App.CreateTeam(th.Context, team); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -267,11 +271,11 @@ func (th *TestHelper) CreateUserOrGuest(guest bool) *model.User { utils.DisableDebugLogForTest() var err *model.AppError if guest { - if user, err = th.App.CreateGuest(user); err != nil { + if user, err = th.App.CreateGuest(th.Context, user); err != nil { panic(err) } } else { - if user, err = th.App.CreateUser(user); err != nil { + if user, err = th.App.CreateUser(th.Context, user); err != nil { panic(err) } } @@ -289,7 +293,7 @@ func (th *TestHelper) CreateBot() *model.Bot { OwnerId: th.BasicUser.Id, } - bot, err := th.App.CreateBot(bot) + bot, err := th.App.CreateBot(th.Context, bot) if err != nil { panic(err) } @@ -329,7 +333,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType string, option utils.DisableDebugLogForTest() var appErr *model.AppError - if channel, appErr = th.App.CreateChannel(channel, true); appErr != nil { + if channel, appErr = th.App.CreateChannel(th.Context, channel, true); appErr != nil { panic(appErr) } @@ -357,7 +361,7 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel { utils.DisableDebugLogForTest() var err *model.AppError var channel *model.Channel - if channel, err = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, user.Id); err != nil { + if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -387,7 +391,7 @@ func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post { utils.DisableDebugLogForTest() var err *model.AppError - if post, err = th.App.CreatePost(post, channel, false, true); err != nil { + if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -404,7 +408,7 @@ func (th *TestHelper) CreateMessagePost(channel *model.Channel, message string) utils.DisableDebugLogForTest() var err *model.AppError - if post, err = th.App.CreatePost(post, channel, false, true); err != nil { + if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -414,7 +418,7 @@ func (th *TestHelper) CreateMessagePost(channel *model.Channel, message string) func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - _, err := th.App.JoinUserToTeam(team, user, "") + _, err := th.App.JoinUserToTeam(th.Context, team, user, "") if err != nil { panic(err) } @@ -425,7 +429,7 @@ func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { func (th *TestHelper) RemoveUserFromTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - err := th.App.RemoveUserFromTeam(team.Id, user.Id, "") + err := th.App.RemoveUserFromTeam(th.Context, team.Id, user.Id, "") if err != nil { panic(err) } @@ -525,7 +529,7 @@ func (th *TestHelper) CreateEmoji() *model.Emoji { func (th *TestHelper) AddReactionToPost(post *model.Post, user *model.User, emojiName string) *model.Reaction { utils.DisableDebugLogForTest() - reaction, err := th.App.SaveReactionForPost(&model.Reaction{ + reaction, err := th.App.SaveReactionForPost(th.Context, &model.Reaction{ UserId: user.Id, PostId: post.Id, EmojiName: emojiName, @@ -660,7 +664,7 @@ func (th *TestHelper) SetupPluginAPI() *PluginAPI { Id: "pluginid", } - return NewPluginAPI(th.App, manifest) + return NewPluginAPI(th.App, th.Context, manifest) } func (th *TestHelper) RemovePermissionFromRole(permission string, roleName string) { @@ -734,3 +738,7 @@ func NewTestId() string { return string(newId) } + +func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API { + return th.App.NewPluginAPI(th.Context, manifest) +} diff --git a/app/import.go b/app/import.go index 5fd009e9cc8..bb0b98f8408 100644 --- a/app/import.go +++ b/app/import.go @@ -13,6 +13,7 @@ import ( "strings" "sync" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) @@ -75,7 +76,7 @@ func rewriteFilePaths(line *LineImportData, basePath string) { } } -func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) { +func (a *App) bulkImportWorker(c *request.Context, dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) { postLines := []LineImportWorkerData{} directPostLines := []LineImportWorkerData{} for line := range lines { @@ -86,7 +87,7 @@ func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan Lin errors <- LineImportWorkerError{model.NewAppError("BulkImport", "app.import.import_line.null_post.error", nil, "", http.StatusBadRequest), line.LineNumber} } if len(postLines) >= importMultiplePostsThreshold { - if errLine, err := a.importMultiplePostLines(postLines, dryRun); err != nil { + if errLine, err := a.importMultiplePostLines(c, postLines, dryRun); err != nil { errors <- LineImportWorkerError{err, errLine} } postLines = []LineImportWorkerData{} @@ -97,40 +98,40 @@ func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan Lin errors <- LineImportWorkerError{model.NewAppError("BulkImport", "app.import.import_line.null_direct_post.error", nil, "", http.StatusBadRequest), line.LineNumber} } if len(directPostLines) >= importMultiplePostsThreshold { - if errLine, err := a.importMultipleDirectPostLines(directPostLines, dryRun); err != nil { + if errLine, err := a.importMultipleDirectPostLines(c, directPostLines, dryRun); err != nil { errors <- LineImportWorkerError{err, errLine} } directPostLines = []LineImportWorkerData{} } default: - if err := a.importLine(line.LineImportData, dryRun); err != nil { + if err := a.importLine(c, line.LineImportData, dryRun); err != nil { errors <- LineImportWorkerError{err, line.LineNumber} } } } if len(postLines) > 0 { - if errLine, err := a.importMultiplePostLines(postLines, dryRun); err != nil { + if errLine, err := a.importMultiplePostLines(c, postLines, dryRun); err != nil { errors <- LineImportWorkerError{err, errLine} } } if len(directPostLines) > 0 { - if errLine, err := a.importMultipleDirectPostLines(directPostLines, dryRun); err != nil { + if errLine, err := a.importMultipleDirectPostLines(c, directPostLines, dryRun); err != nil { errors <- LineImportWorkerError{err, errLine} } } wg.Done() } -func (a *App) BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { - return a.bulkImport(fileReader, dryRun, workers, "") +func (a *App) BulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { + return a.bulkImport(c, fileReader, dryRun, workers, "") } -func (a *App) BulkImportWithPath(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { - return a.bulkImport(fileReader, dryRun, workers, importPath) +func (a *App) BulkImportWithPath(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { + return a.bulkImport(c, fileReader, dryRun, workers, importPath) } -func (a *App) bulkImport(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { +func (a *App) bulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { scanner := bufio.NewScanner(fileReader) buf := make([]byte, 0, 64*1024) scanner.Buffer(buf, maxScanTokenSize) @@ -192,7 +193,7 @@ func (a *App) bulkImport(fileReader io.Reader, dryRun bool, workers int, importP linesChan = make(chan LineImportWorkerData, workers) for i := 0; i < workers; i++ { wg.Add(1) - go a.bulkImportWorker(dryRun, &wg, linesChan, errorsChan) + go a.bulkImportWorker(c, dryRun, &wg, linesChan, errorsChan) } } @@ -236,7 +237,7 @@ func processImportDataFileVersionLine(line LineImportData) (int, *model.AppError return *line.Version, nil } -func (a *App) importLine(line LineImportData, dryRun bool) *model.AppError { +func (a *App) importLine(c *request.Context, line LineImportData, dryRun bool) *model.AppError { switch { case line.Type == "scheme": if line.Scheme == nil { @@ -247,12 +248,12 @@ func (a *App) importLine(line LineImportData, dryRun bool) *model.AppError { if line.Team == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_team.error", nil, "", http.StatusBadRequest) } - return a.importTeam(line.Team, dryRun) + return a.importTeam(c, line.Team, dryRun) case line.Type == "channel": if line.Channel == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_channel.error", nil, "", http.StatusBadRequest) } - return a.importChannel(line.Channel, dryRun) + return a.importChannel(c, line.Channel, dryRun) case line.Type == "user": if line.User == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_user.error", nil, "", http.StatusBadRequest) diff --git a/app/import_functions.go b/app/import_functions.go index 70684f7bc88..bcf57645721 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -15,6 +15,7 @@ import ( "path" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" "github.com/mattermost/mattermost-server/v5/store" @@ -155,7 +156,7 @@ func (a *App) importRole(data *RoleImportData, dryRun bool, isSchemeRole bool) * return err } -func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError { +func (a *App) importTeam(c *request.Context, data *TeamImportData, dryRun bool) *model.AppError { if err := validateTeamImportData(data); err != nil { return err } @@ -202,7 +203,7 @@ func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError { } if team.Id == "" { - if _, err := a.CreateTeam(team); err != nil { + if _, err := a.CreateTeam(c, team); err != nil { return err } } else { @@ -214,7 +215,7 @@ func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError { return nil } -func (a *App) importChannel(data *ChannelImportData, dryRun bool) *model.AppError { +func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun bool) *model.AppError { if err := validateChannelImportData(data); err != nil { return err } @@ -267,7 +268,7 @@ func (a *App) importChannel(data *ChannelImportData, dryRun bool) *model.AppErro } if channel.Id == "" { - if _, err := a.CreateChannel(channel, false); err != nil { + if _, err := a.CreateChannel(c, channel, false); err != nil { return err } } else { @@ -1020,7 +1021,7 @@ func (a *App) importReaction(data *ReactionImportData, post *model.Post) *model. return nil } -func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID string) *model.AppError { +func (a *App) importReplies(c *request.Context, data []ReplyImportData, post *model.Post, teamID string) *model.AppError { var err *model.AppError usernames := []string{} for _, replyData := range data { @@ -1068,7 +1069,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID str reply.Message = *replyData.Message reply.CreateAt = *replyData.CreateAt - fileIDs, err := a.uploadAttachments(replyData.Attachments, reply, teamID) + fileIDs, err := a.uploadAttachments(c, replyData.Attachments, reply, teamID) if err != nil { return err } @@ -1116,7 +1117,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID str return nil } -func (a *App) importAttachment(data *AttachmentImportData, post *model.Post, teamID string) (*model.FileInfo, *model.AppError) { +func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, post *model.Post, teamID string) (*model.FileInfo, *model.AppError) { file, err := os.Open(*data.Path) if file == nil || err != nil { return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]interface{}{"FilePath": *data.Path}, "", http.StatusBadRequest) @@ -1157,7 +1158,7 @@ func (a *App) importAttachment(data *AttachmentImportData, post *model.Post, tea mlog.Info("Uploading file with name", mlog.String("file_name", file.Name())) - fileInfo, appErr := a.DoUploadFile(timestamp, teamID, post.ChannelId, post.UserId, file.Name(), fileData) + fileInfo, appErr := a.DoUploadFile(c, timestamp, teamID, post.ChannelId, post.UserId, file.Name(), fileData) if appErr != nil { mlog.Error("Failed to upload file:", mlog.Err(appErr)) return nil, appErr @@ -1251,7 +1252,7 @@ func getPostStrID(post *model.Post) string { // importMultiplePostLines will return an error and the line that // caused it whenever possible -func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) { +func (a *App) importMultiplePostLines(c *request.Context, lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) { if len(lines) == 0 { return 0, nil } @@ -1332,7 +1333,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) post.Props = *line.Post.Props } - fileIDs, appErr := a.uploadAttachments(line.Post.Attachments, post, team.Id) + fileIDs, appErr := a.uploadAttachments(c, line.Post.Attachments, post, team.Id) if appErr != nil { return line.LineNumber, appErr } @@ -1423,7 +1424,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) } if postWithData.postData.Replies != nil && len(*postWithData.postData.Replies) > 0 { - err := a.importReplies(*postWithData.postData.Replies, postWithData.post, postWithData.team.Id) + err := a.importReplies(c, *postWithData.postData.Replies, postWithData.post, postWithData.team.Id) if err != nil { return postWithData.lineNumber, err } @@ -1434,14 +1435,14 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) } // uploadAttachments imports new attachments and returns current attachments of the post as a map -func (a *App) uploadAttachments(attachments *[]AttachmentImportData, post *model.Post, teamID string) (map[string]bool, *model.AppError) { +func (a *App) uploadAttachments(c *request.Context, attachments *[]AttachmentImportData, post *model.Post, teamID string) (map[string]bool, *model.AppError) { if attachments == nil { return nil, nil } fileIDs := make(map[string]bool) for _, attachment := range *attachments { attachment := attachment - fileInfo, err := a.importAttachment(&attachment, post, teamID) + fileInfo, err := a.importAttachment(c, &attachment, post, teamID) if err != nil { return nil, err } @@ -1538,7 +1539,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m // importMultipleDirectPostLines will return an error and the line // that caused it whenever possible -func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) { +func (a *App) importMultipleDirectPostLines(c *request.Context, lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) { if len(lines) == 0 { return 0, nil } @@ -1585,7 +1586,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun var channel *model.Channel var ch *model.Channel if len(userIDs) == 2 { - ch, err = a.GetOrCreateDirectChannel(userIDs[0], userIDs[1]) + ch, err = a.GetOrCreateDirectChannel(c, userIDs[0], userIDs[1]) if err != nil && err.Id != store.ChannelExistsError { return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest) } @@ -1628,7 +1629,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun post.Props = *line.DirectPost.Props } - fileIDs, err := a.uploadAttachments(line.DirectPost.Attachments, post, "noteam") + fileIDs, err := a.uploadAttachments(c, line.DirectPost.Attachments, post, "noteam") if err != nil { return line.LineNumber, err } @@ -1717,7 +1718,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun } if postWithData.directPostData.Replies != nil { - if err := a.importReplies(*postWithData.directPostData.Replies, postWithData.post, "noteam"); err != nil { + if err := a.importReplies(c, *postWithData.directPostData.Replies, postWithData.post, "noteam"); err != nil { return postWithData.lineNumber, err } } diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 3d988ff608d..cc5342e9be5 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -518,12 +518,12 @@ func TestImportImportTeam(t *testing.T) { } // Try importing an invalid team in dryRun mode. - err = th.App.importTeam(&data, true) + err = th.App.importTeam(th.Context, &data, true) require.Error(t, err, "Should have received an error importing an invalid team.") // Do a valid team in dry-run mode. data.Type = ptrStr("O") - appErr := th.App.importTeam(&data, true) + appErr := th.App.importTeam(th.Context, &data, true) require.Nil(t, appErr, "Received an error validating valid team.") // Check that no more teams are in the DB. @@ -531,7 +531,7 @@ func TestImportImportTeam(t *testing.T) { // Do an invalid team in apply mode, check db changes. data.Type = ptrStr("XYZ") - err = th.App.importTeam(&data, false) + err = th.App.importTeam(th.Context, &data, false) require.Error(t, err, "Import should have failed on invalid team.") // Check that no more teams are in the DB. @@ -539,7 +539,7 @@ func TestImportImportTeam(t *testing.T) { // Do a valid team in apply mode, check db changes. data.Type = ptrStr("O") - appErr = th.App.importTeam(&data, false) + appErr = th.App.importTeam(th.Context, &data, false) require.Nil(t, appErr, "Received an error importing valid team: %v", err) // Check that one more team is in the DB. @@ -564,7 +564,7 @@ func TestImportImportTeam(t *testing.T) { // Check that the original number of teams are again in the DB (because this query doesn't include deleted). data.Type = ptrStr("O") - appErr = th.App.importTeam(&data, false) + appErr = th.App.importTeam(th.Context, &data, false) require.Nil(t, appErr, "Received an error importing updated valid team.") th.CheckTeamCount(t, teamsCount+1) @@ -596,7 +596,7 @@ func TestImportImportChannel(t *testing.T) { // Import a Team. teamName := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), @@ -617,7 +617,7 @@ func TestImportImportChannel(t *testing.T) { Purpose: ptrStr("Channel Purpose"), Scheme: &scheme1.Name, } - err = th.App.importChannel(&data, true) + err = th.App.importChannel(th.Context, &data, true) require.NotNil(t, err, "Expected error due to invalid name.") // Check that no more channels are in the DB. @@ -626,7 +626,7 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel with a nonexistent team in dry-run mode. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - err = th.App.importChannel(&data, true) + err = th.App.importChannel(th.Context, &data, true) require.Nil(t, err, "Expected success as cannot validate channel name in dry run mode.") // Check that no more channels are in the DB. @@ -634,7 +634,7 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in dry-run mode. data.Team = &teamName - err = th.App.importChannel(&data, true) + err = th.App.importChannel(th.Context, &data, true) require.Nil(t, err, "Expected success as valid team.") // Check that no more channels are in the DB. @@ -642,7 +642,7 @@ func TestImportImportChannel(t *testing.T) { // Do an invalid channel in apply mode. data.Name = nil - err = th.App.importChannel(&data, false) + err = th.App.importChannel(th.Context, &data, false) require.NotNil(t, err, "Expected error due to invalid name (apply mode).") // Check that no more channels are in the DB. @@ -651,7 +651,7 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode with a non-existent team. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - err = th.App.importChannel(&data, false) + err = th.App.importChannel(th.Context, &data, false) require.NotNil(t, err, "Expected error due to non-existent team (apply mode).") // Check that no more channels are in the DB. @@ -659,7 +659,7 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode. data.Team = &teamName - err = th.App.importChannel(&data, false) + err = th.App.importChannel(th.Context, &data, false) require.Nil(t, err, "Expected success in apply mode") // Check that 1 more channel is in the DB. @@ -682,7 +682,7 @@ func TestImportImportChannel(t *testing.T) { data.Header = ptrStr("New Header") data.Purpose = ptrStr("New Purpose") data.Scheme = &scheme2.Name - err = th.App.importChannel(&data, false) + err = th.App.importChannel(th.Context, &data, false) require.Nil(t, err, "Expected success in apply mode") // Check channel count the same. @@ -864,7 +864,7 @@ func TestImportImportUser(t *testing.T) { // Test team and channel memberships teamName := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), @@ -873,7 +873,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get team from database.") channelName := model.NewId() - th.App.importChannel(&ChannelImportData{ + th.App.importChannel(th.Context, &ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), @@ -1386,7 +1386,7 @@ func TestImportImportUser(t *testing.T) { AllowOpenInvite: ptrBool(true), Scheme: &teamScheme.Name, } - appErr = th.App.importTeam(teamData, false) + appErr = th.App.importTeam(th.Context, teamData, false) assert.Nil(t, appErr) team, appErr = th.App.GetTeamByName(teamName) require.Nil(t, appErr, "Failed to get team from database.") @@ -1399,7 +1399,7 @@ func TestImportImportUser(t *testing.T) { Header: ptrStr("Channe Header"), Purpose: ptrStr("Channel Purpose"), } - appErr = th.App.importChannel(channelData, false) + appErr = th.App.importChannel(th.Context, channelData, false) assert.Nil(t, appErr) channel, appErr = th.App.GetChannelByName(*channelData.Name, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database") @@ -1928,7 +1928,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { // Create a Team. teamName := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), @@ -1938,7 +1938,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { // Create a Channel. channelName := model.NewId() - th.App.importChannel(&ChannelImportData{ + th.App.importChannel(th.Context, &ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), @@ -1971,7 +1971,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 25, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true) assert.NotNil(t, err) assert.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -1989,7 +1989,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, true) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2006,7 +2006,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 35, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) assert.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2024,7 +2024,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 10, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) // Batch will fail when searching for teams, so no specific line // is associated with the error @@ -2044,7 +2044,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 7, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) // Batch will fail when searching for channels, so no specific // line is associated with the error @@ -2064,7 +2064,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 2, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) // Batch will fail when searching for users, so no specific line // is associated with the error @@ -2085,7 +2085,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) @@ -2113,7 +2113,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) @@ -2142,7 +2142,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id) @@ -2160,7 +2160,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id) @@ -2179,7 +2179,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) @@ -2222,7 +2222,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2261,7 +2261,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2302,7 +2302,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2348,7 +2348,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2372,7 +2372,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2396,7 +2396,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err, "Expected success.") assert.Equal(t, 0, errLine) @@ -2404,7 +2404,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { // Create another Team. teamName2 := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName2, DisplayName: ptrStr("Display Name 2"), Type: ptrStr("O"), @@ -2413,7 +2413,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { require.Nil(t, err, "Failed to get team from database.") // Create another Channel for the another team. - th.App.importChannel(&ChannelImportData{ + th.App.importChannel(th.Context, &ChannelImportData{ Team: &teamName2, Name: &channelName, DisplayName: ptrStr("Display Name"), @@ -2451,7 +2451,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { }, 1, } - errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data, data2}, false) + errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data, data2}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) @@ -2466,7 +2466,7 @@ func TestImportImportPost(t *testing.T) { // Create a Team. teamName := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), @@ -2476,7 +2476,7 @@ func TestImportImportPost(t *testing.T) { // Create a Channel. channelName := model.NewId() - th.App.importChannel(&ChannelImportData{ + th.App.importChannel(th.Context, &ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), @@ -2522,7 +2522,7 @@ func TestImportImportPost(t *testing.T) { }, 12, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true) assert.NotNil(t, err) assert.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2541,7 +2541,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2559,7 +2559,7 @@ func TestImportImportPost(t *testing.T) { }, 2, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) assert.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2578,7 +2578,7 @@ func TestImportImportPost(t *testing.T) { }, 7, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2597,7 +2597,7 @@ func TestImportImportPost(t *testing.T) { }, 8, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2616,7 +2616,7 @@ func TestImportImportPost(t *testing.T) { }, 9, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.NotNil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) @@ -2635,7 +2635,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) @@ -2664,7 +2664,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) @@ -2694,7 +2694,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id) @@ -2713,7 +2713,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id) @@ -2732,7 +2732,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) assert.Nil(t, err) assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) @@ -2768,7 +2768,7 @@ func TestImportImportPost(t *testing.T) { 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -2808,7 +2808,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -2848,7 +2848,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -2895,7 +2895,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -2920,7 +2920,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -2945,7 +2945,7 @@ func TestImportImportPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3044,7 +3044,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Get the channel to check that the header was updated. - channel, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, appErr) require.Equal(t, channel.Header, *data.Header) @@ -3115,7 +3115,7 @@ func TestImportImportDirectChannel(t *testing.T) { appErr = th.App.importDirectChannel(&data, false) require.Nil(t, appErr) - channel, appErr = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + channel, appErr = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, appErr) checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") @@ -3137,7 +3137,7 @@ func TestImportImportDirectPost(t *testing.T) { // Get the channel. var directChannel *model.Channel - channel, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, appErr) require.NotEmpty(t, channel) directChannel = channel @@ -3162,7 +3162,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 7, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true) require.NotNil(t, err) require.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3183,7 +3183,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3204,7 +3204,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 9, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.NotNil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3225,7 +3225,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, "") @@ -3256,7 +3256,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, "") @@ -3287,7 +3287,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 2, "") @@ -3308,7 +3308,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 3, "") @@ -3329,7 +3329,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") @@ -3365,7 +3365,7 @@ func TestImportImportDirectPost(t *testing.T) { 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) @@ -3424,7 +3424,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 4, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true) require.NotNil(t, err) require.Equal(t, data.LineNumber, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3446,7 +3446,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3469,7 +3469,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 8, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.NotNil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 0, "") @@ -3491,7 +3491,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, "") @@ -3523,7 +3523,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 1, "") @@ -3555,7 +3555,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 2, "") @@ -3577,7 +3577,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 3, "") @@ -3599,7 +3599,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") @@ -3636,7 +3636,7 @@ func TestImportImportDirectPost(t *testing.T) { 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) @@ -3675,7 +3675,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3720,7 +3720,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3772,7 +3772,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3802,7 +3802,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3832,7 +3832,7 @@ func TestImportImportDirectPost(t *testing.T) { }, 1, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -3891,14 +3891,14 @@ func TestImportAttachment(t *testing.T) { userID := model.NewId() data := AttachmentImportData{Path: &testImage} - _, err := th.App.importAttachment(&data, &model.Post{UserId: userID, ChannelId: "some-channel"}, "some-team") + _, err := th.App.importAttachment(th.Context, &data, &model.Post{UserId: userID, ChannelId: "some-channel"}, "some-team") assert.Nil(t, err, "sample run without errors") attachments := GetAttachments(userID, th, t) assert.Len(t, attachments, 1) data = AttachmentImportData{Path: &invalidPath} - _, err = th.App.importAttachment(&data, &model.Post{UserId: model.NewId(), ChannelId: "some-channel"}, "some-team") + _, err = th.App.importAttachment(th.Context, &data, &model.Post{UserId: model.NewId(), ChannelId: "some-channel"}, "some-team") assert.NotNil(t, err, "should have failed when opening the file") assert.Equal(t, err.Id, "app.import.attachment.bad_file.error") } @@ -3909,7 +3909,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { // Create a Team. teamName := model.NewRandomTeamName() - th.App.importTeam(&TeamImportData{ + th.App.importTeam(th.Context, &TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), @@ -3919,7 +3919,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { // Create a Channel. channelName := model.NewId() - th.App.importChannel(&ChannelImportData{ + th.App.importChannel(th.Context, &ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), @@ -3992,7 +3992,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { } t.Run("import with attachment", func(t *testing.T) { - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) @@ -4010,7 +4010,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { t.Run("import existing post with new attachment", func(t *testing.T) { data.Post.Attachments = &[]AttachmentImportData{{Path: &testImage}} - errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false) + errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false) require.Nil(t, err) require.Equal(t, 0, errLine) @@ -4047,7 +4047,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { 7, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -4108,7 +4108,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { } t.Run("Regular import of attachment", func(t *testing.T) { - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -4119,7 +4119,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { }) t.Run("Attempt to import again with same file entirely, should NOT add an attachment", func(t *testing.T) { - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -4144,7 +4144,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { 2, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportDataFake}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportDataFake}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) @@ -4169,7 +4169,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { 2, } - errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData2}, false) + errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData2}, false) require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) diff --git a/app/import_test.go b/app/import_test.go index 384d0ccb2a9..5fc39af5c00 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -85,42 +85,42 @@ func TestImportImportLine(t *testing.T) { Type: "gibberish", } - err := th.App.importLine(line, false) + err := th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with invalid type.") // Try import line with team type but nil team. line.Type = "team" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line of type team with a nil team.") // Try import line with channel type but nil channel. line.Type = "channel" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type channel with a nil channel.") // Try import line with user type but nil user. line.Type = "user" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type user with a nil user.") // Try import line with post type but nil post. line.Type = "post" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type post with a nil post.") // Try import line with direct_channel type but nil direct_channel. line.Type = "direct_channel" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type direct_channel with a nil direct_channel.") // Try import line with direct_post type but nil direct_post. line.Type = "direct_post" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type direct_post with a nil direct_post.") // Try import line with scheme type but nil scheme. line.Type = "scheme" - err = th.App.importLine(line, false) + err = th.App.importLine(th.Context, line, false) require.NotNil(t, err, "Expected an error when importing a line with type scheme with a nil scheme.") } @@ -185,13 +185,13 @@ func TestImportBulkImport(t *testing.T) { {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `", "` + username3 + `"], "user": "` + username + `", "message": "Hello Group Channel", "create_at": 123456789015}} {"type": "emoji", "emoji": {"name": "` + emojiName + `", "image": "` + testImage + `"}}` - err, line := th.App.BulkImport(strings.NewReader(data1), false, 2) + err, line := th.App.BulkImport(th.Context, strings.NewReader(data1), false, 2) require.Nil(t, err, "BulkImport should have succeeded") require.Equal(t, 0, line, "BulkImport line should be 0") // Run bulk import using a string that contains a line with invalid json. data2 := `{"type": "version", "version": 1` - err, line = th.App.BulkImport(strings.NewReader(data2), false, 2) + err, line = th.App.BulkImport(th.Context, strings.NewReader(data2), false, 2) require.NotNil(t, err, "Should have failed due to invalid JSON on line 1.") require.Equal(t, 1, line, "Should have failed due to invalid JSON on line 1.") @@ -200,7 +200,7 @@ func TestImportBulkImport(t *testing.T) { {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}} {"type": "user", "user": {"username": "kufjgnkxkrhhfgbrip6qxkfsaa", "email": "kufjgnkxkrhhfgbrip6qxkfsaa@example.com"}} {"type": "user", "user": {"username": "bwshaim6qnc2ne7oqkd5b2s2rq", "email": "bwshaim6qnc2ne7oqkd5b2s2rq@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}]}]}}` - err, line = th.App.BulkImport(strings.NewReader(data3), false, 2) + err, line = th.App.BulkImport(th.Context, strings.NewReader(data3), false, 2) require.NotNil(t, err, "Should have failed due to missing version line on line 1.") require.Equal(t, 1, line, "Should have failed due to missing version line on line 1.") @@ -212,7 +212,7 @@ func TestImportBulkImport(t *testing.T) { {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}} {"type": "user", "user": {"username": "` + username + `", "email": "` + username + `@example.com", "teams": [{"name": "` + teamName + `","theme": "` + teamTheme1 + `", "channels": [{"name": "` + channelName + `"}]}]}} {"type": "post", "post": {"team": "` + teamName + `", "channel": "` + channelName + `", "user": "` + username + `", "message": "Hello World", "create_at": 123456789012}}` - err, line = th.App.BulkImport(strings.NewReader(data4+"\r\n"+posts), false, 2) + err, line = th.App.BulkImport(th.Context, strings.NewReader(data4+"\r\n"+posts), false, 2) require.Nil(t, err, "BulkImport should have succeeded") require.Equal(t, 0, line, "BulkImport line should be 0") }) @@ -220,7 +220,7 @@ func TestImportBulkImport(t *testing.T) { t.Run("First item after version without type", func(t *testing.T) { data := `{"type": "version", "version": 1} {"name": "custom-emoji-troll", "image": "bulkdata/emoji/trollolol.png"}` - err, line := th.App.BulkImport(strings.NewReader(data), false, 2) + err, line := th.App.BulkImport(th.Context, strings.NewReader(data), false, 2) require.NotNil(t, err, "Should have failed due to invalid type on line 2.") require.Equal(t, 2, line, "Should have failed due to invalid type on line 2.") }) @@ -234,7 +234,7 @@ func TestImportBulkImport(t *testing.T) { {"type": "direct_channel", "direct_channel": {"members": ["` + username + `", "` + username + `"]}} {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username + `"], "user": "` + username + `", "message": "Hello Direct Channel to myself", "create_at": 123456789014, "props":{"attachments":[{"id":0,"fallback":"[February 4th, 2020 2:46 PM] author: fallback","color":"D0D0D0","pretext":"","author_name":"author","author_link":"","title":"","title_link":"","text":"this post has props","fields":null,"image_url":"","thumb_url":"","footer":"Posted in #general","footer_icon":"","ts":"1580823992.000100"}]}}}}` - err, line := th.App.BulkImport(strings.NewReader(data6), false, 2) + err, line := th.App.BulkImport(th.Context, strings.NewReader(data6), false, 2) require.Nil(t, err, "BulkImport should have succeeded") require.Equal(t, 0, line, "BulkImport line should be 0") }) @@ -393,7 +393,7 @@ func BenchmarkBulkImport(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - err, _ := th.App.BulkImportWithPath(jsonFile, false, runtime.NumCPU(), dir) + err, _ := th.App.BulkImportWithPath(th.Context, jsonFile, false, runtime.NumCPU(), dir) require.Nil(b, err) } b.StopTimer() diff --git a/app/integration_action.go b/app/integration_action.go index fc4cf3ff80d..814bb6ce8d3 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -32,6 +32,7 @@ import ( "github.com/gorilla/mux" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -39,11 +40,11 @@ import ( "github.com/mattermost/mattermost-server/v5/utils" ) -func (a *App) DoPostAction(postID, actionId, userID, selectedOption string) (string, *model.AppError) { - return a.DoPostActionWithCookie(postID, actionId, userID, selectedOption, nil) +func (a *App) DoPostAction(c *request.Context, postID, actionId, userID, selectedOption string) (string, *model.AppError) { + return a.DoPostActionWithCookie(c, postID, actionId, userID, selectedOption, nil) } -func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) { +func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) { // PostAction may result in the original post being updated. For the // updated post, we need to unconditionally preserve the original @@ -235,13 +236,13 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st var resp *http.Response if strings.HasPrefix(upstreamURL, "/warn_metrics/") { - appErr = a.doLocalWarnMetricsRequest(upstreamURL, upstreamRequest) + appErr = a.doLocalWarnMetricsRequest(c, upstreamURL, upstreamRequest) if appErr != nil { return "", appErr } return "", nil } - resp, appErr = a.DoActionRequest(upstreamURL, upstreamRequest.ToJson()) + resp, appErr = a.DoActionRequest(c, upstreamURL, upstreamRequest.ToJson()) if appErr != nil { return "", appErr } @@ -269,7 +270,7 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st response.Update.IsPinned = originalIsPinned response.Update.HasReactions = originalHasReactions - if _, appErr = a.UpdatePost(response.Update, false); appErr != nil { + if _, appErr = a.UpdatePost(c, response.Update, false); appErr != nil { return "", appErr } } @@ -298,7 +299,7 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st // Perform an HTTP POST request to an integration's action endpoint. // Caller must consume and close returned http.Response as necessary. // For internal requests, requests are routed directly to a plugin ServerHTTP hook -func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) { +func (a *App) DoActionRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) { inURL, err := url.Parse(rawURL) if err != nil { return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, err.Error(), http.StatusBadRequest) @@ -306,7 +307,7 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode rawURLPath := path.Clean(rawURL) if strings.HasPrefix(rawURLPath, "/plugins/") || strings.HasPrefix(rawURLPath, "plugins/") { - return a.DoLocalRequest(rawURLPath, body) + return a.DoLocalRequest(c, rawURLPath, body) } req, err := http.NewRequest("POST", rawURL, bytes.NewReader(body)) @@ -321,7 +322,7 @@ 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) + req.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token) httpClient = a.HTTPService().MakeClient(true) } else { httpClient = a.HTTPService().MakeClient(false) @@ -362,7 +363,7 @@ func (w *LocalResponseWriter) WriteHeader(statusCode int) { w.status = statusCode } -func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []byte) (*http.Response, *model.AppError) { +func (a *App) doPluginRequest(c *request.Context, method, rawURL string, values url.Values, body []byte) (*http.Response, *model.AppError) { rawURL = strings.TrimPrefix(rawURL, "/") inURL, err := url.Parse(rawURL) if err != nil { @@ -405,8 +406,8 @@ func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []b if err != nil { return nil, model.NewAppError("doPluginRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) } - r.Header.Set("Mattermost-User-Id", a.Session().UserId) - r.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session().Token) + r.Header.Set("Mattermost-User-Id", c.Session().UserId) + r.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token) params := make(map[string]string) params["plugin_id"] = pluginID r = mux.SetURLVars(r, params) @@ -428,7 +429,7 @@ func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []b return resp, nil } -func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.PostActionIntegrationRequest) *model.AppError { +func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstreamRequest *model.PostActionIntegrationRequest) *model.AppError { _, err := url.Parse(rawURL) if err != nil { return model.NewAppError("doLocalWarnMetricsRequest", "api.post.do_action.action_integration.app_error", nil, err.Error(), http.StatusBadRequest) @@ -445,7 +446,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po return nil } - user, appErr := a.GetUser(a.Session().UserId) + user, appErr := a.GetUser(c.Session().UserId) if appErr != nil { return appErr } @@ -461,7 +462,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po botPost.Message = ":white_check_mark: " + warnMetricDisplayTexts.BotSuccessMessage if isE0Edition { - if appErr = a.RequestLicenseAndAckWarnMetric(warnMetricId, true); appErr != nil { + if appErr = a.RequestLicenseAndAckWarnMetric(c, warnMetricId, true); appErr != nil { botPost.Message = ":warning: " + i18n.T("api.server.warn_metric.bot_response.start_trial_failure.message") } } else { @@ -507,7 +508,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po } } - if _, err := a.CreatePostAsUser(botPost, a.Session().Id, true); err != nil { + if _, err := a.CreatePostAsUser(c, botPost, c.Session().Id, true); err != nil { return err } @@ -564,8 +565,8 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s return mailToLinkContent.ToJson() } -func (a *App) DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) { - return a.doPluginRequest("POST", rawURL, nil, body) +func (a *App) DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) { + return a.doPluginRequest(c, "POST", rawURL, nil, body) } func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError { @@ -585,7 +586,7 @@ func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppE return nil } -func (a *App) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { +func (a *App) SubmitInteractiveDialog(c *request.Context, request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { url := request.URL request.URL = "" request.Type = "dialog_submission" @@ -595,7 +596,7 @@ func (a *App) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model return nil, model.NewAppError("SubmitInteractiveDialog", "app.submit_interactive_dialog.json_error", nil, jsonErr.Error(), http.StatusBadRequest) } - resp, err := a.DoActionRequest(url, b) + resp, err := a.DoActionRequest(c, url, b) if err != nil { return nil, err } diff --git a/app/integration_action_test.go b/app/integration_action_test.go index c914d303e42..948b1151e1b 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -57,14 +57,14 @@ func TestPostActionInvalidURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) require.True(t, strings.Contains(err.Error(), "missing protocol scheme")) } @@ -157,7 +157,7 @@ func TestPostAction(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) @@ -194,7 +194,7 @@ func TestPostAction(t *testing.T) { }, } - post2, err := th.App.CreatePostAsUser(&menuPost, "", true) + post2, err := th.App.CreatePostAsUser(th.Context, &menuPost, "", true) require.Nil(t, err) attachments2, ok := post2.GetProp("attachments").([]*model.SlackAttachment) @@ -203,16 +203,16 @@ func TestPostAction(t *testing.T) { require.NotEmpty(t, attachments2[0].Actions) require.NotEmpty(t, attachments2[0].Actions[0].Id) - clientTriggerId, err := th.App.DoPostAction(post.Id, "notavalidid", th.BasicUser.Id, "") + clientTriggerId, err := th.App.DoPostAction(th.Context, post.Id, "notavalidid", th.BasicUser.Id, "") require.NotNil(t, err) assert.Equal(t, http.StatusNotFound, err.StatusCode) assert.True(t, clientTriggerId == "") - clientTriggerId, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + clientTriggerId, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) assert.True(t, len(clientTriggerId) == 26) - clientTriggerId, err = th.App.DoPostAction(post2.Id, attachments2[0].Actions[0].Id, th.BasicUser.Id, "selected") + clientTriggerId, err = th.App.DoPostAction(th.Context, post2.Id, attachments2[0].Actions[0].Id, th.BasicUser.Id, "selected") require.Nil(t, err) assert.True(t, len(clientTriggerId) == 26) @@ -220,7 +220,7 @@ func TestPostAction(t *testing.T) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "" }) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) require.True(t, strings.Contains(err.Error(), "address forbidden")) @@ -252,13 +252,13 @@ func TestPostAction(t *testing.T) { }, } - postplugin, err := th.App.CreatePostAsUser(&interactivePostPlugin, "", true) + postplugin, err := th.App.CreatePostAsUser(th.Context, &interactivePostPlugin, "", true) require.Nil(t, err) attachmentsPlugin, ok := postplugin.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) - _, err = th.App.DoPostAction(postplugin.Id, attachmentsPlugin[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, postplugin.Id, attachmentsPlugin[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) th.App.UpdateConfig(func(cfg *model.Config) { @@ -293,13 +293,13 @@ func TestPostAction(t *testing.T) { }, } - postSiteURL, err := th.App.CreatePostAsUser(&interactivePostSiteURL, "", true) + postSiteURL, err := th.App.CreatePostAsUser(th.Context, &interactivePostSiteURL, "", true) require.Nil(t, err) attachmentsSiteURL, ok := postSiteURL.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) - _, err = th.App.DoPostAction(postSiteURL.Id, attachmentsSiteURL[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, postSiteURL.Id, attachmentsSiteURL[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) require.False(t, strings.Contains(err.Error(), "address forbidden")) @@ -335,13 +335,13 @@ func TestPostAction(t *testing.T) { }, } - postSubpath, err := th.App.CreatePostAsUser(&interactivePostSubpath, "", true) + postSubpath, err := th.App.CreatePostAsUser(th.Context, &interactivePostSubpath, "", true) require.Nil(t, err) attachmentsSubpath, ok := postSubpath.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) - _, err = th.App.DoPostAction(postSubpath.Id, attachmentsSubpath[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, postSubpath.Id, attachmentsSubpath[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) }) @@ -410,12 +410,12 @@ func TestPostActionProps(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) - clientTriggerId, err := th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + clientTriggerId, err := th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) assert.True(t, len(clientTriggerId) == 26) @@ -506,7 +506,7 @@ func TestSubmitInteractiveDialog(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App) + `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context) hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin") require.NoError(t, err2) @@ -514,14 +514,14 @@ func TestSubmitInteractiveDialog(t *testing.T) { submit.URL = ts.URL - resp, err := th.App.SubmitInteractiveDialog(submit) + resp, err := th.App.SubmitInteractiveDialog(th.Context, submit) assert.Nil(t, err) require.NotNil(t, resp) assert.Equal(t, "some generic error", resp.Error) assert.Equal(t, "some error", resp.Errors["name1"]) submit.URL = "" - resp, err = th.App.SubmitInteractiveDialog(submit) + resp, err = th.App.SubmitInteractiveDialog(th.Context, submit) assert.NotNil(t, err) assert.Nil(t, resp) @@ -531,18 +531,18 @@ func TestSubmitInteractiveDialog(t *testing.T) { }) submit.URL = "/notvalid/myplugin/myaction" - resp, err = th.App.SubmitInteractiveDialog(submit) + resp, err = th.App.SubmitInteractiveDialog(th.Context, submit) assert.NotNil(t, err) require.Nil(t, resp) submit.URL = "/plugins/myplugin/myaction" - resp, err = th.App.SubmitInteractiveDialog(submit) + resp, err = th.App.SubmitInteractiveDialog(th.Context, submit) assert.Nil(t, err) require.NotNil(t, resp) assert.Equal(t, "some error", resp.Errors["name1"]) submit.URL = "/plugins/myplugin/myaction?abc=xyz" - resp, err = th.App.SubmitInteractiveDialog(submit) + resp, err = th.App.SubmitInteractiveDialog(th.Context, submit) assert.Nil(t, err) require.NotNil(t, resp) assert.Equal(t, "some other error", resp.Errors["name1"]) @@ -588,14 +588,14 @@ func TestPostActionRelativeURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) @@ -628,14 +628,14 @@ func TestPostActionRelativeURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) @@ -668,14 +668,14 @@ func TestPostActionRelativeURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) @@ -709,14 +709,14 @@ func TestPostActionRelativeURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) @@ -749,14 +749,14 @@ func TestPostActionRelativeURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) } @@ -788,7 +788,7 @@ func TestPostActionRelativePluginURL(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App) + `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context) hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin") require.NoError(t, err2) @@ -823,14 +823,14 @@ func TestPostActionRelativePluginURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.NotNil(t, err) }) @@ -863,14 +863,14 @@ func TestPostActionRelativePluginURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) }) @@ -903,14 +903,14 @@ func TestPostActionRelativePluginURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) }) @@ -943,14 +943,14 @@ func TestPostActionRelativePluginURL(t *testing.T) { }, } - post, err := th.App.CreatePostAsUser(&interactivePost, "", true) + post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true) require.Nil(t, err) attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment) require.True(t, ok) require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - _, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") + _, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "") require.Nil(t, err) }) } @@ -1007,53 +1007,53 @@ func TestDoPluginRequest(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App) + `, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context) hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin") require.NoError(t, err2) require.NotNil(t, hooks) - resp, err := th.App.doPluginRequest("GET", "/plugins/myplugin", nil, nil) + resp, err := th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", nil, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ := ioutil.ReadAll(resp.Body) assert.Equal(t, "could not find param abc=xyz", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz", nil, nil) + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz", nil, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ = ioutil.ReadAll(resp.Body) assert.Equal(t, "param multiple should have 3 values", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin", + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", url.Values{"abc": []string{"xyz"}, "multiple": []string{"1 first", "2 second", "3 third"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ = ioutil.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz&multiple=1%20first", + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first", url.Values{"multiple": []string{"2 second", "3 third"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ = ioutil.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third", + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third", url.Values{"multiple": []string{"2 second"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ = ioutil.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", url.Values{"multiple": []string{"2 second"}, "abc": []string{"xyz"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) body, _ = ioutil.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) - resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", + resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", url.Values{"multiple": []string{"4 fourth"}, "abc": []string{"xyz"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) diff --git a/app/layer_generators/opentracing_layer.go.tmpl b/app/layer_generators/opentracing_layer.go.tmpl index c441d4bace8..3b690bd96f4 100644 --- a/app/layer_generators/opentracing_layer.go.tmpl +++ b/app/layer_generators/opentracing_layer.go.tmpl @@ -19,14 +19,6 @@ type {{.Name}} struct { log *mlog.Logger notificationsLog *mlog.Logger - t i18n.TranslateFunc - session model.Session - requestId string - ipAddress string - path string - userAgent string - acceptLanguage string - accountMigration einterfaces.AccountMigrationInterface cluster einterfaces.ClusterInterface compliance einterfaces.ComplianceInterface @@ -42,7 +34,6 @@ type {{.Name}} struct { imageProxy *imageproxy.ImageProxy timezones *timezones.Timezones - context context.Context ctx context.Context } @@ -84,15 +75,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *{{.Name newApp.srv = childApp.Srv() newApp.log = childApp.Log() newApp.notificationsLog = childApp.NotificationsLog() - newApp.t = childApp.GetT() - if childApp.Session() != nil { - newApp.session = *childApp.Session() - } - newApp.requestId = childApp.RequestId() - newApp.ipAddress = childApp.IpAddress() - newApp.path = childApp.Path() - newApp.userAgent = childApp.UserAgent() - newApp.acceptLanguage = childApp.AcceptLanguage() newApp.accountMigration = childApp.AccountMigration() newApp.cluster = childApp.Cluster() newApp.compliance = childApp.Compliance() @@ -106,7 +88,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *{{.Name newApp.httpService = childApp.HTTPService() newApp.imageProxy = childApp.ImageProxy() newApp.timezones = childApp.Timezones() - newApp.context = childApp.Context() return &newApp } @@ -121,27 +102,6 @@ func (a *{{.Name}}) Log() *mlog.Logger { func (a *{{.Name}}) NotificationsLog() *mlog.Logger { return a.notificationsLog } -func (a *{{.Name}}) T(translationID string, args ...interface{}) string { - return a.t(translationID, args...) -} -func (a *{{.Name}}) Session() *model.Session { - return &a.session -} -func (a *{{.Name}}) RequestId() string { - return a.requestId -} -func (a *{{.Name}}) IpAddress() string { - return a.ipAddress -} -func (a *{{.Name}}) Path() string { - return a.path -} -func (a *{{.Name}}) UserAgent() string { - return a.userAgent -} -func (a *{{.Name}}) AcceptLanguage() string { - return a.acceptLanguage -} func (a *{{.Name}}) AccountMigration() einterfaces.AccountMigrationInterface { return a.accountMigration } @@ -178,36 +138,6 @@ func (a *{{.Name}}) ImageProxy() *imageproxy.ImageProxy { func (a *{{.Name}}) Timezones() *timezones.Timezones { return a.timezones } -func (a *{{.Name}}) Context() context.Context { - return a.context -} -func (a *{{.Name}}) SetSession(sess *model.Session) { - a.session = *sess -} -func (a *{{.Name}}) SetT(t i18n.TranslateFunc){ - a.t = t -} -func (a *{{.Name}}) SetRequestId(str string){ - a.requestId = str -} -func (a *{{.Name}}) SetIpAddress(str string){ - a.ipAddress = str -} -func (a *{{.Name}}) SetUserAgent(str string){ - a.userAgent = str -} -func (a *{{.Name}}) SetAcceptLanguage(str string) { - a.acceptLanguage = str -} -func (a *{{.Name}}) SetPath(str string){ - a.path = str -} -func (a *{{.Name}}) SetContext(c context.Context){ - a.context = c -} func (a *{{.Name}}) SetServer(srv *app.Server) { - a.srv = srv -} -func (a *{{.Name}}) GetT() i18n.TranslateFunc { - return a.t -} + a.srv = srv +} \ No newline at end of file diff --git a/app/login.go b/app/login.go index 18765958dbd..c9fb0603668 100644 --- a/app/login.go +++ b/app/login.go @@ -15,6 +15,7 @@ import ( "github.com/avct/uasurfer" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -41,7 +42,7 @@ func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) { return pem, subject, email } -func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) { +func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) { // Do statistics defer func() { if a.Metrics() != nil { @@ -111,7 +112,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken } // and then authenticate them - if user, err = a.authenticateUser(user, password, mfaToken); err != nil { + if user, err = a.authenticateUser(c, user, password, mfaToken); err != nil { return nil, err } @@ -154,10 +155,10 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) return nil, model.NewAppError("GetUserForLogin", "store.sql_user.get_for_login.app_error", nil, "", http.StatusBadRequest) } -func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError { +func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError { if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { var rejectionReason string - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { rejectionReason = hooks.UserWillLogIn(pluginContext, user) return rejectionReason == "" @@ -215,8 +216,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, w.Header().Set(model.HEADER_TOKEN, session.Token) - a.SetSession(session) - + c.SetSession(session) if a.Srv().License() != nil && *a.Srv().License().Features.LDAP && a.Ldap() != nil { userVal := *user sessionVal := *session @@ -227,7 +227,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLoggedIn(pluginContext, user) return true @@ -238,7 +238,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, return nil } -func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { +func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) { secure := false if GetProtocol(r) == "https" { secure = true @@ -251,7 +251,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: c.Session().Token, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -262,7 +262,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { userCookie := &http.Cookie{ Name: model.SESSION_COOKIE_USER, - Value: a.Session().UserId, + Value: c.Session().UserId, Path: subpath, MaxAge: maxAge, Expires: expiresAt, @@ -272,7 +272,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { csrfCookie := &http.Cookie{ Name: model.SESSION_COOKIE_CSRF, - Value: a.Session().GetCSRF(), + Value: c.Session().GetCSRF(), Path: subpath, MaxAge: maxAge, Expires: expiresAt, diff --git a/app/login_test.go b/app/login_test.go index b2a2a1bc657..2674b424a80 100644 --- a/app/login_test.go +++ b/app/login_test.go @@ -51,7 +51,7 @@ func TestCWSLogin(t *testing.T) { token := model.NewToken(TokenTypeCWSAccess, "") defer th.App.DeleteToken(token) os.Setenv("CWS_CLOUD_TOKEN", token.Token) - user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false) + user, err := th.App.AuthenticateUserForLogin(th.Context, "", th.BasicUser.Username, "", "", token.Token, false) require.Nil(t, err) require.NotNil(t, user) require.Equal(t, th.BasicUser.Username, user.Username) @@ -65,7 +65,7 @@ func TestCWSLogin(t *testing.T) { os.Setenv("CWS_CLOUD_TOKEN", token.Token) require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false) + user, err := th.App.AuthenticateUserForLogin(th.Context, "", th.BasicUser.Username, "", "", token.Token, false) require.NotNil(t, err) require.Nil(t, user) }) diff --git a/app/migrations.go b/app/migrations.go index f06c0946e06..3486e76a574 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -20,25 +20,29 @@ const ContentExtractionConfigDefaultTrueMigrationKey = "ContentExtractionConfigD // This function migrates the default built in roles from code/config to the database. func (a *App) DoAdvancedPermissionsMigration() { + a.Srv().doAdvancedPermissionsMigration() +} + +func (s *Server) doAdvancedPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := s.Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { return } mlog.Info("Migrating roles to database.") roles := model.MakeDefaultRoles() - roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.Srv().License() != nil) + roles = utils.SetRolePermissionsFromConfig(roles, s.Config(), s.License() != nil) allSucceeded := true for _, role := range roles { - _, err := a.Srv().Store.Role().Save(role) + _, err := s.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(context.Background(), role.Name) + fetchedRole, err := s.Store.Role().GetByName(context.Background(), role.Name) if err != nil { mlog.Critical("Failed to migrate role to database.", mlog.Err(err)) allSucceeded = false @@ -51,7 +55,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 = s.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 @@ -63,10 +67,10 @@ func (a *App) DoAdvancedPermissionsMigration() { return } - config := a.Config() + config := s.Config() if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.ALLOW_EDIT_POST_ALWAYS { *config.ServiceSettings.PostEditTimeLimit = -1 - if err := a.SaveConfig(config, true); err != nil { + if err := s.SaveConfig(config, true); err != nil { mlog.Error("Failed to update config in Advanced Permissions Phase 1 Migration.", mlog.Err(err)) } } @@ -76,7 +80,7 @@ func (a *App) DoAdvancedPermissionsMigration() { Value: "true", } - if err := a.Srv().Store.System().Save(&system); err != nil { + if err := s.Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark advanced permissions migration as completed.", mlog.Err(err)) } } @@ -92,8 +96,12 @@ func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error { } func (a *App) DoEmojisPermissionsMigration() { + a.Srv().doEmojisPermissionsMigration() +} + +func (s *Server) doEmojisPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil { + if _, err := s.Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil { return } @@ -102,15 +110,15 @@ func (a *App) DoEmojisPermissionsMigration() { var err *model.AppError mlog.Info("Migrating emojis config to database.") - switch *a.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation { + switch *s.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation { case model.RESTRICT_EMOJI_CREATION_ALL: - role, err = a.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) + role, err = s.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } case model.RESTRICT_EMOJI_CREATION_ADMIN: - role, err = a.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID) + role, err = s.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return @@ -124,13 +132,13 @@ func (a *App) DoEmojisPermissionsMigration() { if role != nil { role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id) - if _, nErr := a.Srv().Store.Role().Save(role); nErr != nil { + if _, nErr := s.Store.Role().Save(role); nErr != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(nErr)) return } } - systemAdminRole, err = a.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) + systemAdminRole, err = s.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID) if err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return @@ -141,7 +149,7 @@ func (a *App) DoEmojisPermissionsMigration() { model.PERMISSION_DELETE_EMOJIS.Id, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id, ) - if _, err := a.Srv().Store.Role().Save(systemAdminRole); err != nil { + if _, err := s.Store.Role().Save(systemAdminRole); err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } @@ -151,40 +159,44 @@ func (a *App) DoEmojisPermissionsMigration() { Value: "true", } - if err := a.Srv().Store.System().Save(&system); err != nil { + if err := s.Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark emojis permissions migration as completed.", mlog.Err(err)) } } func (a *App) DoGuestRolesCreationMigration() { + a.Srv().doGuestRolesCreationMigration() +} + +func (s *Server) doGuestRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil { + if _, err := s.Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil { 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 := s.Store.Scheme().GetAllPage("", 0, 1000000) if err != nil { mlog.Critical("Failed to get all schemes.", mlog.Err(err)) allSucceeded = false @@ -200,7 +212,7 @@ func (a *App) DoGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := a.Srv().Store.Role().Save(teamGuestRole); err != nil { + if savedRole, err := s.Store.Role().Save(teamGuestRole); err != nil { mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -216,14 +228,14 @@ func (a *App) DoGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := a.Srv().Store.Role().Save(channelGuestRole); err != nil { + if savedRole, err := s.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 := s.Store.Scheme().Save(scheme) if err != nil { mlog.Critical("Failed to update custom scheme.", mlog.Err(err)) allSucceeded = false @@ -240,34 +252,38 @@ func (a *App) DoGuestRolesCreationMigration() { Value: "true", } - if err := a.Srv().Store.System().Save(&system); err != nil { + if err := s.Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark guest roles creation migration as completed.", mlog.Err(err)) } } func (a *App) DoSystemConsoleRolesCreationMigration() { + a.Srv().doSystemConsoleRolesCreationMigration() +} + +func (s *Server) doSystemConsoleRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil { + if _, err := s.Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_MANAGER_ROLE_ID)) allSucceeded = false } } - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID)) allSucceeded = false } } - if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil { - if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil { + if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil { + if _, err := s.Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_USER_MANAGER_ROLE_ID)) allSucceeded = false } @@ -282,18 +298,18 @@ func (a *App) DoSystemConsoleRolesCreationMigration() { Value: "true", } - if err := a.Srv().Store.System().Save(&system); err != nil { + if err := s.Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark system console roles creation migration as completed.", mlog.Err(err)) } } -func (a *App) doContentExtractionConfigDefaultTrueMigration() { +func (s *Server) doContentExtractionConfigDefaultTrueMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil { + if _, err := s.Store.System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil { return } - a.UpdateConfig(func(config *model.Config) { + s.UpdateConfig(func(config *model.Config) { config.FileSettings.ExtractContent = model.NewBool(true) }) @@ -302,21 +318,25 @@ func (a *App) doContentExtractionConfigDefaultTrueMigration() { Value: "true", } - if err := a.Srv().Store.System().Save(&system); err != nil { + if err := s.Store.System().Save(&system); err != nil { mlog.Critical("Failed to mark content extraction config migration as completed.", mlog.Err(err)) } } func (a *App) DoAppMigrations() { - a.DoAdvancedPermissionsMigration() - a.DoEmojisPermissionsMigration() - a.DoGuestRolesCreationMigration() - a.DoSystemConsoleRolesCreationMigration() + a.Srv().doAppMigrations() +} + +func (s *Server) doAppMigrations() { + s.doAdvancedPermissionsMigration() + s.doEmojisPermissionsMigration() + s.doGuestRolesCreationMigration() + s.doSystemConsoleRolesCreationMigration() // This migration always must be the last, because can be based on previous // migrations. For example, it needs the guest roles migration. - err := a.DoPermissionsMigrations() + err := s.doPermissionsMigrations() if err != nil { mlog.Critical("(app.App).DoPermissionsMigrations failed", mlog.Err(err)) } - a.doContentExtractionConfigDefaultTrueMigration() + s.doContentExtractionConfigDefaultTrueMigration() } diff --git a/app/notification_push_test.go b/app/notification_push_test.go index 3497ca9b27e..28dd6f195f6 100644 --- a/app/notification_push_test.go +++ b/app/notification_push_test.go @@ -1283,7 +1283,7 @@ func TestAllPushNotifications(t *testing.T) { ExpiresAt: model.GetMillis() + 100000, }) require.Nil(t, err) - _, err = th.App.AddTeamMember(th.BasicTeam.Id, u.Id) + _, err = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, u.Id) require.Nil(t, err) th.AddUserToChannel(u, th.BasicChannel) testData = append(testData, userSession{ diff --git a/app/notification_test.go b/app/notification_test.go index d373a35232b..981f3bca2b8 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -21,7 +21,7 @@ func TestSendNotifications(t *testing.T) { th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false) - post1, appErr := th.App.CreatePostMissingChannel(&model.Post{ + post1, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@" + th.BasicUser2.Username, @@ -35,10 +35,10 @@ func TestSendNotifications(t *testing.T) { require.NotNil(t, mentions) require.True(t, utils.StringInSlice(th.BasicUser2.Id, mentions), "mentions", mentions) - dm, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + dm, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, appErr) - post2, appErr := th.App.CreatePostMissingChannel(&model.Post{ + post2, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -49,12 +49,12 @@ func TestSendNotifications(t *testing.T) { require.NoError(t, err) require.NotNil(t, mentions) - _, appErr = th.App.UpdateActive(th.BasicUser2, false) + _, appErr = th.App.UpdateActive(th.Context, th.BasicUser2, false) require.Nil(t, appErr) appErr = th.App.Srv().InvalidateAllCaches() require.Nil(t, appErr) - post3, appErr := th.App.CreatePostMissingChannel(&model.Post{ + post3, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -81,7 +81,7 @@ func TestSendNotifications(t *testing.T) { Props: model.StringInterface{"from_webhook": "true", "override_username": "a bot"}, } - rootPost, appErr = th.App.CreatePostMissingChannel(rootPost, false) + rootPost, appErr = th.App.CreatePostMissingChannel(th.Context, rootPost, false) require.Nil(t, appErr) childPost := &model.Post{ @@ -90,7 +90,7 @@ func TestSendNotifications(t *testing.T) { RootId: rootPost.Id, Message: "a reply", } - childPost, appErr = th.App.CreatePostMissingChannel(childPost, false) + childPost, appErr = th.App.CreatePostMissingChannel(th.Context, childPost, false) require.Nil(t, appErr) postList := model.PostList{ @@ -130,7 +130,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { users = append(users, user) } - _, appErr1 := th.App.CreatePostMissingChannel(&model.Post{ + _, appErr1 := th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@channel", @@ -150,7 +150,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { } }) - _, appErr1 = th.App.CreatePostMissingChannel(&model.Post{ + _, appErr1 = th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@channel", @@ -213,7 +213,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) { guest := th.CreateGuest() user4 := th.CreateUser() guestAndUser4Channel := th.CreateChannel(th.BasicTeam) - defer th.App.PermanentDeleteUser(guest) + defer th.App.PermanentDeleteUser(th.Context, guest) th.LinkUserToTeam(user3, th.BasicTeam) th.LinkUserToTeam(user4, th.BasicTeam) th.LinkUserToTeam(guest, th.BasicTeam) @@ -289,7 +289,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) { t.Run("should not return inactive users", func(t *testing.T) { inactiveUser := th.CreateUser() - inactiveUser, appErr := th.App.UpdateActive(inactiveUser, false) + inactiveUser, appErr := th.App.UpdateActive(th.Context, inactiveUser, false) require.Nil(t, appErr) post := &model.Post{} diff --git a/app/oauth.go b/app/oauth.go index c4d12cc42c3..65e7f980f42 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -546,22 +547,22 @@ func (a *App) RevokeAccessToken(token string) *model.AppError { return nil } -func (a *App) CompleteOAuth(service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *App) CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) { defer body.Close() action := props["action"] switch action { case model.OAUTH_ACTION_SIGNUP: - return a.CreateOAuthUser(service, body, teamID, tokenUser) + return a.CreateOAuthUser(c, service, body, teamID, tokenUser) case model.OAUTH_ACTION_LOGIN: - return a.LoginByOAuth(service, body, teamID, tokenUser) + return a.LoginByOAuth(c, service, body, teamID, tokenUser) case model.OAUTH_ACTION_EMAIL_TO_SSO: return a.CompleteSwitchWithOAuth(service, body, props["email"], tokenUser) case model.OAUTH_ACTION_SSO_TO_EMAIL: - return a.LoginByOAuth(service, body, teamID, tokenUser) + return a.LoginByOAuth(c, service, body, teamID, tokenUser) default: - return a.LoginByOAuth(service, body, teamID, tokenUser) + return a.LoginByOAuth(c, service, body, teamID, tokenUser) } } @@ -582,7 +583,7 @@ func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model. return provider, nil } -func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { provider, e := a.getSSOProvider(service) if e != nil { return nil, e @@ -608,7 +609,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, to user, err := a.GetUserByAuth(model.NewString(*authUser.AuthData), service) if err != nil { if err.Id == MissingAuthAccountError { - user, err = a.CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamID, tokenUser) + user, err = a.CreateOAuthUser(c, service, bytes.NewReader(buf.Bytes()), teamID, tokenUser) } else { return nil, err } @@ -624,7 +625,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, to return nil, err } if teamID != "" { - err = a.AddUserToTeamByTeamId(teamID, user) + err = a.AddUserToTeamByTeamId(c, teamID, user) } } diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 4ed38fc7eb3..202d72bea89 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -19,6 +19,7 @@ import ( "github.com/dyatlov/go-opengraph/opengraph" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" @@ -45,14 +46,6 @@ type OpenTracingAppLayer struct { log *mlog.Logger notificationsLog *mlog.Logger - t i18n.TranslateFunc - session model.Session - requestId string - ipAddress string - path string - userAgent string - acceptLanguage string - accountMigration einterfaces.AccountMigrationInterface cluster einterfaces.ClusterInterface compliance einterfaces.ComplianceInterface @@ -68,8 +61,7 @@ type OpenTracingAppLayer struct { imageProxy *imageproxy.ImageProxy timezones *timezones.Timezones - context context.Context - ctx context.Context + ctx context.Context } func (a *OpenTracingAppLayer) ActivateMfa(userID string, token string) *model.AppError { @@ -94,7 +86,7 @@ func (a *OpenTracingAppLayer) ActivateMfa(userID string, token string) *model.Ap return resultVar0 } -func (a *OpenTracingAppLayer) AddChannelMember(userID string, channel *model.Channel, opts app.ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts app.ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddChannelMember") @@ -106,7 +98,7 @@ func (a *OpenTracingAppLayer) AddChannelMember(userID string, channel *model.Cha }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddChannelMember(userID, channel, opts) + resultVar0, resultVar1 := a.app.AddChannelMember(c, userID, channel, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -391,7 +383,7 @@ func (a *OpenTracingAppLayer) AddStatusCacheSkipClusterSend(status *model.Status a.app.AddStatusCacheSkipClusterSend(status) } -func (a *OpenTracingAppLayer) AddTeamMember(teamID string, userID string) (*model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddTeamMember(c *request.Context, teamID string, userID string) (*model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMember") @@ -403,7 +395,7 @@ func (a *OpenTracingAppLayer) AddTeamMember(teamID string, userID string) (*mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddTeamMember(teamID, userID) + resultVar0, resultVar1 := a.app.AddTeamMember(c, teamID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -413,7 +405,7 @@ func (a *OpenTracingAppLayer) AddTeamMember(teamID string, userID string) (*mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AddTeamMemberByInviteId(inviteId string, userID string) (*model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddTeamMemberByInviteId(c *request.Context, inviteId string, userID string) (*model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMemberByInviteId") @@ -425,7 +417,7 @@ func (a *OpenTracingAppLayer) AddTeamMemberByInviteId(inviteId string, userID st }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddTeamMemberByInviteId(inviteId, userID) + resultVar0, resultVar1 := a.app.AddTeamMemberByInviteId(c, inviteId, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -435,7 +427,7 @@ func (a *OpenTracingAppLayer) AddTeamMemberByInviteId(inviteId string, userID st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AddTeamMemberByToken(userID string, tokenID string) (*model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddTeamMemberByToken(c *request.Context, userID string, tokenID string) (*model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMemberByToken") @@ -447,7 +439,7 @@ func (a *OpenTracingAppLayer) AddTeamMemberByToken(userID string, tokenID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddTeamMemberByToken(userID, tokenID) + resultVar0, resultVar1 := a.app.AddTeamMemberByToken(c, userID, tokenID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -457,7 +449,7 @@ func (a *OpenTracingAppLayer) AddTeamMemberByToken(userID string, tokenID string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AddTeamMembers(teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) { +func (a *OpenTracingAppLayer) AddTeamMembers(c *request.Context, teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMembers") @@ -469,7 +461,7 @@ func (a *OpenTracingAppLayer) AddTeamMembers(teamID string, userIDs []string, us }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddTeamMembers(teamID, userIDs, userRequestorId, graceful) + resultVar0, resultVar1 := a.app.AddTeamMembers(c, teamID, userIDs, userRequestorId, graceful) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -523,7 +515,7 @@ func (a *OpenTracingAppLayer) AddUserToChannel(user *model.User, channel *model. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AddUserToTeam(teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddUserToTeam(c *request.Context, teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeam") @@ -535,7 +527,7 @@ func (a *OpenTracingAppLayer) AddUserToTeam(teamID string, userID string, userRe }() defer span.Finish() - resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeam(teamID, userID, userRequestorId) + resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeam(c, teamID, userID, userRequestorId) if resultVar2 != nil { span.LogFields(spanlog.Error(resultVar2)) @@ -545,7 +537,7 @@ func (a *OpenTracingAppLayer) AddUserToTeam(teamID string, userID string, userRe return resultVar0, resultVar1, resultVar2 } -func (a *OpenTracingAppLayer) AddUserToTeamByInviteId(inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddUserToTeamByInviteId(c *request.Context, inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByInviteId") @@ -557,7 +549,7 @@ func (a *OpenTracingAppLayer) AddUserToTeamByInviteId(inviteId string, userID st }() defer span.Finish() - resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeamByInviteId(inviteId, userID) + resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeamByInviteId(c, inviteId, userID) if resultVar2 != nil { span.LogFields(spanlog.Error(resultVar2)) @@ -567,7 +559,7 @@ func (a *OpenTracingAppLayer) AddUserToTeamByInviteId(inviteId string, userID st return resultVar0, resultVar1, resultVar2 } -func (a *OpenTracingAppLayer) AddUserToTeamByTeamId(teamID string, user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) AddUserToTeamByTeamId(c *request.Context, teamID string, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByTeamId") @@ -579,7 +571,7 @@ func (a *OpenTracingAppLayer) AddUserToTeamByTeamId(teamID string, user *model.U }() defer span.Finish() - resultVar0 := a.app.AddUserToTeamByTeamId(teamID, user) + resultVar0 := a.app.AddUserToTeamByTeamId(c, teamID, user) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -589,7 +581,7 @@ func (a *OpenTracingAppLayer) AddUserToTeamByTeamId(teamID string, user *model.U return resultVar0 } -func (a *OpenTracingAppLayer) AddUserToTeamByToken(userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddUserToTeamByToken(c *request.Context, userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByToken") @@ -601,7 +593,7 @@ func (a *OpenTracingAppLayer) AddUserToTeamByToken(userID string, tokenID string }() defer span.Finish() - resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeamByToken(userID, tokenID) + resultVar0, resultVar1, resultVar2 := a.app.AddUserToTeamByToken(c, userID, tokenID) if resultVar2 != nil { span.LogFields(spanlog.Error(resultVar2)) @@ -716,7 +708,7 @@ func (a *OpenTracingAppLayer) AttachDeviceId(sessionID string, deviceID string, return resultVar0 } -func (a *OpenTracingAppLayer) AttachSessionCookies(w http.ResponseWriter, r *http.Request) { +func (a *OpenTracingAppLayer) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AttachSessionCookies") @@ -728,10 +720,10 @@ func (a *OpenTracingAppLayer) AttachSessionCookies(w http.ResponseWriter, r *htt }() defer span.Finish() - a.app.AttachSessionCookies(w, r) + a.app.AttachSessionCookies(c, w, r) } -func (a *OpenTracingAppLayer) AuthenticateUserForLogin(id string, loginId string, password string, mfaToken string, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) { +func (a *OpenTracingAppLayer) AuthenticateUserForLogin(c *request.Context, id string, loginId string, password string, mfaToken string, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AuthenticateUserForLogin") @@ -743,7 +735,7 @@ func (a *OpenTracingAppLayer) AuthenticateUserForLogin(id string, loginId string }() defer span.Finish() - resultVar0, resultVar1 := a.app.AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken, ldapOnly) + resultVar0, resultVar1 := a.app.AuthenticateUserForLogin(c, id, loginId, password, mfaToken, cwsToken, ldapOnly) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -966,7 +958,7 @@ func (a *OpenTracingAppLayer) BulkExport(writer io.Writer, outPath string, opts return resultVar0 } -func (a *OpenTracingAppLayer) BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { +func (a *OpenTracingAppLayer) BulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BulkImport") @@ -978,7 +970,7 @@ func (a *OpenTracingAppLayer) BulkImport(fileReader io.Reader, dryRun bool, work }() defer span.Finish() - resultVar0, resultVar1 := a.app.BulkImport(fileReader, dryRun, workers) + resultVar0, resultVar1 := a.app.BulkImport(c, fileReader, dryRun, workers) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -988,7 +980,7 @@ func (a *OpenTracingAppLayer) BulkImport(fileReader io.Reader, dryRun bool, work return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) BulkImportWithPath(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { +func (a *OpenTracingAppLayer) BulkImportWithPath(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BulkImportWithPath") @@ -1000,7 +992,7 @@ func (a *OpenTracingAppLayer) BulkImportWithPath(fileReader io.Reader, dryRun bo }() defer span.Finish() - resultVar0, resultVar1 := a.app.BulkImportWithPath(fileReader, dryRun, workers, importPath) + resultVar0, resultVar1 := a.app.BulkImportWithPath(c, fileReader, dryRun, workers, importPath) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -1098,7 +1090,7 @@ func (a *OpenTracingAppLayer) ChannelMembersToRemove(teamID *string) ([]*model.C return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CheckAndSendUserLimitWarningEmails() *model.AppError { +func (a *OpenTracingAppLayer) CheckAndSendUserLimitWarningEmails(c *request.Context) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckAndSendUserLimitWarningEmails") @@ -1110,7 +1102,7 @@ func (a *OpenTracingAppLayer) CheckAndSendUserLimitWarningEmails() *model.AppErr }() defer span.Finish() - resultVar0 := a.app.CheckAndSendUserLimitWarningEmails() + resultVar0 := a.app.CheckAndSendUserLimitWarningEmails(c) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -1571,7 +1563,7 @@ func (a *OpenTracingAppLayer) CompareAndSetPluginKey(pluginID string, key string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CompleteOAuth(service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompleteOAuth") @@ -1583,7 +1575,7 @@ func (a *OpenTracingAppLayer) CompleteOAuth(service string, body io.ReadCloser, }() defer span.Finish() - resultVar0, resultVar1 := a.app.CompleteOAuth(service, body, teamID, props, tokenUser) + resultVar0, resultVar1 := a.app.CompleteOAuth(c, service, body, teamID, props, tokenUser) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1698,7 +1690,7 @@ func (a *OpenTracingAppLayer) CopyFileInfos(userID string, fileIDs []string) ([] return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { +func (a *OpenTracingAppLayer) CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateBot") @@ -1710,7 +1702,7 @@ func (a *OpenTracingAppLayer) CreateBot(bot *model.Bot) (*model.Bot, *model.AppE }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateBot(bot) + resultVar0, resultVar1 := a.app.CreateBot(c, bot) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1720,7 +1712,7 @@ func (a *OpenTracingAppLayer) CreateBot(bot *model.Bot) (*model.Bot, *model.AppE return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannel") @@ -1732,7 +1724,7 @@ func (a *OpenTracingAppLayer) CreateChannel(channel *model.Channel, addMember bo }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateChannel(channel, addMember) + resultVar0, resultVar1 := a.app.CreateChannel(c, channel, addMember) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1764,7 +1756,7 @@ func (a *OpenTracingAppLayer) CreateChannelScheme(channel *model.Channel) (*mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateChannelWithUser(channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannelWithUser") @@ -1776,7 +1768,7 @@ func (a *OpenTracingAppLayer) CreateChannelWithUser(channel *model.Channel, user }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateChannelWithUser(channel, userID) + resultVar0, resultVar1 := a.app.CreateChannelWithUser(c, channel, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1808,7 +1800,7 @@ func (a *OpenTracingAppLayer) CreateCommand(cmd *model.Command) (*model.Command, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateCommandPost(post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateCommandPost") @@ -1824,7 +1816,7 @@ func (a *OpenTracingAppLayer) CreateCommandPost(post *model.Post, teamID string, span.SetTag("skipSlackParsing", skipSlackParsing) defer span.Finish() - resultVar0, resultVar1 := a.app.CreateCommandPost(post, teamID, response, skipSlackParsing) + resultVar0, resultVar1 := a.app.CreateCommandPost(c, post, teamID, response, skipSlackParsing) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1856,7 +1848,7 @@ func (a *OpenTracingAppLayer) CreateCommandWebhook(commandID string, args *model return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateDefaultChannels(c *request.Context, teamID string) ([]*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateDefaultChannels") @@ -1868,7 +1860,7 @@ func (a *OpenTracingAppLayer) CreateDefaultChannels(teamID string) ([]*model.Cha }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateDefaultChannels(teamID) + resultVar0, resultVar1 := a.app.CreateDefaultChannels(c, teamID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1878,7 +1870,7 @@ func (a *OpenTracingAppLayer) CreateDefaultChannels(teamID string) ([]*model.Cha return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateDefaultMemberships(since int64, includeRemovedMembers bool) error { +func (a *OpenTracingAppLayer) CreateDefaultMemberships(c *request.Context, since int64, includeRemovedMembers bool) error { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateDefaultMemberships") @@ -1890,7 +1882,7 @@ func (a *OpenTracingAppLayer) CreateDefaultMemberships(since int64, includeRemov }() defer span.Finish() - resultVar0 := a.app.CreateDefaultMemberships(since, includeRemovedMembers) + resultVar0 := a.app.CreateDefaultMemberships(c, since, includeRemovedMembers) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -1966,7 +1958,7 @@ func (a *OpenTracingAppLayer) CreateGroupChannel(userIDs []string, creatorId str return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateGuest(user *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateGuest(c *request.Context, user *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGuest") @@ -1978,7 +1970,7 @@ func (a *OpenTracingAppLayer) CreateGuest(user *model.User) (*model.User, *model }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateGuest(user) + resultVar0, resultVar1 := a.app.CreateGuest(c, user) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2076,7 +2068,7 @@ func (a *OpenTracingAppLayer) CreateOAuthStateToken(extra string) (*model.Token, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateOAuthUser(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateOAuthUser(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateOAuthUser") @@ -2088,7 +2080,7 @@ func (a *OpenTracingAppLayer) CreateOAuthUser(service string, userData io.Reader }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateOAuthUser(service, userData, teamID, tokenUser) + resultVar0, resultVar1 := a.app.CreateOAuthUser(c, service, userData, teamID, tokenUser) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2142,7 +2134,7 @@ func (a *OpenTracingAppLayer) CreatePasswordRecoveryToken(userID string, email s return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) { +func (a *OpenTracingAppLayer) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePost") @@ -2154,7 +2146,7 @@ func (a *OpenTracingAppLayer) CreatePost(post *model.Post, channel *model.Channe }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreatePost(post, channel, triggerWebhooks, setOnline) + resultVar0, resultVar1 := a.app.CreatePost(c, post, channel, triggerWebhooks, setOnline) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2164,7 +2156,7 @@ func (a *OpenTracingAppLayer) CreatePost(post *model.Post, channel *model.Channe return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePostAsUser") @@ -2176,7 +2168,7 @@ func (a *OpenTracingAppLayer) CreatePostAsUser(post *model.Post, currentSessionI }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreatePostAsUser(post, currentSessionId, setOnline) + resultVar0, resultVar1 := a.app.CreatePostAsUser(c, post, currentSessionId, setOnline) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2186,7 +2178,7 @@ func (a *OpenTracingAppLayer) CreatePostAsUser(post *model.Post, currentSessionI return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePostMissingChannel") @@ -2198,7 +2190,7 @@ func (a *OpenTracingAppLayer) CreatePostMissingChannel(post *model.Post, trigger }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreatePostMissingChannel(post, triggerWebhooks) + resultVar0, resultVar1 := a.app.CreatePostMissingChannel(c, post, triggerWebhooks) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2318,7 +2310,7 @@ func (a *OpenTracingAppLayer) CreateSidebarCategory(userID string, teamID string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { +func (a *OpenTracingAppLayer) CreateTeam(c *request.Context, team *model.Team) (*model.Team, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateTeam") @@ -2330,7 +2322,7 @@ func (a *OpenTracingAppLayer) CreateTeam(team *model.Team) (*model.Team, *model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateTeam(team) + resultVar0, resultVar1 := a.app.CreateTeam(c, team) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2340,7 +2332,7 @@ func (a *OpenTracingAppLayer) CreateTeam(team *model.Team) (*model.Team, *model. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateTeamWithUser(team *model.Team, userID string) (*model.Team, *model.AppError) { +func (a *OpenTracingAppLayer) CreateTeamWithUser(c *request.Context, team *model.Team, userID string) (*model.Team, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateTeamWithUser") @@ -2352,7 +2344,7 @@ func (a *OpenTracingAppLayer) CreateTeamWithUser(team *model.Team, userID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateTeamWithUser(team, userID) + resultVar0, resultVar1 := a.app.CreateTeamWithUser(c, team, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2406,7 +2398,7 @@ func (a *OpenTracingAppLayer) CreateUploadSession(us *model.UploadSession) (*mod return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUser(user *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUser(c *request.Context, user *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUser") @@ -2418,7 +2410,7 @@ func (a *OpenTracingAppLayer) CreateUser(user *model.User) (*model.User, *model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUser(user) + resultVar0, resultVar1 := a.app.CreateUser(c, user) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2450,7 +2442,7 @@ func (a *OpenTracingAppLayer) CreateUserAccessToken(token *model.UserAccessToken return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUserAsAdmin(user *model.User, redirect string) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUserAsAdmin(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserAsAdmin") @@ -2462,7 +2454,7 @@ func (a *OpenTracingAppLayer) CreateUserAsAdmin(user *model.User, redirect strin }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUserAsAdmin(user, redirect) + resultVar0, resultVar1 := a.app.CreateUserAsAdmin(c, user, redirect) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2472,7 +2464,7 @@ func (a *OpenTracingAppLayer) CreateUserAsAdmin(user *model.User, redirect strin return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUserFromSignup(user *model.User, redirect string) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUserFromSignup(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserFromSignup") @@ -2484,7 +2476,7 @@ func (a *OpenTracingAppLayer) CreateUserFromSignup(user *model.User, redirect st }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUserFromSignup(user, redirect) + resultVar0, resultVar1 := a.app.CreateUserFromSignup(c, user, redirect) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2494,7 +2486,7 @@ func (a *OpenTracingAppLayer) CreateUserFromSignup(user *model.User, redirect st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUserWithInviteId(user *model.User, inviteId string, redirect string) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUserWithInviteId(c *request.Context, user *model.User, inviteId string, redirect string) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserWithInviteId") @@ -2506,7 +2498,7 @@ func (a *OpenTracingAppLayer) CreateUserWithInviteId(user *model.User, inviteId }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUserWithInviteId(user, inviteId, redirect) + resultVar0, resultVar1 := a.app.CreateUserWithInviteId(c, user, inviteId, redirect) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2516,7 +2508,7 @@ func (a *OpenTracingAppLayer) CreateUserWithInviteId(user *model.User, inviteId return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUserWithToken(c *request.Context, user *model.User, token *model.Token) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserWithToken") @@ -2528,7 +2520,7 @@ func (a *OpenTracingAppLayer) CreateUserWithToken(user *model.User, token *model }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUserWithToken(user, token) + resultVar0, resultVar1 := a.app.CreateUserWithToken(c, user, token) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2538,7 +2530,7 @@ func (a *OpenTracingAppLayer) CreateUserWithToken(user *model.User, token *model return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateWebhookPost(userID string, channel *model.Channel, text string, overrideUsername string, overrideIconURL string, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text string, overrideUsername string, overrideIconURL string, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateWebhookPost") @@ -2550,7 +2542,7 @@ func (a *OpenTracingAppLayer) CreateWebhookPost(userID string, channel *model.Ch }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateWebhookPost(userID, channel, text, overrideUsername, overrideIconURL, overrideIconEmoji, props, postType, postRootId) + resultVar0, resultVar1 := a.app.CreateWebhookPost(c, userID, channel, text, overrideUsername, overrideIconURL, overrideIconEmoji, props, postType, postRootId) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2626,7 +2618,7 @@ func (a *OpenTracingAppLayer) DBHealthCheckWrite() error { return resultVar0 } -func (a *OpenTracingAppLayer) DeactivateGuests() *model.AppError { +func (a *OpenTracingAppLayer) DeactivateGuests(c *request.Context) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeactivateGuests") @@ -2638,7 +2630,7 @@ func (a *OpenTracingAppLayer) DeactivateGuests() *model.AppError { }() defer span.Finish() - resultVar0 := a.app.DeactivateGuests() + resultVar0 := a.app.DeactivateGuests(c) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -2797,7 +2789,7 @@ func (a *OpenTracingAppLayer) DeleteBrandImage() *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) DeleteChannel(channel *model.Channel, userID string) *model.AppError { +func (a *OpenTracingAppLayer) DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteChannel") @@ -2809,7 +2801,7 @@ func (a *OpenTracingAppLayer) DeleteChannel(channel *model.Channel, userID strin }() defer span.Finish() - resultVar0 := a.app.DeleteChannel(channel, userID) + resultVar0 := a.app.DeleteChannel(c, channel, userID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -2959,7 +2951,7 @@ func (a *OpenTracingAppLayer) DeleteGroup(groupID string) (*model.Group, *model. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) DeleteGroupConstrainedMemberships() error { +func (a *OpenTracingAppLayer) DeleteGroupConstrainedMemberships(c *request.Context) error { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroupConstrainedMemberships") @@ -2971,7 +2963,7 @@ func (a *OpenTracingAppLayer) DeleteGroupConstrainedMemberships() error { }() defer span.Finish() - resultVar0 := a.app.DeleteGroupConstrainedMemberships() + resultVar0 := a.app.DeleteGroupConstrainedMemberships(c) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -3194,7 +3186,7 @@ func (a *OpenTracingAppLayer) DeletePublicKey(name string) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { +func (a *OpenTracingAppLayer) DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteReactionForPost") @@ -3206,7 +3198,7 @@ func (a *OpenTracingAppLayer) DeleteReactionForPost(reaction *model.Reaction) *m }() defer span.Finish() - resultVar0 := a.app.DeleteReactionForPost(reaction) + resultVar0 := a.app.DeleteReactionForPost(c, reaction) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -3458,7 +3450,7 @@ func (a *OpenTracingAppLayer) DisableUserAccessToken(token *model.UserAccessToke return resultVar0 } -func (a *OpenTracingAppLayer) DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) { +func (a *OpenTracingAppLayer) DoActionRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoActionRequest") @@ -3470,7 +3462,7 @@ func (a *OpenTracingAppLayer) DoActionRequest(rawURL string, body []byte) (*http }() defer span.Finish() - resultVar0, resultVar1 := a.app.DoActionRequest(rawURL, body) + resultVar0, resultVar1 := a.app.DoActionRequest(c, rawURL, body) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3562,7 +3554,7 @@ func (a *OpenTracingAppLayer) DoGuestRolesCreationMigration() { a.app.DoGuestRolesCreationMigration() } -func (a *OpenTracingAppLayer) DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) { +func (a *OpenTracingAppLayer) DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoLocalRequest") @@ -3574,7 +3566,7 @@ func (a *OpenTracingAppLayer) DoLocalRequest(rawURL string, body []byte) (*http. }() defer span.Finish() - resultVar0, resultVar1 := a.app.DoLocalRequest(rawURL, body) + resultVar0, resultVar1 := a.app.DoLocalRequest(c, rawURL, body) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3584,7 +3576,7 @@ func (a *OpenTracingAppLayer) DoLocalRequest(rawURL string, body []byte) (*http. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile bool, isOAuthUser bool, isSaml bool) *model.AppError { +func (a *OpenTracingAppLayer) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile bool, isOAuthUser bool, isSaml bool) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoLogin") @@ -3596,7 +3588,7 @@ func (a *OpenTracingAppLayer) DoLogin(w http.ResponseWriter, r *http.Request, us }() defer span.Finish() - resultVar0 := a.app.DoLogin(w, r, user, deviceID, isMobile, isOAuthUser, isSaml) + resultVar0 := a.app.DoLogin(c, w, r, user, deviceID, isMobile, isOAuthUser, isSaml) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -3628,7 +3620,7 @@ func (a *OpenTracingAppLayer) DoPermissionsMigrations() error { return resultVar0 } -func (a *OpenTracingAppLayer) DoPostAction(postID string, actionId string, userID string, selectedOption string) (string, *model.AppError) { +func (a *OpenTracingAppLayer) DoPostAction(c *request.Context, postID string, actionId string, userID string, selectedOption string) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoPostAction") @@ -3640,7 +3632,7 @@ func (a *OpenTracingAppLayer) DoPostAction(postID string, actionId string, userI }() defer span.Finish() - resultVar0, resultVar1 := a.app.DoPostAction(postID, actionId, userID, selectedOption) + resultVar0, resultVar1 := a.app.DoPostAction(c, postID, actionId, userID, selectedOption) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3650,7 +3642,7 @@ func (a *OpenTracingAppLayer) DoPostAction(postID string, actionId string, userI return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) DoPostActionWithCookie(postID string, actionId string, userID string, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) { +func (a *OpenTracingAppLayer) DoPostActionWithCookie(c *request.Context, postID string, actionId string, userID string, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoPostActionWithCookie") @@ -3662,7 +3654,7 @@ func (a *OpenTracingAppLayer) DoPostActionWithCookie(postID string, actionId str }() defer span.Finish() - resultVar0, resultVar1 := a.app.DoPostActionWithCookie(postID, actionId, userID, selectedOption, cookie) + resultVar0, resultVar1 := a.app.DoPostActionWithCookie(c, postID, actionId, userID, selectedOption, cookie) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3687,7 +3679,7 @@ func (a *OpenTracingAppLayer) DoSystemConsoleRolesCreationMigration() { a.app.DoSystemConsoleRolesCreationMigration() } -func (a *OpenTracingAppLayer) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { +func (a *OpenTracingAppLayer) DoUploadFile(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoUploadFile") @@ -3699,7 +3691,7 @@ func (a *OpenTracingAppLayer) DoUploadFile(now time.Time, rawTeamId string, rawC }() defer span.Finish() - resultVar0, resultVar1 := a.app.DoUploadFile(now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) + resultVar0, resultVar1 := a.app.DoUploadFile(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3709,7 +3701,7 @@ func (a *OpenTracingAppLayer) DoUploadFile(now time.Time, rawTeamId string, rawC return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) { +func (a *OpenTracingAppLayer) DoUploadFileExpectModification(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoUploadFileExpectModification") @@ -3721,7 +3713,7 @@ func (a *OpenTracingAppLayer) DoUploadFileExpectModification(now time.Time, rawT }() defer span.Finish() - resultVar0, resultVar1, resultVar2 := a.app.DoUploadFileExpectModification(now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) + resultVar0, resultVar1, resultVar2 := a.app.DoUploadFileExpectModification(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) if resultVar2 != nil { span.LogFields(spanlog.Error(resultVar2)) @@ -3836,7 +3828,7 @@ func (a *OpenTracingAppLayer) EnvironmentConfig(filter func(reflect.StructField) return resultVar0 } -func (a *OpenTracingAppLayer) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { +func (a *OpenTracingAppLayer) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExecuteCommand") @@ -3850,7 +3842,7 @@ func (a *OpenTracingAppLayer) ExecuteCommand(args *model.CommandArgs) (*model.Co span.SetTag("args", args) defer span.Finish() - resultVar0, resultVar1 := a.app.ExecuteCommand(args) + resultVar0, resultVar1 := a.app.ExecuteCommand(c, args) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -6980,7 +6972,7 @@ func (a *OpenTracingAppLayer) GetOpenGraphMetadata(requestURL string) *opengraph return resultVar0 } -func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(c *request.Context, userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOrCreateDirectChannel") @@ -6992,7 +6984,7 @@ func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(userID string, otherUserI }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetOrCreateDirectChannel(userID, otherUserID, channelOptions...) + resultVar0, resultVar1 := a.app.GetOrCreateDirectChannel(c, userID, otherUserID, channelOptions...) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7156,7 +7148,7 @@ func (a *OpenTracingAppLayer) GetPasswordRecoveryToken(token string) (*model.Tok return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetPermalinkPost(postID string, userID string) (*model.PostList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPermalinkPost") @@ -7168,7 +7160,7 @@ func (a *OpenTracingAppLayer) GetPermalinkPost(postID string, userID string) (*m }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPermalinkPost(postID, userID) + resultVar0, resultVar1 := a.app.GetPermalinkPost(c, postID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7691,7 +7683,7 @@ func (a *OpenTracingAppLayer) GetPrivateChannelsForTeam(teamID string, offset in return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetProductNotices(userID string, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) { +func (a *OpenTracingAppLayer) GetProductNotices(c *request.Context, userID string, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetProductNotices") @@ -7703,7 +7695,7 @@ func (a *OpenTracingAppLayer) GetProductNotices(userID string, teamID string, cl }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetProductNotices(userID, teamID, client, clientVersion, locale) + resultVar0, resultVar1 := a.app.GetProductNotices(c, userID, teamID, client, clientVersion, locale) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8717,7 +8709,7 @@ func (a *OpenTracingAppLayer) GetStatusesByIds(userIDs []string) (map[string]int return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion { +func (a *OpenTracingAppLayer) GetSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSuggestions") @@ -8729,7 +8721,7 @@ func (a *OpenTracingAppLayer) GetSuggestions(commandArgs *model.CommandArgs, com }() defer span.Finish() - resultVar0 := a.app.GetSuggestions(commandArgs, commands, roleID) + resultVar0 := a.app.GetSuggestions(c, commandArgs, commands, roleID) return resultVar0 } @@ -9570,7 +9562,7 @@ func (a *OpenTracingAppLayer) GetUsers(options *model.UserGetOptions) ([]*model. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetUsersByGroupChannelIds(channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) GetUsersByGroupChannelIds(c *request.Context, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersByGroupChannelIds") @@ -9582,7 +9574,7 @@ func (a *OpenTracingAppLayer) GetUsersByGroupChannelIds(channelIDs []string, asA }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetUsersByGroupChannelIds(channelIDs, asAdmin) + resultVar0, resultVar1 := a.app.GetUsersByGroupChannelIds(c, channelIDs, asAdmin) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -10098,7 +10090,7 @@ func (a *OpenTracingAppLayer) Handle404(w http.ResponseWriter, r *http.Request) a.app.Handle404(w, r) } -func (a *OpenTracingAppLayer) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { +func (a *OpenTracingAppLayer) HandleCommandResponse(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandResponse") @@ -10110,7 +10102,7 @@ func (a *OpenTracingAppLayer) HandleCommandResponse(command *model.Command, args }() defer span.Finish() - resultVar0, resultVar1 := a.app.HandleCommandResponse(command, args, response, builtIn) + resultVar0, resultVar1 := a.app.HandleCommandResponse(c, command, args, response, builtIn) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -10120,7 +10112,7 @@ func (a *OpenTracingAppLayer) HandleCommandResponse(command *model.Command, args return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) HandleCommandResponsePost(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandResponsePost") @@ -10132,7 +10124,7 @@ func (a *OpenTracingAppLayer) HandleCommandResponsePost(command *model.Command, }() defer span.Finish() - resultVar0, resultVar1 := a.app.HandleCommandResponsePost(command, args, response, builtIn) + resultVar0, resultVar1 := a.app.HandleCommandResponsePost(c, command, args, response, builtIn) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -10142,7 +10134,7 @@ func (a *OpenTracingAppLayer) HandleCommandResponsePost(command *model.Command, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) HandleCommandWebhook(hookID string, response *model.CommandResponse) *model.AppError { +func (a *OpenTracingAppLayer) HandleCommandWebhook(c *request.Context, hookID string, response *model.CommandResponse) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandWebhook") @@ -10154,7 +10146,7 @@ func (a *OpenTracingAppLayer) HandleCommandWebhook(hookID string, response *mode }() defer span.Finish() - resultVar0 := a.app.HandleCommandWebhook(hookID, response) + resultVar0 := a.app.HandleCommandWebhook(c, hookID, response) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -10179,7 +10171,7 @@ func (a *OpenTracingAppLayer) HandleImages(previewPathList []string, thumbnailPa a.app.HandleImages(previewPathList, thumbnailPathList, fileData) } -func (a *OpenTracingAppLayer) HandleIncomingWebhook(hookID string, req *model.IncomingWebhookRequest) *model.AppError { +func (a *OpenTracingAppLayer) HandleIncomingWebhook(c *request.Context, hookID string, req *model.IncomingWebhookRequest) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleIncomingWebhook") @@ -10191,7 +10183,7 @@ func (a *OpenTracingAppLayer) HandleIncomingWebhook(hookID string, req *model.In }() defer span.Finish() - resultVar0 := a.app.HandleIncomingWebhook(hookID, req) + resultVar0 := a.app.HandleIncomingWebhook(c, hookID, req) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -10461,7 +10453,7 @@ func (a *OpenTracingAppLayer) ImportPermissions(jsonl io.Reader) error { return resultVar0 } -func (a *OpenTracingAppLayer) InitPlugins(pluginDir string, webappPluginDir string) { +func (a *OpenTracingAppLayer) InitPlugins(c *request.Context, pluginDir string, webappPluginDir string) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitPlugins") @@ -10473,37 +10465,7 @@ func (a *OpenTracingAppLayer) InitPlugins(pluginDir string, webappPluginDir stri }() defer span.Finish() - a.app.InitPlugins(pluginDir, webappPluginDir) -} - -func (a *OpenTracingAppLayer) InitPostMetadata() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitPostMetadata") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.InitPostMetadata() -} - -func (a *OpenTracingAppLayer) InitServer() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitServer") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.InitServer() + a.app.InitPlugins(c, pluginDir, webappPluginDir) } func (a *OpenTracingAppLayer) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) { @@ -10846,7 +10808,7 @@ func (a *OpenTracingAppLayer) IsUsernameTaken(name string) bool { return resultVar0 } -func (a *OpenTracingAppLayer) JoinChannel(channel *model.Channel, userID string) *model.AppError { +func (a *OpenTracingAppLayer) JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinChannel") @@ -10858,7 +10820,7 @@ func (a *OpenTracingAppLayer) JoinChannel(channel *model.Channel, userID string) }() defer span.Finish() - resultVar0 := a.app.JoinChannel(channel, userID) + resultVar0 := a.app.JoinChannel(c, channel, userID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -10868,7 +10830,7 @@ func (a *OpenTracingAppLayer) JoinChannel(channel *model.Channel, userID string) return resultVar0 } -func (a *OpenTracingAppLayer) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { +func (a *OpenTracingAppLayer) JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinDefaultChannels") @@ -10880,7 +10842,7 @@ func (a *OpenTracingAppLayer) JoinDefaultChannels(teamID string, user *model.Use }() defer span.Finish() - resultVar0 := a.app.JoinDefaultChannels(teamID, user, shouldBeAdmin, userRequestorId) + resultVar0 := a.app.JoinDefaultChannels(c, teamID, user, shouldBeAdmin, userRequestorId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -10890,7 +10852,7 @@ func (a *OpenTracingAppLayer) JoinDefaultChannels(teamID string, user *model.Use return resultVar0 } -func (a *OpenTracingAppLayer) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) { +func (a *OpenTracingAppLayer) JoinUserToTeam(c *request.Context, team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinUserToTeam") @@ -10902,7 +10864,7 @@ func (a *OpenTracingAppLayer) JoinUserToTeam(team *model.Team, user *model.User, }() defer span.Finish() - resultVar0, resultVar1 := a.app.JoinUserToTeam(team, user, userRequestorId) + resultVar0, resultVar1 := a.app.JoinUserToTeam(c, team, user, userRequestorId) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -10912,7 +10874,7 @@ func (a *OpenTracingAppLayer) JoinUserToTeam(team *model.Team, user *model.User, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) LeaveChannel(channelID string, userID string) *model.AppError { +func (a *OpenTracingAppLayer) LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LeaveChannel") @@ -10924,7 +10886,7 @@ func (a *OpenTracingAppLayer) LeaveChannel(channelID string, userID string) *mod }() defer span.Finish() - resultVar0 := a.app.LeaveChannel(channelID, userID) + resultVar0 := a.app.LeaveChannel(c, channelID, userID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -10934,7 +10896,7 @@ func (a *OpenTracingAppLayer) LeaveChannel(channelID string, userID string) *mod return resultVar0 } -func (a *OpenTracingAppLayer) LeaveTeam(team *model.Team, user *model.User, requestorId string) *model.AppError { +func (a *OpenTracingAppLayer) LeaveTeam(c *request.Context, team *model.Team, user *model.User, requestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LeaveTeam") @@ -10946,7 +10908,7 @@ func (a *OpenTracingAppLayer) LeaveTeam(team *model.Team, user *model.User, requ }() defer span.Finish() - resultVar0 := a.app.LeaveTeam(team, user, requestorId) + resultVar0 := a.app.LeaveTeam(c, team, user, requestorId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -11176,7 +11138,7 @@ func (a *OpenTracingAppLayer) LogAuditRecWithLevel(rec *audit.Record, level mlog a.app.LogAuditRecWithLevel(rec, level, err) } -func (a *OpenTracingAppLayer) LoginByOAuth(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LoginByOAuth") @@ -11188,7 +11150,7 @@ func (a *OpenTracingAppLayer) LoginByOAuth(service string, userData io.Reader, t }() defer span.Finish() - resultVar0, resultVar1 := a.app.LoginByOAuth(service, userData, teamID, tokenUser) + resultVar0, resultVar1 := a.app.LoginByOAuth(c, service, userData, teamID, tokenUser) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -11215,7 +11177,7 @@ func (a *OpenTracingAppLayer) MakeAuditRecord(event string, initialStatus string return resultVar0 } -func (a *OpenTracingAppLayer) MakePermissionError(permissions []*model.Permission) *model.AppError { +func (a *OpenTracingAppLayer) MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MakePermissionError") @@ -11227,7 +11189,7 @@ func (a *OpenTracingAppLayer) MakePermissionError(permissions []*model.Permissio }() defer span.Finish() - resultVar0 := a.app.MakePermissionError(permissions) + resultVar0 := a.app.MakePermissionError(s, permissions) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -11371,7 +11333,7 @@ func (a *OpenTracingAppLayer) MigrateIdLDAP(toAttribute string) *model.AppError return resultVar0 } -func (a *OpenTracingAppLayer) MoveChannel(team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MoveChannel") @@ -11383,7 +11345,7 @@ func (a *OpenTracingAppLayer) MoveChannel(team *model.Team, channel *model.Chann }() defer span.Finish() - resultVar0 := a.app.MoveChannel(team, channel, user) + resultVar0 := a.app.MoveChannel(c, team, channel, user) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -11454,7 +11416,7 @@ func (a *OpenTracingAppLayer) NewClusterDiscoveryService() *app.ClusterDiscovery return resultVar0 } -func (a *OpenTracingAppLayer) NewPluginAPI(manifest *model.Manifest) plugin.API { +func (a *OpenTracingAppLayer) NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NewPluginAPI") @@ -11466,7 +11428,7 @@ func (a *OpenTracingAppLayer) NewPluginAPI(manifest *model.Manifest) plugin.API }() defer span.Finish() - resultVar0 := a.app.NewPluginAPI(manifest) + resultVar0 := a.app.NewPluginAPI(c, manifest) return resultVar0 } @@ -11640,7 +11602,7 @@ func (a *OpenTracingAppLayer) PatchBot(botUserId string, botPatch *model.BotPatc return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannel") @@ -11652,7 +11614,7 @@ func (a *OpenTracingAppLayer) PatchChannel(channel *model.Channel, patch *model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.PatchChannel(channel, patch, userID) + resultVar0, resultVar1 := a.app.PatchChannel(c, channel, patch, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -11684,7 +11646,7 @@ func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(channel *model.C return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) PatchPost(postID string, patch *model.PostPatch) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) PatchPost(c *request.Context, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchPost") @@ -11696,7 +11658,7 @@ func (a *OpenTracingAppLayer) PatchPost(postID string, patch *model.PostPatch) ( }() defer span.Finish() - resultVar0, resultVar1 := a.app.PatchPost(postID, patch) + resultVar0, resultVar1 := a.app.PatchPost(c, postID, patch) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -11816,7 +11778,7 @@ func (a *OpenTracingAppLayer) PatchUser(userID string, patch *model.UserPatch, a return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) PermanentDeleteAllUsers() *model.AppError { +func (a *OpenTracingAppLayer) PermanentDeleteAllUsers(c *request.Context) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteAllUsers") @@ -11828,7 +11790,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteAllUsers() *model.AppError { }() defer span.Finish() - resultVar0 := a.app.PermanentDeleteAllUsers() + resultVar0 := a.app.PermanentDeleteAllUsers(c) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -11926,7 +11888,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeamId(teamID string) *model.AppErr return resultVar0 } -func (a *OpenTracingAppLayer) PermanentDeleteUser(user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) PermanentDeleteUser(c *request.Context, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteUser") @@ -11938,7 +11900,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteUser(user *model.User) *model.AppEr }() defer span.Finish() - resultVar0 := a.app.PermanentDeleteUser(user) + resultVar0 := a.app.PermanentDeleteUser(c, user) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -11965,24 +11927,7 @@ func (a *OpenTracingAppLayer) PluginCommandsForTeam(teamID string) []*model.Comm return resultVar0 } -func (a *OpenTracingAppLayer) PluginContext() *plugin.Context { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PluginContext") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.PluginContext() - - return resultVar0 -} - -func (a *OpenTracingAppLayer) PopulateWebConnConfig(cfg *app.WebConnConfig, seqVal string) (*app.WebConnConfig, error) { +func (a *OpenTracingAppLayer) PopulateWebConnConfig(s *model.Session, cfg *app.WebConnConfig, seqVal string) (*app.WebConnConfig, error) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PopulateWebConnConfig") @@ -11994,7 +11939,7 @@ func (a *OpenTracingAppLayer) PopulateWebConnConfig(cfg *app.WebConnConfig, seqV }() defer span.Finish() - resultVar0, resultVar1 := a.app.PopulateWebConnConfig(cfg, seqVal) + resultVar0, resultVar1 := a.app.PopulateWebConnConfig(s, cfg, seqVal) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12021,7 +11966,7 @@ func (a *OpenTracingAppLayer) PostActionCookieSecret() []byte { return resultVar0 } -func (a *OpenTracingAppLayer) PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *OpenTracingAppLayer) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostAddToChannelMessage") @@ -12033,7 +11978,7 @@ func (a *OpenTracingAppLayer) PostAddToChannelMessage(user *model.User, addedUse }() defer span.Finish() - resultVar0 := a.app.PostAddToChannelMessage(user, addedUser, channel, postRootId) + resultVar0 := a.app.PostAddToChannelMessage(c, user, addedUser, channel, postRootId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12060,7 +12005,7 @@ func (a *OpenTracingAppLayer) PostPatchWithProxyRemovedFromImageURLs(patch *mode return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(userID string, channel *model.Channel, oldChannelDisplayName string, newChannelDisplayName string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName string, newChannelDisplayName string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelDisplayNameMessage") @@ -12072,7 +12017,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(userID string, }() defer span.Finish() - resultVar0 := a.app.PostUpdateChannelDisplayNameMessage(userID, channel, oldChannelDisplayName, newChannelDisplayName) + resultVar0 := a.app.PostUpdateChannelDisplayNameMessage(c, userID, channel, oldChannelDisplayName, newChannelDisplayName) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12082,7 +12027,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(userID string, return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(userID string, channel *model.Channel, oldChannelHeader string, newChannelHeader string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader string, newChannelHeader string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelHeaderMessage") @@ -12094,7 +12039,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(userID string, chan }() defer span.Finish() - resultVar0 := a.app.PostUpdateChannelHeaderMessage(userID, channel, oldChannelHeader, newChannelHeader) + resultVar0 := a.app.PostUpdateChannelHeaderMessage(c, userID, channel, oldChannelHeader, newChannelHeader) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12104,7 +12049,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(userID string, chan return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelPurposeMessage") @@ -12116,7 +12061,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(userID string, cha }() defer span.Finish() - resultVar0 := a.app.PostUpdateChannelPurposeMessage(userID, channel, oldChannelPurpose, newChannelPurpose) + resultVar0 := a.app.PostUpdateChannelPurposeMessage(c, userID, channel, oldChannelPurpose, newChannelPurpose) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12228,7 +12173,7 @@ func (a *OpenTracingAppLayer) ProcessSlackText(text string) string { return resultVar0 } -func (a *OpenTracingAppLayer) PromoteGuestToUser(user *model.User, requestorId string) *model.AppError { +func (a *OpenTracingAppLayer) PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PromoteGuestToUser") @@ -12240,7 +12185,7 @@ func (a *OpenTracingAppLayer) PromoteGuestToUser(user *model.User, requestorId s }() defer span.Finish() - resultVar0 := a.app.PromoteGuestToUser(user, requestorId) + resultVar0 := a.app.PromoteGuestToUser(c, user, requestorId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12816,7 +12761,7 @@ func (a *OpenTracingAppLayer) RemoveTeamIcon(teamID string) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId string) *model.AppError { +func (a *OpenTracingAppLayer) RemoveTeamMemberFromTeam(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveTeamMemberFromTeam") @@ -12828,7 +12773,7 @@ func (a *OpenTracingAppLayer) RemoveTeamMemberFromTeam(teamMember *model.TeamMem }() defer span.Finish() - resultVar0 := a.app.RemoveTeamMemberFromTeam(teamMember, requestorId) + resultVar0 := a.app.RemoveTeamMemberFromTeam(c, teamMember, requestorId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12860,7 +12805,7 @@ func (a *OpenTracingAppLayer) RemoveTeamsFromRetentionPolicy(policyID string, te return resultVar0 } -func (a *OpenTracingAppLayer) RemoveUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUserFromChannel") @@ -12872,7 +12817,7 @@ func (a *OpenTracingAppLayer) RemoveUserFromChannel(userIDToRemove string, remov }() defer span.Finish() - resultVar0 := a.app.RemoveUserFromChannel(userIDToRemove, removerUserId, channel) + resultVar0 := a.app.RemoveUserFromChannel(c, userIDToRemove, removerUserId, channel) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12882,7 +12827,7 @@ func (a *OpenTracingAppLayer) RemoveUserFromChannel(userIDToRemove string, remov return resultVar0 } -func (a *OpenTracingAppLayer) RemoveUserFromTeam(teamID string, userID string, requestorId string) *model.AppError { +func (a *OpenTracingAppLayer) RemoveUserFromTeam(c *request.Context, teamID string, userID string, requestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUserFromTeam") @@ -12894,7 +12839,7 @@ func (a *OpenTracingAppLayer) RemoveUserFromTeam(teamID string, userID string, r }() defer span.Finish() - resultVar0 := a.app.RemoveUserFromTeam(teamID, userID, requestorId) + resultVar0 := a.app.RemoveUserFromTeam(c, teamID, userID, requestorId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12904,7 +12849,7 @@ func (a *OpenTracingAppLayer) RemoveUserFromTeam(teamID string, userID string, r return resultVar0 } -func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { +func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUsersFromChannelNotMemberOfTeam") @@ -12916,7 +12861,7 @@ func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(remover *mod }() defer span.Finish() - resultVar0 := a.app.RemoveUsersFromChannelNotMemberOfTeam(remover, channel, team) + resultVar0 := a.app.RemoveUsersFromChannelNotMemberOfTeam(c, remover, channel, team) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12970,7 +12915,7 @@ func (a *OpenTracingAppLayer) RenameTeam(team *model.Team, newTeamName string, n return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) RequestLicenseAndAckWarnMetric(warnMetricId string, isBot bool) *model.AppError { +func (a *OpenTracingAppLayer) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RequestLicenseAndAckWarnMetric") @@ -12982,7 +12927,7 @@ func (a *OpenTracingAppLayer) RequestLicenseAndAckWarnMetric(warnMetricId string }() defer span.Finish() - resultVar0 := a.app.RequestLicenseAndAckWarnMetric(warnMetricId, isBot) + resultVar0 := a.app.RequestLicenseAndAckWarnMetric(c, warnMetricId, isBot) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -13058,7 +13003,7 @@ func (a *OpenTracingAppLayer) ResetSamlAuthDataToEmail(includeDeleted bool, dryR return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) RestoreChannel(channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestoreChannel") @@ -13070,7 +13015,7 @@ func (a *OpenTracingAppLayer) RestoreChannel(channel *model.Channel, userID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.RestoreChannel(channel, userID) + resultVar0, resultVar1 := a.app.RestoreChannel(c, channel, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -13447,7 +13392,7 @@ func (a *OpenTracingAppLayer) SaveConfig(newCfg *model.Config, sendConfigChangeC return resultVar0 } -func (a *OpenTracingAppLayer) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { +func (a *OpenTracingAppLayer) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveReactionForPost") @@ -13459,7 +13404,7 @@ func (a *OpenTracingAppLayer) SaveReactionForPost(reaction *model.Reaction) (*mo }() defer span.Finish() - resultVar0, resultVar1 := a.app.SaveReactionForPost(reaction) + resultVar0, resultVar1 := a.app.SaveReactionForPost(c, reaction) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -13723,7 +13668,7 @@ func (a *OpenTracingAppLayer) SearchEngine() *searchengine.Broker { return resultVar0 } -func (a *OpenTracingAppLayer) SearchFilesInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page int, perPage int) (*model.FileInfoList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page int, perPage int) (*model.FileInfoList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchFilesInTeamForUser") @@ -13735,7 +13680,7 @@ func (a *OpenTracingAppLayer) SearchFilesInTeamForUser(terms string, userId stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchFilesInTeamForUser(terms, userId, teamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) + resultVar0, resultVar1 := a.app.SearchFilesInTeamForUser(c, terms, userId, teamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -13789,7 +13734,7 @@ func (a *OpenTracingAppLayer) SearchPostsInTeam(teamID string, paramsList []*mod return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SearchPostsInTeamForUser(terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page int, perPage int) (*model.PostSearchResults, *model.AppError) { +func (a *OpenTracingAppLayer) SearchPostsInTeamForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page int, perPage int) (*model.PostSearchResults, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchPostsInTeamForUser") @@ -13801,7 +13746,7 @@ func (a *OpenTracingAppLayer) SearchPostsInTeamForUser(terms string, userID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchPostsInTeamForUser(terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) + resultVar0, resultVar1 := a.app.SearchPostsInTeamForUser(c, terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14075,7 +14020,7 @@ func (a *OpenTracingAppLayer) SendAdminUpgradeRequestEmail(username string, subs return resultVar0 } -func (a *OpenTracingAppLayer) SendAutoResponse(channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { +func (a *OpenTracingAppLayer) SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponse") @@ -14087,7 +14032,7 @@ func (a *OpenTracingAppLayer) SendAutoResponse(channel *model.Channel, receiver }() defer span.Finish() - resultVar0, resultVar1 := a.app.SendAutoResponse(channel, receiver, post) + resultVar0, resultVar1 := a.app.SendAutoResponse(c, channel, receiver, post) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14097,7 +14042,7 @@ func (a *OpenTracingAppLayer) SendAutoResponse(channel *model.Channel, receiver return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { +func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponseIfNecessary") @@ -14109,7 +14054,7 @@ func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(channel *model.Channel }() defer span.Finish() - resultVar0, resultVar1 := a.app.SendAutoResponseIfNecessary(channel, sender, post) + resultVar0, resultVar1 := a.app.SendAutoResponseIfNecessary(c, channel, sender, post) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -15100,7 +15045,7 @@ func (a *OpenTracingAppLayer) SetTeamIconFromMultiPartFile(teamID string, file m return resultVar0 } -func (a *OpenTracingAppLayer) SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { +func (a *OpenTracingAppLayer) SlackImport(c *request.Context, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SlackImport") @@ -15112,7 +15057,7 @@ func (a *OpenTracingAppLayer) SlackImport(fileData multipart.File, fileSize int6 }() defer span.Finish() - resultVar0, resultVar1 := a.app.SlackImport(fileData, fileSize, teamID) + resultVar0, resultVar1 := a.app.SlackImport(c, fileData, fileSize, teamID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -15144,7 +15089,7 @@ func (a *OpenTracingAppLayer) SoftDeleteTeam(teamID string) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { +func (a *OpenTracingAppLayer) SubmitInteractiveDialog(c *request.Context, request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SubmitInteractiveDialog") @@ -15156,7 +15101,7 @@ func (a *OpenTracingAppLayer) SubmitInteractiveDialog(request model.SubmitDialog }() defer span.Finish() - resultVar0, resultVar1 := a.app.SubmitInteractiveDialog(request) + resultVar0, resultVar1 := a.app.SubmitInteractiveDialog(c, request) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -15306,7 +15251,7 @@ func (a *OpenTracingAppLayer) SyncPluginsActiveState() { a.app.SyncPluginsActiveState() } -func (a *OpenTracingAppLayer) SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { +func (a *OpenTracingAppLayer) SyncRolesAndMembership(c *request.Context, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SyncRolesAndMembership") @@ -15318,7 +15263,7 @@ func (a *OpenTracingAppLayer) SyncRolesAndMembership(syncableID string, syncable }() defer span.Finish() - a.app.SyncRolesAndMembership(syncableID, syncableType, includeRemovedMembers) + a.app.SyncRolesAndMembership(c, syncableID, syncableType, includeRemovedMembers) } func (a *OpenTracingAppLayer) SyncSyncableRoles(syncableID string, syncableType model.GroupSyncableType) *model.AppError { @@ -15597,7 +15542,7 @@ func (a *OpenTracingAppLayer) TotalWebsocketConnections() int { return resultVar0 } -func (a *OpenTracingAppLayer) TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { +func (a *OpenTracingAppLayer) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TriggerWebhook") @@ -15609,7 +15554,7 @@ func (a *OpenTracingAppLayer) TriggerWebhook(payload *model.OutgoingWebhookPaylo }() defer span.Finish() - a.app.TriggerWebhook(payload, hook, post, channel) + a.app.TriggerWebhook(c, payload, hook, post, channel) } func (a *OpenTracingAppLayer) UnregisterPluginCommand(pluginID string, teamID string, trigger string) { @@ -15642,7 +15587,7 @@ func (a *OpenTracingAppLayer) UnregisterPluginCommands(pluginID string) { a.app.UnregisterPluginCommands(pluginID) } -func (a *OpenTracingAppLayer) UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateActive(c *request.Context, user *model.User, active bool) (*model.User, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateActive") @@ -15654,7 +15599,7 @@ func (a *OpenTracingAppLayer) UpdateActive(user *model.User, active bool) (*mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateActive(user, active) + resultVar0, resultVar1 := a.app.UpdateActive(c, user, active) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -15664,7 +15609,7 @@ func (a *OpenTracingAppLayer) UpdateActive(user *model.User, active bool) (*mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateBotActive(c *request.Context, botUserId string, active bool) (*model.Bot, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateBotActive") @@ -15676,7 +15621,7 @@ func (a *OpenTracingAppLayer) UpdateBotActive(botUserId string, active bool) (*m }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateBotActive(botUserId, active) + resultVar0, resultVar1 := a.app.UpdateBotActive(c, botUserId, active) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -15818,7 +15763,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(channelID string, u return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelPrivacy") @@ -15830,7 +15775,7 @@ func (a *OpenTracingAppLayer) UpdateChannelPrivacy(oldChannel *model.Channel, us }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannelPrivacy(oldChannel, user) + resultVar0, resultVar1 := a.app.UpdateChannelPrivacy(c, oldChannel, user) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16269,7 +16214,7 @@ func (a *OpenTracingAppLayer) UpdatePasswordSendEmail(user *model.User, newPassw return resultVar0 } -func (a *OpenTracingAppLayer) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePost") @@ -16281,7 +16226,7 @@ func (a *OpenTracingAppLayer) UpdatePost(post *model.Post, safeUpdate bool) (*mo }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdatePost(post, safeUpdate) + resultVar0, resultVar1 := a.app.UpdatePost(c, post, safeUpdate) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16724,7 +16669,7 @@ func (a *OpenTracingAppLayer) UpdateUser(user *model.User, sendNotifications boo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateUserActive(userID string, active bool) *model.AppError { +func (a *OpenTracingAppLayer) UpdateUserActive(c *request.Context, userID string, active bool) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserActive") @@ -16736,7 +16681,7 @@ func (a *OpenTracingAppLayer) UpdateUserActive(userID string, active bool) *mode }() defer span.Finish() - resultVar0 := a.app.UpdateUserActive(userID, active) + resultVar0 := a.app.UpdateUserActive(c, userID, active) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -16908,7 +16853,7 @@ func (a *OpenTracingAppLayer) UpdateWebConnUserActivity(session model.Session, a a.app.UpdateWebConnUserActivity(session, activityAt) } -func (a *OpenTracingAppLayer) UploadData(us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) { +func (a *OpenTracingAppLayer) UploadData(c *request.Context, us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadData") @@ -16920,7 +16865,7 @@ func (a *OpenTracingAppLayer) UploadData(us *model.UploadSession, rd io.Reader) }() defer span.Finish() - resultVar0, resultVar1 := a.app.UploadData(us, rd) + resultVar0, resultVar1 := a.app.UploadData(c, us, rd) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16952,7 +16897,7 @@ func (a *OpenTracingAppLayer) UploadEmojiImage(id string, imageData *multipart.F return resultVar0 } -func (a *OpenTracingAppLayer) UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) { +func (a *OpenTracingAppLayer) UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadFile") @@ -16964,7 +16909,7 @@ func (a *OpenTracingAppLayer) UploadFile(data []byte, channelID string, filename }() defer span.Finish() - resultVar0, resultVar1 := a.app.UploadFile(data, channelID, filename) + resultVar0, resultVar1 := a.app.UploadFile(c, data, channelID, filename) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16974,7 +16919,7 @@ func (a *OpenTracingAppLayer) UploadFile(data []byte, channelID string, filename return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UploadFileX(channelID string, name string, input io.Reader, opts ...func(*app.UploadFileTask)) (*model.FileInfo, *model.AppError) { +func (a *OpenTracingAppLayer) UploadFileX(c *request.Context, channelID string, name string, input io.Reader, opts ...func(*app.UploadFileTask)) (*model.FileInfo, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadFileX") @@ -16986,7 +16931,7 @@ func (a *OpenTracingAppLayer) UploadFileX(channelID string, name string, input i }() defer span.Finish() - resultVar0, resultVar1 := a.app.UploadFileX(channelID, name, input, opts...) + resultVar0, resultVar1 := a.app.UploadFileX(c, channelID, name, input, opts...) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16996,7 +16941,7 @@ func (a *OpenTracingAppLayer) UploadFileX(channelID string, name string, input i return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UploadFiles(teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { +func (a *OpenTracingAppLayer) UploadFiles(c *request.Context, teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadFiles") @@ -17008,7 +16953,7 @@ func (a *OpenTracingAppLayer) UploadFiles(teamID string, channelID string, userI }() defer span.Finish() - resultVar0, resultVar1 := a.app.UploadFiles(teamID, channelID, userID, files, filenames, clientIds, now) + resultVar0, resultVar1 := a.app.UploadFiles(c, teamID, channelID, userID, files, filenames, clientIds, now) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17018,7 +16963,7 @@ func (a *OpenTracingAppLayer) UploadFiles(teamID string, channelID string, userI return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UploadMultipartFiles(teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { +func (a *OpenTracingAppLayer) UploadMultipartFiles(c *request.Context, teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadMultipartFiles") @@ -17030,7 +16975,7 @@ func (a *OpenTracingAppLayer) UploadMultipartFiles(teamID string, channelID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.UploadMultipartFiles(teamID, channelID, userID, fileHeaders, clientIds, now) + resultVar0, resultVar1 := a.app.UploadMultipartFiles(c, teamID, channelID, userID, fileHeaders, clientIds, now) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17247,15 +17192,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *OpenTra newApp.srv = childApp.Srv() newApp.log = childApp.Log() newApp.notificationsLog = childApp.NotificationsLog() - newApp.t = childApp.GetT() - if childApp.Session() != nil { - newApp.session = *childApp.Session() - } - newApp.requestId = childApp.RequestId() - newApp.ipAddress = childApp.IpAddress() - newApp.path = childApp.Path() - newApp.userAgent = childApp.UserAgent() - newApp.acceptLanguage = childApp.AcceptLanguage() newApp.accountMigration = childApp.AccountMigration() newApp.cluster = childApp.Cluster() newApp.compliance = childApp.Compliance() @@ -17269,7 +17205,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *OpenTra newApp.httpService = childApp.HTTPService() newApp.imageProxy = childApp.ImageProxy() newApp.timezones = childApp.Timezones() - newApp.context = childApp.Context() return &newApp } @@ -17283,27 +17218,6 @@ func (a *OpenTracingAppLayer) Log() *mlog.Logger { func (a *OpenTracingAppLayer) NotificationsLog() *mlog.Logger { return a.notificationsLog } -func (a *OpenTracingAppLayer) T(translationID string, args ...interface{}) string { - return a.t(translationID, args...) -} -func (a *OpenTracingAppLayer) Session() *model.Session { - return &a.session -} -func (a *OpenTracingAppLayer) RequestId() string { - return a.requestId -} -func (a *OpenTracingAppLayer) IpAddress() string { - return a.ipAddress -} -func (a *OpenTracingAppLayer) Path() string { - return a.path -} -func (a *OpenTracingAppLayer) UserAgent() string { - return a.userAgent -} -func (a *OpenTracingAppLayer) AcceptLanguage() string { - return a.acceptLanguage -} func (a *OpenTracingAppLayer) AccountMigration() einterfaces.AccountMigrationInterface { return a.accountMigration } @@ -17340,36 +17254,6 @@ func (a *OpenTracingAppLayer) ImageProxy() *imageproxy.ImageProxy { func (a *OpenTracingAppLayer) Timezones() *timezones.Timezones { return a.timezones } -func (a *OpenTracingAppLayer) Context() context.Context { - return a.context -} -func (a *OpenTracingAppLayer) SetSession(sess *model.Session) { - a.session = *sess -} -func (a *OpenTracingAppLayer) SetT(t i18n.TranslateFunc) { - a.t = t -} -func (a *OpenTracingAppLayer) SetRequestId(str string) { - a.requestId = str -} -func (a *OpenTracingAppLayer) SetIpAddress(str string) { - a.ipAddress = str -} -func (a *OpenTracingAppLayer) SetUserAgent(str string) { - a.userAgent = str -} -func (a *OpenTracingAppLayer) SetAcceptLanguage(str string) { - a.acceptLanguage = str -} -func (a *OpenTracingAppLayer) SetPath(str string) { - a.path = str -} -func (a *OpenTracingAppLayer) SetContext(c context.Context) { - a.context = c -} func (a *OpenTracingAppLayer) SetServer(srv *app.Server) { a.srv = srv } -func (a *OpenTracingAppLayer) GetT() i18n.TranslateFunc { - return a.t -} diff --git a/app/options.go b/app/options.go index 932827ceff8..4ce8c78ea48 100644 --- a/app/options.go +++ b/app/options.go @@ -95,6 +95,14 @@ func SetLogger(logger *mlog.Logger) Option { } } +func SkipPostInitializiation() Option { + return func(s *Server) error { + s.skipPostInit = true + + return nil + } +} + type AppOption func(a *App) type AppOptionCreator func() []AppOption diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index bba792fd4ff..a5b183ec01a 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -157,8 +157,8 @@ func applyPermissionsMap(role *model.Role, roleMap map[string]map[string]bool, m return result } -func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, roles []*model.Role) *model.AppError { - if _, err := a.Srv().Store.System().GetByName(key); err == nil { +func (s *Server) doPermissionsMigration(key string, migrationMap permissionsMap, roles []*model.Role) *model.AppError { + if _, err := s.Store.System().GetByName(key); err == nil { return nil } @@ -172,7 +172,7 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro for _, role := range roles { role.Permissions = applyPermissionsMap(role, roleMap, migrationMap) - if _, err := a.Srv().Store.Role().Save(role); err != nil { + if _, err := s.Store.Role().Save(role); err != nil { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): @@ -183,7 +183,7 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro } } - if err := a.Srv().Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil { + if err := s.Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil { return model.NewAppError("doPermissionsMigration", "app.system.save.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil @@ -904,6 +904,11 @@ func (a *App) getAddAuthenticationSubsectionPermissions() (permissionsMap, error // DoPermissionsMigrations execute all the permissions migrations need by the current version. func (a *App) DoPermissionsMigrations() error { + return a.Srv().doPermissionsMigrations() +} + +func (s *Server) doPermissionsMigrations() error { + a := New(ServerConnector(s)) PermissionsMigrations := []struct { Key string Migration func() (permissionsMap, error) @@ -936,7 +941,7 @@ func (a *App) DoPermissionsMigrations() error { {Key: model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS, Migration: a.getAddReportingSubsectionPermissions}, } - roles, err := a.srv.Store.Role().GetAll() + roles, err := s.Store.Role().GetAll() if err != nil { return err } @@ -946,7 +951,7 @@ func (a *App) DoPermissionsMigrations() error { if err != nil { return err } - if err := a.doPermissionsMigration(migration.Key, migMap, roles); err != nil { + if err := s.doPermissionsMigration(migration.Key, migMap, roles); err != nil { return err } } diff --git a/app/plugin.go b/app/plugin.go index 3df51472479..1440d08c9d3 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -20,6 +20,7 @@ import ( svg "github.com/h2non/go-is-svg" "github.com/pkg/errors" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/services/marketplace" @@ -69,21 +70,25 @@ func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) { } func (a *App) SyncPluginsActiveState() { + a.Srv().syncPluginsActiveState() +} + +func (s *Server) syncPluginsActiveState() { // Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment. - a.Srv().PluginsLock.RLock() - pluginsEnvironment := a.Srv().PluginsEnvironment - a.Srv().PluginsLock.RUnlock() + s.PluginsLock.RLock() + pluginsEnvironment := s.PluginsEnvironment + s.PluginsLock.RUnlock() if pluginsEnvironment == nil { return } - config := a.Config().PluginSettings + config := s.Config().PluginSettings if *config.Enable { availablePlugins, err := pluginsEnvironment.Available() if err != nil { - a.Log().Error("Unable to get available plugins", mlog.Err(err)) + s.Log.Error("Unable to get available plugins", mlog.Err(err)) return } @@ -99,7 +104,7 @@ func (a *App) SyncPluginsActiveState() { // Tie Apps proxy disabled status to the feature flag. if pluginID == "com.mattermost.apps" { - if !a.Config().FeatureFlags.AppsEnabled { + if !s.Config().FeatureFlags.AppsEnabled { pluginEnabled = false } } @@ -124,7 +129,7 @@ func (a *App) SyncPluginsActiveState() { if deactivated && plugin.Manifest.HasClient() { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_DISABLED, "", "", "", nil) message.Add("manifest", plugin.Manifest.ClientManifest()) - a.Publish(message) + s.Publish(message) } }(plugin) } @@ -138,14 +143,14 @@ func (a *App) SyncPluginsActiveState() { pluginID := plugin.Manifest.Id updatedManifest, activated, err := pluginsEnvironment.Activate(pluginID) if err != nil { - plugin.WrapLogger(a.Log()).Error("Unable to activate plugin", mlog.Err(err)) + plugin.WrapLogger(s.Log).Error("Unable to activate plugin", mlog.Err(err)) return } 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)) + if err := s.notifyPluginEnabled(updatedManifest); err != nil { + s.Log.Error("Failed to notify cluster on plugin enable", mlog.Err(err)) } } }(plugin) @@ -155,26 +160,30 @@ func (a *App) SyncPluginsActiveState() { pluginsEnvironment.Shutdown() } - if err := a.notifyPluginStatusesChanged(); err != nil { + if err := s.notifyPluginStatusesChanged(); err != nil { mlog.Warn("failed to notify plugin status changed", mlog.Err(err)) } } -func (a *App) NewPluginAPI(manifest *model.Manifest) plugin.API { - return NewPluginAPI(a, manifest) +func (a *App) NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API { + return NewPluginAPI(a, c, manifest) } -func (a *App) InitPlugins(pluginDir, webappPluginDir string) { +func (a *App) InitPlugins(c *request.Context, pluginDir, webappPluginDir string) { + a.Srv().initPlugins(c, pluginDir, webappPluginDir) +} + +func (s *Server) initPlugins(c *request.Context, 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() - if pluginsEnvironment != nil || !*a.Config().PluginSettings.Enable { - a.SyncPluginsActiveState() + s.PluginsLock.RLock() + pluginsEnvironment := s.PluginsEnvironment + s.PluginsLock.RUnlock() + if pluginsEnvironment != nil || !*s.Config().PluginSettings.Enable { + s.syncPluginsActiveState() return } - a.Log().Info("Starting up plugins") + s.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)) @@ -186,57 +195,69 @@ func (a *App) InitPlugins(pluginDir, webappPluginDir string) { return } - env, err := plugin.NewEnvironment(a.NewPluginAPI, pluginDir, webappPluginDir, a.Log(), a.Metrics()) + newApiFunc := func(manifest *model.Manifest) plugin.API { + return New(ServerConnector(s)).NewPluginAPI(c, manifest) + } + + env, err := plugin.NewEnvironment(newApiFunc, pluginDir, webappPluginDir, s.Log, s.Metrics) if err != nil { mlog.Error("Failed to start up plugins", mlog.Err(err)) return } - a.SetPluginsEnvironment(env) + s.PluginsLock.Lock() + s.PluginsEnvironment = env + s.PluginsLock.Unlock() - if err := a.SyncPlugins(); err != nil { + if err := s.syncPlugins(); err != nil { mlog.Error("Failed to sync plugins from the file store", mlog.Err(err)) } - plugins := a.processPrepackagedPlugins(prepackagedPluginsDir) - pluginsEnvironment = a.GetPluginsEnvironment() + plugins := s.processPrepackagedPlugins(prepackagedPluginsDir) + pluginsEnvironment = s.GetPluginsEnvironment() if pluginsEnvironment == nil { mlog.Info("Plugins environment not found, server is likely shutting down") return } pluginsEnvironment.SetPrepackagedPlugins(plugins) - a.installFeatureFlagPlugins() + s.installFeatureFlagPlugins() // 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(old, new *model.Config) { + s.PluginsLock.Lock() + s.RemoveConfigListener(s.PluginConfigListenerId) + s.PluginConfigListenerId = s.AddConfigListener(func(old, new *model.Config) { // If plugin status remains unchanged, only then run this. // Because (*App).InitPlugins is already run as a config change hook. if *old.PluginSettings.Enable == *new.PluginSettings.Enable { - a.installFeatureFlagPlugins() - a.SyncPluginsActiveState() + s.installFeatureFlagPlugins() + s.syncPluginsActiveState() } - if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { + if pluginsEnvironment := s.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)) + s.Log.Error("Plugin OnConfigurationChange hook failed", mlog.Err(err)) } return true }, plugin.OnConfigurationChangeID) } }) - a.Srv().PluginsLock.Unlock() + s.PluginsLock.Unlock() - a.SyncPluginsActiveState() + s.syncPluginsActiveState() } // SyncPlugins synchronizes the plugins installed locally // with the plugin bundles available in the file store. func (a *App) SyncPlugins() *model.AppError { + return a.Srv().syncPlugins() +} + +// SyncPlugins synchronizes the plugins installed locally +// with the plugin bundles available in the file store. +func (s *Server) syncPlugins() *model.AppError { mlog.Info("Syncing plugins from the file store") - pluginsEnvironment := a.GetPluginsEnvironment() + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return model.NewAppError("SyncPlugins", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -252,14 +273,14 @@ func (a *App) SyncPlugins() *model.AppError { go func(pluginID string) { defer wg.Done() // Only handle managed plugins with .filestore flag file. - _, err := os.Stat(filepath.Join(*a.Config().PluginSettings.Directory, pluginID, managedPluginFileName)) + _, err := os.Stat(filepath.Join(*s.Config().PluginSettings.Directory, pluginID, managedPluginFileName)) if os.IsNotExist(err) { mlog.Warn("Skipping sync for unmanaged plugin", mlog.String("plugin_id", pluginID)) } else if err != nil { mlog.Error("Skipping sync for plugin after failure to check if managed", mlog.String("plugin_id", pluginID), mlog.Err(err)) } else { mlog.Debug("Removing local installation of managed plugin before sync", mlog.String("plugin_id", pluginID)) - if err := a.removePluginLocally(pluginID); err != nil { + if err := s.removePluginLocally(pluginID); err != nil { mlog.Error("Failed to remove local installation of managed plugin before sync", mlog.String("plugin_id", pluginID), mlog.Err(err)) } } @@ -268,7 +289,7 @@ func (a *App) SyncPlugins() *model.AppError { wg.Wait() // Install plugins from the file store. - pluginSignaturePathMap, appErr := a.getPluginsFromFolder() + pluginSignaturePathMap, appErr := s.getPluginsFromFolder() if appErr != nil { return appErr } @@ -277,7 +298,7 @@ func (a *App) SyncPlugins() *model.AppError { wg.Add(1) go func(plugin *pluginSignaturePath) { defer wg.Done() - reader, appErr := a.FileReader(plugin.path) + reader, appErr := s.fileReader(plugin.path) if appErr != nil { mlog.Error("Failed to open plugin bundle from file store.", mlog.String("bundle", plugin.path), mlog.Err(appErr)) return @@ -285,8 +306,8 @@ func (a *App) SyncPlugins() *model.AppError { defer reader.Close() var signature filestore.ReadCloseSeeker - if *a.Config().PluginSettings.RequirePluginSignature { - signature, appErr = a.FileReader(plugin.signaturePath) + if *s.Config().PluginSettings.RequirePluginSignature { + signature, appErr = s.fileReader(plugin.signaturePath) if appErr != nil { mlog.Error("Failed to open plugin signature from file store.", mlog.Err(appErr)) return @@ -295,7 +316,7 @@ func (a *App) SyncPlugins() *model.AppError { } mlog.Info("Syncing plugin from file store", mlog.String("bundle", plugin.path)) - if _, err := a.installPluginLocally(reader, signature, installPluginLocallyAlways); err != nil { + if _, err := s.installPluginLocally(reader, signature, installPluginLocallyAlways); err != nil { mlog.Error("Failed to sync plugin from file store", mlog.String("bundle", plugin.path), mlog.Err(err)) } }(plugin) @@ -348,7 +369,11 @@ func (a *App) GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { // activation if inactive anywhere in the cluster. // Notifies cluster peers through config change. func (a *App) EnablePlugin(id string) *model.AppError { - pluginsEnvironment := a.GetPluginsEnvironment() + return a.Srv().enablePlugin(id) +} + +func (s *Server) enablePlugin(id string) *model.AppError { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return model.NewAppError("EnablePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -372,12 +397,12 @@ func (a *App) EnablePlugin(id string) *model.AppError { return model.NewAppError("EnablePlugin", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound) } - a.UpdateConfig(func(cfg *model.Config) { + s.UpdateConfig(func(cfg *model.Config) { cfg.PluginSettings.PluginStates[id] = &model.PluginState{Enable: true} }) // This call will implicitly invoke SyncPluginsActiveState which will activate enabled plugins. - if err := a.SaveConfig(a.Config(), true); err != nil { + if err := s.SaveConfig(s.Config(), true); err != nil { if err.Id == "ent.cluster.save_config.error" { return model.NewAppError("EnablePlugin", "app.plugin.cluster.save_config.app_error", nil, "", http.StatusInternalServerError) } @@ -390,7 +415,11 @@ func (a *App) EnablePlugin(id string) *model.AppError { // DisablePlugin will set the config for an installed plugin to disabled, triggering deactivation if active. // Notifies cluster peers through config change. func (a *App) DisablePlugin(id string) *model.AppError { - pluginsEnvironment := a.GetPluginsEnvironment() + return a.Srv().disablePlugin(id) +} + +func (s *Server) disablePlugin(id string) *model.AppError { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return model.NewAppError("DisablePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -414,13 +443,13 @@ func (a *App) DisablePlugin(id string) *model.AppError { return model.NewAppError("DisablePlugin", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound) } - a.UpdateConfig(func(cfg *model.Config) { + s.UpdateConfig(func(cfg *model.Config) { cfg.PluginSettings.PluginStates[id] = &model.PluginState{Enable: false} }) - a.UnregisterPluginCommands(id) + s.unregisterPluginCommands(id) // This call will implicitly invoke SyncPluginsActiveState which will deactivate disabled plugins. - if err := a.SaveConfig(a.Config(), true); err != nil { + if err := s.SaveConfig(s.Config(), true); err != nil { return model.NewAppError("DisablePlugin", "app.plugin.config.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -505,8 +534,8 @@ func (a *App) GetMarketplacePlugins(filter *model.MarketplacePluginFilter) ([]*m } // getPrepackagedPlugin returns a pre-packaged plugin. -func (a *App) getPrepackagedPlugin(pluginID, version string) (*plugin.PrepackagedPlugin, *model.AppError) { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) getPrepackagedPlugin(pluginID, version string) (*plugin.PrepackagedPlugin, *model.AppError) { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil, model.NewAppError("getPrepackagedPlugin", "app.plugin.config.app_error", nil, "plugin environment is nil", http.StatusInternalServerError) } @@ -522,16 +551,16 @@ func (a *App) getPrepackagedPlugin(pluginID, version string) (*plugin.Prepackage } // getRemoteMarketplacePlugin returns plugin from marketplace-server. -func (a *App) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) { +func (s *Server) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) { marketplaceClient, err := marketplace.NewClient( - *a.Config().PluginSettings.MarketplaceUrl, - a.HTTPService(), + *s.Config().PluginSettings.MarketplaceUrl, + s.HTTPService, ) if err != nil { return nil, model.NewAppError("GetMarketplacePlugin", "app.plugin.marketplace_client.app_error", nil, err.Error(), http.StatusInternalServerError) } - filter := a.getBaseMarketplaceFilter() + filter := s.getBaseMarketplaceFilter() filter.PluginId = pluginID filter.ReturnAllVersions = true @@ -682,11 +711,15 @@ func (a *App) mergeLocalPlugins(remoteMarketplacePlugins map[string]*model.Marke } func (a *App) getBaseMarketplaceFilter() *model.MarketplacePluginFilter { + return a.Srv().getBaseMarketplaceFilter() +} + +func (s *Server) getBaseMarketplaceFilter() *model.MarketplacePluginFilter { filter := &model.MarketplacePluginFilter{ ServerVersion: model.CurrentVersion, } - license := a.Srv().License() + license := s.License() if license != nil && *license.Features.EnterprisePlugins { filter.EnterprisePlugins = true } @@ -733,8 +766,8 @@ func pluginMatchesFilter(manifest *model.Manifest, filter string) bool { // it will notify all connected websocket clients (across all peers) to trigger the (re-)installation. // There is a small chance that this never occurs, because the last server to finish installing dies before it can announce. // There is also a chance that multiple servers notify, but the webapp handles this idempotently. -func (a *App) notifyPluginEnabled(manifest *model.Manifest) error { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) notifyPluginEnabled(manifest *model.Manifest) error { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return errors.New("pluginsEnvironment is nil") } @@ -744,15 +777,15 @@ func (a *App) notifyPluginEnabled(manifest *model.Manifest) error { var statuses model.PluginStatuses - if a.Cluster() != nil { + if s.Cluster != nil { var err *model.AppError - statuses, err = a.Cluster().GetPluginStatuses() + statuses, err = s.Cluster.GetPluginStatuses() if err != nil { return err } } - localStatus, err := a.GetPluginStatus(manifest.Id) + localStatus, err := s.GetPluginStatus(manifest.Id) if err != nil { return err } @@ -772,26 +805,26 @@ func (a *App) notifyPluginEnabled(manifest *model.Manifest) error { // Notify all cluster peer clients. message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_ENABLED, "", "", "", nil) message.Add("manifest", manifest.ClientManifest()) - a.Publish(message) + s.Publish(message) return nil } -func (a *App) getPluginsFromFolder() (map[string]*pluginSignaturePath, *model.AppError) { - fileStorePaths, appErr := a.ListDirectory(fileStorePluginFolder) +func (s *Server) getPluginsFromFolder() (map[string]*pluginSignaturePath, *model.AppError) { + fileStorePaths, appErr := s.listDirectory(fileStorePluginFolder) if appErr != nil { return nil, model.NewAppError("getPluginsFromDir", "app.plugin.sync.list_filestore.app_error", nil, appErr.Error(), http.StatusInternalServerError) } - return a.getPluginsFromFilePaths(fileStorePaths), nil + return s.getPluginsFromFilePaths(fileStorePaths), nil } -func (a *App) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pluginSignaturePath { +func (s *Server) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pluginSignaturePath { pluginSignaturePathMap := make(map[string]*pluginSignaturePath) fsPrefix := "" - if *a.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 { - ptr := a.Config().FileSettings.AmazonS3PathPrefix + if *s.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 { + ptr := s.Config().FileSettings.AmazonS3PathPrefix if ptr != nil && *ptr != "" { fsPrefix = *ptr + "/" } @@ -824,7 +857,7 @@ func (a *App) getPluginsFromFilePaths(fileStorePaths []string) map[string]*plugi return pluginSignaturePathMap } -func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.PrepackagedPlugin { +func (s *Server) processPrepackagedPlugins(pluginsDir string) []*plugin.PrepackagedPlugin { prepackagedPluginsDir, found := fileutils.FindDir(pluginsDir) if !found { return nil @@ -840,7 +873,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged return nil } - pluginSignaturePathMap := a.getPluginsFromFilePaths(fileStorePaths) + pluginSignaturePathMap := s.getPluginsFromFilePaths(fileStorePaths) plugins := make([]*plugin.PrepackagedPlugin, 0, len(pluginSignaturePathMap)) prepackagedPlugins := make(chan *plugin.PrepackagedPlugin, len(pluginSignaturePathMap)) @@ -849,7 +882,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged wg.Add(1) go func(psPath *pluginSignaturePath) { defer wg.Done() - p, err := a.processPrepackagedPlugin(psPath) + p, err := s.processPrepackagedPlugin(psPath) if err != nil { mlog.Error("Failed to install prepackaged plugin", mlog.String("path", psPath.path), mlog.Err(err)) return @@ -870,7 +903,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged // processPrepackagedPlugin will return the prepackaged plugin metadata and will also // install the prepackaged plugin if it had been previously enabled and AutomaticPrepackagedPlugins is true. -func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin.PrepackagedPlugin, error) { +func (s *Server) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin.PrepackagedPlugin, error) { mlog.Debug("Processing prepackaged plugin", mlog.String("path", pluginPath.path)) fileReader, err := os.Open(pluginPath.path) @@ -891,18 +924,18 @@ func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin } // Skip installing the plugin at all if automatic prepackaged plugins is disabled - if !*a.Config().PluginSettings.AutomaticPrepackagedPlugins { + if !*s.Config().PluginSettings.AutomaticPrepackagedPlugins { return plugin, nil } // Skip installing if the plugin is has not been previously enabled. - pluginState := a.Config().PluginSettings.PluginStates[plugin.Manifest.Id] + pluginState := s.Config().PluginSettings.PluginStates[plugin.Manifest.Id] if pluginState == nil || !pluginState.Enable { return plugin, nil } mlog.Debug("Installing prepackaged plugin", mlog.String("path", pluginPath.path)) - if _, err := a.installExtractedPlugin(plugin.Manifest, pluginDir, installPluginLocallyOnlyIfNewOrUpgrade); err != nil { + if _, err := s.installExtractedPlugin(plugin.Manifest, pluginDir, installPluginLocallyOnlyIfNewOrUpgrade); err != nil { return nil, errors.Wrapf(err, "Failed to install extracted prepackaged plugin %s", pluginPath.path) } @@ -910,24 +943,24 @@ func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin } // installFeatureFlagPlugins handles the automatic installation/upgrade of plugins from feature flags -func (a *App) installFeatureFlagPlugins() { - ffControledPlugins := a.Config().FeatureFlags.Plugins() +func (s *Server) installFeatureFlagPlugins() { + ffControledPlugins := s.Config().FeatureFlags.Plugins() // Respect the automatic prepackaged disable setting - if !*a.Config().PluginSettings.AutomaticPrepackagedPlugins { + if !*s.Config().PluginSettings.AutomaticPrepackagedPlugins { return } for pluginID, version := range ffControledPlugins { // Skip installing if the plugin has been previously disabled. - pluginState := a.Config().PluginSettings.PluginStates[pluginID] + pluginState := s.Config().PluginSettings.PluginStates[pluginID] if pluginState != nil && !pluginState.Enable { - a.Log().Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version)) + s.Log.Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version)) continue } // Check if we already installed this version as InstallMarketplacePlugin can't handle re-installs well. - pluginStatus, err := a.Srv().GetPluginStatus(pluginID) + pluginStatus, err := s.GetPluginStatus(pluginID) pluginExists := err == nil if pluginExists && pluginStatus.Version == version { continue @@ -935,37 +968,37 @@ func (a *App) installFeatureFlagPlugins() { if version != "" && version != "control" { // If we are on-prem skip installation if this is a downgrade - license := a.Srv().License() + license := s.License() inCloud := license != nil && *license.Features.Cloud if !inCloud && pluginExists { parsedVersion, err := semver.Parse(version) if err != nil { - a.Log().Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) + s.Log.Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) return } parsedExistingVersion, err := semver.Parse(pluginStatus.Version) if err != nil { - a.Log().Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version)) + s.Log.Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version)) return } if parsedVersion.LTE(parsedExistingVersion) { - a.Log().Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version)) + s.Log.Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version)) return } } - _, err := a.InstallMarketplacePlugin(&model.InstallMarketplacePluginRequest{ + _, err := s.installMarketplacePlugin(&model.InstallMarketplacePluginRequest{ Id: pluginID, Version: version, }) if err != nil { - a.Log().Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) + s.Log.Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) } else { - if err := a.EnablePlugin(pluginID); err != nil { - a.Log().Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) + if err := s.enablePlugin(pluginID); err != nil { + s.Log.Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version)) } else { - a.Log().Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version)) + s.Log.Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version)) } } } diff --git a/app/plugin_api.go b/app/plugin_api.go index 1dd978bdae1..dc01e2cfb73 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -15,6 +15,7 @@ import ( "path/filepath" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -23,14 +24,16 @@ import ( type PluginAPI struct { id string app *App + ctx *request.Context logger *mlog.SugarLogger manifest *model.Manifest } -func NewPluginAPI(a *App, manifest *model.Manifest) *PluginAPI { +func NewPluginAPI(a *App, c *request.Context, manifest *model.Manifest) *PluginAPI { return &PluginAPI{ id: manifest.Id, manifest: manifest, + ctx: c, app: a, logger: a.Log().With(mlog.String("plugin_id", manifest.Id)).Sugar(), } @@ -79,7 +82,7 @@ func (api *PluginAPI) ExecuteSlashCommand(commandArgs *model.CommandArgs) (*mode } commandArgs.T = i18n.GetUserTranslations(user.Locale) commandArgs.SiteURL = api.app.GetSiteURL() - response, appErr := api.app.ExecuteCommand(commandArgs) + response, appErr := api.app.ExecuteCommand(api.ctx, commandArgs) if appErr != nil { return response, appErr } @@ -153,7 +156,7 @@ func (api *PluginAPI) GetTelemetryId() string { } func (api *PluginAPI) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { - return api.app.CreateTeam(team) + return api.app.CreateTeam(api.ctx, team) } func (api *PluginAPI) DeleteTeam(teamID string) *model.AppError { @@ -190,11 +193,11 @@ func (api *PluginAPI) GetTeamsForUser(userID string) ([]*model.Team, *model.AppE } func (api *PluginAPI) CreateTeamMember(teamID, userID string) (*model.TeamMember, *model.AppError) { - return api.app.AddTeamMember(teamID, userID) + return api.app.AddTeamMember(api.ctx, teamID, userID) } func (api *PluginAPI) CreateTeamMembers(teamID string, userIDs []string, requestorId string) ([]*model.TeamMember, *model.AppError) { - members, err := api.app.AddTeamMembers(teamID, userIDs, requestorId, false) + members, err := api.app.AddTeamMembers(api.ctx, teamID, userIDs, requestorId, false) if err != nil { return nil, err } @@ -202,11 +205,11 @@ func (api *PluginAPI) CreateTeamMembers(teamID string, userIDs []string, request } func (api *PluginAPI) CreateTeamMembersGracefully(teamID string, userIDs []string, requestorId string) ([]*model.TeamMemberWithError, *model.AppError) { - return api.app.AddTeamMembers(teamID, userIDs, requestorId, true) + return api.app.AddTeamMembers(api.ctx, teamID, userIDs, requestorId, true) } func (api *PluginAPI) DeleteTeamMember(teamID, userID, requestorId string) *model.AppError { - return api.app.RemoveUserFromTeam(teamID, userID, requestorId) + return api.app.RemoveUserFromTeam(api.ctx, teamID, userID, requestorId) } func (api *PluginAPI) GetTeamMembers(teamID string, page, perPage int) ([]*model.TeamMember, *model.AppError) { @@ -230,7 +233,7 @@ func (api *PluginAPI) GetTeamStats(teamID string) (*model.TeamStats, *model.AppE } func (api *PluginAPI) CreateUser(user *model.User) (*model.User, *model.AppError) { - return api.app.CreateUser(user) + return api.app.CreateUser(api.ctx, user) } func (api *PluginAPI) DeleteUser(userID string) *model.AppError { @@ -238,7 +241,7 @@ func (api *PluginAPI) DeleteUser(userID string) *model.AppError { if err != nil { return err } - _, err = api.app.UpdateActive(user, false) + _, err = api.app.UpdateActive(api.ctx, user, false) return err } @@ -284,7 +287,7 @@ func (api *PluginAPI) UpdateUser(user *model.User) (*model.User, *model.AppError } func (api *PluginAPI) UpdateUserActive(userID string, active bool) *model.AppError { - return api.app.UpdateUserActive(userID, active) + return api.app.UpdateUserActive(api.ctx, userID, active) } func (api *PluginAPI) GetUserStatus(userID string) (*model.Status, *model.AppError) { @@ -363,7 +366,7 @@ func (api *PluginAPI) GetLDAPUserAttributes(userID string, attributes []string) } func (api *PluginAPI) CreateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { - return api.app.CreateChannel(channel, false) + return api.app.CreateChannel(api.ctx, channel, false) } func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError { @@ -371,7 +374,7 @@ func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError { if err != nil { return err } - return api.app.DeleteChannel(channel, "") + return api.app.DeleteChannel(api.ctx, channel, "") } func (api *PluginAPI) GetPublicChannelsForTeam(teamID string, page, perPage int) ([]*model.Channel, *model.AppError) { @@ -415,7 +418,7 @@ func (api *PluginAPI) GetChannelStats(channelID string) (*model.ChannelStats, *m } func (api *PluginAPI) GetDirectChannel(userID1, userID2 string) (*model.Channel, *model.AppError) { - return api.app.GetOrCreateDirectChannel(userID1, userID2) + return api.app.GetOrCreateDirectChannel(api.ctx, userID1, userID2) } func (api *PluginAPI) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { @@ -482,7 +485,7 @@ func (api *PluginAPI) SearchPostsInTeamForUser(teamID string, userID string, sea includeDeletedChannels = *searchParams.IncludeDeletedChannels } - return api.app.SearchPostsInTeamForUser(terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) + return api.app.SearchPostsInTeamForUser(api.ctx, terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage) } func (api *PluginAPI) AddChannelMember(channelID, userID string) (*model.ChannelMember, *model.AppError) { @@ -491,7 +494,7 @@ func (api *PluginAPI) AddChannelMember(channelID, userID string) (*model.Channel return nil, err } - return api.app.AddChannelMember(userID, channel, ChannelMemberOpts{ + return api.app.AddChannelMember(api.ctx, userID, channel, ChannelMemberOpts{ // For now, don't allow overriding these via the plugin API. UserRequestorID: "", PostRootID: "", @@ -504,7 +507,7 @@ func (api *PluginAPI) AddUserToChannel(channelID, userID, asUserID string) (*mod return nil, err } - return api.app.AddChannelMember(userID, channel, ChannelMemberOpts{ + return api.app.AddChannelMember(api.ctx, userID, channel, ChannelMemberOpts{ UserRequestorID: asUserID, }) } @@ -534,7 +537,7 @@ func (api *PluginAPI) UpdateChannelMemberNotifications(channelID, userID string, } func (api *PluginAPI) DeleteChannelMember(channelID, userID string) *model.AppError { - return api.app.LeaveChannel(channelID, userID) + return api.app.LeaveChannel(api.ctx, channelID, userID) } func (api *PluginAPI) GetGroup(groupId string) (*model.Group, *model.AppError) { @@ -560,15 +563,15 @@ func (api *PluginAPI) GetGroupsForUser(userID string) ([]*model.Group, *model.Ap } func (api *PluginAPI) CreatePost(post *model.Post) (*model.Post, *model.AppError) { - return api.app.CreatePostMissingChannel(post, true) + return api.app.CreatePostMissingChannel(api.ctx, post, true) } func (api *PluginAPI) AddReaction(reaction *model.Reaction) (*model.Reaction, *model.AppError) { - return api.app.SaveReactionForPost(reaction) + return api.app.SaveReactionForPost(api.ctx, reaction) } func (api *PluginAPI) RemoveReaction(reaction *model.Reaction) *model.AppError { - return api.app.DeleteReactionForPost(reaction) + return api.app.DeleteReactionForPost(api.ctx, reaction) } func (api *PluginAPI) GetReactions(postID string) ([]*model.Reaction, *model.AppError) { @@ -617,7 +620,7 @@ func (api *PluginAPI) GetPostsForChannel(channelID string, page, perPage int) (* } func (api *PluginAPI) UpdatePost(post *model.Post) (*model.Post, *model.AppError) { - return api.app.UpdatePost(post, false) + return api.app.UpdatePost(api.ctx, post, false) } func (api *PluginAPI) GetProfileImage(userID string) ([]byte, *model.AppError) { @@ -689,7 +692,7 @@ func (api *PluginAPI) GetFile(fileID string) ([]byte, *model.AppError) { } func (api *PluginAPI) UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) { - return api.app.UploadFile(data, channelID, filename) + return api.app.UploadFile(api.ctx, data, channelID, filename) } func (api *PluginAPI) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) { @@ -885,7 +888,7 @@ func (api *PluginAPI) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) { } } - return api.app.CreateBot(bot) + return api.app.CreateBot(api.ctx, bot) } func (api *PluginAPI) PatchBot(userID string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) { @@ -903,7 +906,7 @@ func (api *PluginAPI) GetBots(options *model.BotGetOptions) ([]*model.Bot, *mode } func (api *PluginAPI) UpdateBotActive(userID string, active bool) (*model.Bot, *model.AppError) { - return api.app.UpdateBotActive(userID, active) + return api.app.UpdateBotActive(api.ctx, userID, active) } func (api *PluginAPI) PermanentDeleteBot(userID string) *model.AppError { diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index 70bf95b230e..3a77edd8e24 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -25,6 +25,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces/mocks" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" @@ -68,7 +69,7 @@ func setDefaultPluginConfig(th *TestHelper, pluginID string) { }) } -func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, app *App) string { +func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, app *App, c *request.Context) string { pluginDir, err := ioutil.TempDir("", "") require.NoError(t, err) t.Cleanup(func() { @@ -87,7 +88,11 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests } }) - env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log(), nil) + newPluginAPI := func(manifest *model.Manifest) plugin.API { + return app.NewPluginAPI(c, manifest) + } + + env, err := plugin.NewEnvironment(newPluginAPI, pluginDir, webappPluginDir, app.Log(), nil) require.NoError(t, err) require.Equal(t, len(pluginCodes), len(pluginIDs)) @@ -115,8 +120,8 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests return pluginDir } -func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App) string { - return setupMultiPluginApiTest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginID}, app) +func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) string { + return setupMultiPluginApiTest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginID}, app, c) } func TestPublicFilesPathConfiguration(t *testing.T) { @@ -141,7 +146,7 @@ func TestPublicFilesPathConfiguration(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}`, pluginID, th.App) + `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}`, pluginID, th.App, th.Context) publicFilesFolderInTest := filepath.Join(pluginDir, pluginID, "public") publicFilesPath, err := th.App.GetPluginsEnvironment().PublicFilesPath(pluginID) @@ -154,13 +159,13 @@ func TestPluginAPIGetUserPreferences(t *testing.T) { defer th.TearDown() api := th.SetupPluginAPI() - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user1" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user1) + defer th.App.PermanentDeleteUser(th.Context, user1) preferences, err := api.GetPreferencesForUser(user1.Id) require.Nil(t, err) @@ -177,13 +182,13 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) { defer th.TearDown() api := th.SetupPluginAPI() - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user1" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user1) + defer th.App.PermanentDeleteUser(th.Context, user1) preferences, err := api.GetPreferencesForUser(user1.Id) require.Nil(t, err) @@ -195,13 +200,13 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) { require.Nil(t, err) assert.Equal(t, 0, len(preferences)) - user2, err := th.App.CreateUser(&model.User{ + user2, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user2" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user2) + defer th.App.PermanentDeleteUser(th.Context, user2) preference := model.Preference{ Name: user2.Id, @@ -229,13 +234,13 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) { defer th.TearDown() api := th.SetupPluginAPI() - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user1" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user1) + defer th.App.PermanentDeleteUser(th.Context, user1) preferences, err := api.GetPreferencesForUser(user1.Id) require.Nil(t, err) @@ -278,37 +283,37 @@ func TestPluginAPIGetUsers(t *testing.T) { defer th.TearDown() api := th.SetupPluginAPI() - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user1" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user1) + defer th.App.PermanentDeleteUser(th.Context, user1) - user2, err := th.App.CreateUser(&model.User{ + user2, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user2" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user2) + defer th.App.PermanentDeleteUser(th.Context, user2) - user3, err := th.App.CreateUser(&model.User{ + user3, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user3" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user3) + defer th.App.PermanentDeleteUser(th.Context, user3) - user4, err := th.App.CreateUser(&model.User{ + user4, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user4" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user4) + defer th.App.PermanentDeleteUser(th.Context, user4) testCases := []struct { Description string @@ -368,37 +373,37 @@ func TestPluginAPIGetUsersInTeam(t *testing.T) { team1 := th.CreateTeam() team2 := th.CreateTeam() - user1, err := th.App.CreateUser(&model.User{ + user1, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user1" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user1) + defer th.App.PermanentDeleteUser(th.Context, user1) - user2, err := th.App.CreateUser(&model.User{ + user2, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user2" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user2) + defer th.App.PermanentDeleteUser(th.Context, user2) - user3, err := th.App.CreateUser(&model.User{ + user3, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user3" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user3) + defer th.App.PermanentDeleteUser(th.Context, user3) - user4, err := th.App.CreateUser(&model.User{ + user4, err := th.App.CreateUser(th.Context, &model.User{ Email: strings.ToLower(model.NewId()) + "success+test@example.com", Password: "password", Username: "user4" + model.NewId(), }) require.Nil(t, err) - defer th.App.PermanentDeleteUser(user4) + defer th.App.PermanentDeleteUser(th.Context, user4) // Add all users to team 1 _, _, err = th.App.joinUserToTeam(team1, user1) @@ -478,7 +483,7 @@ func TestPluginAPIGetFile(t *testing.T) { uploadTime := time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local) filename := "testGetFile" fileData := []byte("Hello World") - info, err := th.App.DoUploadFile(uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData) + info, err := th.App.DoUploadFile(th.Context, 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) @@ -500,7 +505,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { defer th.TearDown() api := th.SetupPluginAPI() - fileInfo1, err := th.App.DoUploadFile( + fileInfo1, err := th.App.DoUploadFile(th.Context, time.Date(2020, 1, 1, 1, 1, 1, 1, time.UTC), th.BasicTeam.Id, th.BasicChannel.Id, @@ -514,7 +519,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { th.App.RemoveFile(fileInfo1.Path) }() - fileInfo2, err := th.App.DoUploadFile( + fileInfo2, err := th.App.DoUploadFile(th.Context, time.Date(2020, 1, 2, 1, 1, 1, 1, time.UTC), th.BasicTeam.Id, th.BasicChannel.Id, @@ -528,7 +533,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { th.App.RemoveFile(fileInfo2.Path) }() - fileInfo3, err := th.App.DoUploadFile( + fileInfo3, err := th.App.DoUploadFile(th.Context, time.Date(2020, 1, 3, 1, 1, 1, 1, time.UTC), th.BasicTeam.Id, th.BasicChannel.Id, @@ -598,7 +603,7 @@ func TestPluginAPISavePluginConfig(t *testing.T) { }, } - api := NewPluginAPI(th.App, manifest) + api := NewPluginAPI(th.App, th.Context, manifest) pluginConfigJsonString := `{"mystringsetting": "str", "MyIntSetting": 32, "myboolsetting": true}` @@ -641,7 +646,7 @@ func TestPluginAPIGetPluginConfig(t *testing.T) { }, } - api := NewPluginAPI(th.App, manifest) + api := NewPluginAPI(th.App, th.Context, manifest) pluginConfigJsonString := `{"mystringsetting": "str", "myintsetting": 32, "myboolsetting": true}` var pluginConfig map[string]interface{} @@ -761,7 +766,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(), nil) + env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), nil) require.NoError(t, err) pluginIDs := []string{"pluginid1", "pluginid2", "pluginid3"} @@ -834,7 +839,7 @@ func TestInstallPlugin(t *testing.T) { // we need a modified version of setupPluginApiTest() because it wasn't possible to use it directly here // since it removes plugin dirs right after it returns, does not update App configs with the plugin // dirs and this behavior tends to break this test as a result. - setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App) (func(), string) { + setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) (func(), string) { pluginDir, err := ioutil.TempDir("", "") require.NoError(t, err) webappPluginDir, err := ioutil.TempDir("", "") @@ -845,7 +850,11 @@ func TestInstallPlugin(t *testing.T) { *cfg.PluginSettings.ClientDirectory = webappPluginDir }) - env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log(), nil) + newPluginAPI := func(manifest *model.Manifest) plugin.API { + return app.NewPluginAPI(c, manifest) + } + + env, err := plugin.NewEnvironment(newPluginAPI, pluginDir, webappPluginDir, app.Log(), nil) require.NoError(t, err) app.SetPluginsEnvironment(env) @@ -935,7 +944,7 @@ func TestInstallPlugin(t *testing.T) { "type": "text" } ] - }}`, "testinstallplugin", th.App) + }}`, "testinstallplugin", th.App, th.Context) defer tearDown() hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin("testinstallplugin") @@ -1046,7 +1055,7 @@ func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string, } setupPluginApiTest(t, code, fmt.Sprintf(`{"id": "%v", "backend": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema), - id, th.App) + id, th.App, th.Context) hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin(id) require.NoError(t, err) require.NotNil(t, hooks) @@ -1473,6 +1482,7 @@ func TestInterpluginPluginHTTP(t *testing.T) { "testplugininterclient", }, th.App, + th.Context, ) hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin("testplugininterclient") @@ -1495,7 +1505,7 @@ func TestApiMetrics(t *testing.T) { defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) - env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock) + env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock) require.NoError(t, err) th.App.SetPluginsEnvironment(env) @@ -1547,7 +1557,7 @@ func TestApiMetrics(t *testing.T) { Password: "passwd1", AuthService: "", } - _, appErr := th.App.CreateUser(user1) + _, appErr := th.App.CreateUser(th.Context, user1) require.Nil(t, appErr) time.Sleep(1 * time.Second) user1, appErr = th.App.GetUser(user1.Id) @@ -1617,7 +1627,7 @@ func TestPluginHTTPConnHijack(t *testing.T) { require.NoError(t, err) require.NotEmpty(t, pluginCode) - tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.App.NewPluginAPI) + tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.NewPluginAPI) defer tearDown() require.NoError(t, errors[0]) require.Len(t, ids, 1) @@ -1652,7 +1662,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) { require.NoError(t, err) require.NotEmpty(t, pluginCode) - tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.App.NewPluginAPI) + tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.NewPluginAPI) defer tearDown() require.NoError(t, errors[0]) require.Len(t, ids, 1) @@ -1702,7 +1712,7 @@ func (*MockSlashCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model DisplayName: "mock", } } -func (mscp *MockSlashCommandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { +func (mscp *MockSlashCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { mscp.Args = args mscp.Message = message return &model.CommandResponse{ diff --git a/app/plugin_commands.go b/app/plugin_commands.go index 1875c28908c..c7b9c1192b4 100644 --- a/app/plugin_commands.go +++ b/app/plugin_commands.go @@ -11,6 +11,7 @@ import ( "github.com/pkg/errors" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" ) @@ -88,16 +89,20 @@ func (a *App) UnregisterPluginCommand(pluginID, teamID, trigger string) { } func (a *App) UnregisterPluginCommands(pluginID string) { - a.Srv().pluginCommandsLock.Lock() - defer a.Srv().pluginCommandsLock.Unlock() + a.Srv().unregisterPluginCommands(pluginID) +} + +func (s *Server) unregisterPluginCommands(pluginID string) { + s.pluginCommandsLock.Lock() + defer s.pluginCommandsLock.Unlock() var remaining []*PluginCommand - for _, pc := range a.Srv().pluginCommands { + for _, pc := range s.pluginCommands { if pc.PluginId != pluginID { remaining = append(remaining, pc) } } - a.Srv().pluginCommands = remaining + s.pluginCommands = remaining } func (a *App) PluginCommandsForTeam(teamID string) []*model.Command { @@ -115,7 +120,7 @@ func (a *App) PluginCommandsForTeam(teamID string) []*model.Command { // tryExecutePluginCommand attempts to run a command provided by a plugin based on the given arguments. If no such // command can be found, returns nil for all arguments. -func (a *App) tryExecutePluginCommand(args *model.CommandArgs) (*model.Command, *model.CommandResponse, *model.AppError) { +func (a *App) tryExecutePluginCommand(c *request.Context, args *model.CommandArgs) (*model.Command, *model.CommandResponse, *model.AppError) { parts := strings.Split(args.Command, " ") trigger := parts[0][1:] trigger = strings.ToLower(trigger) @@ -156,7 +161,7 @@ func (a *App) tryExecutePluginCommand(args *model.CommandArgs) (*model.Command, args.AddChannelMention(channelName, channelID) } - response, appErr := pluginHooks.ExecuteCommand(a.PluginContext(), args) + response, appErr := pluginHooks.ExecuteCommand(pluginContext(c), args) // Checking if plugin crashed after running the command if err := pluginsEnvironment.PerformHealthCheck(matched.PluginId); err != nil { diff --git a/app/plugin_commands_test.go b/app/plugin_commands_test.go index cafe469eb10..8145aca87fc 100644 --- a/app/plugin_commands_test.go +++ b/app/plugin_commands_test.go @@ -24,7 +24,7 @@ func TestPluginCommand(t *testing.T) { args.Command = "/plugin" t.Run("error before plugin command registered", func(t *testing.T) { - _, err := th.App.ExecuteCommand(args) + _, err := th.App.ExecuteCommand(th.Context, args) require.NotNil(t, err) }) @@ -86,12 +86,12 @@ func TestPluginCommand(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) require.Nil(t, nil, activationErrors[0]) - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType) require.Equal(t, "text", resp.Text) @@ -180,7 +180,7 @@ func TestPluginCommand(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) @@ -191,7 +191,7 @@ func TestPluginCommand(t *testing.T) { go func() { defer close(wait) - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) // Ignore if we kill below. if !killed { @@ -212,7 +212,7 @@ func TestPluginCommand(t *testing.T) { }) t.Run("error after plugin command unregistered", func(t *testing.T) { - _, err := th.App.ExecuteCommand(args) + _, err := th.App.ExecuteCommand(th.Context, args) require.NotNil(t, err) }) @@ -274,13 +274,13 @@ func TestPluginCommand(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) require.Nil(t, nil, activationErrors[0]) args.Command = "/code" - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType) require.Equal(t, "text", resp.Text) @@ -320,12 +320,12 @@ func TestPluginCommand(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) require.Nil(t, nil, activationErrors[0]) args.Command = "/code" - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, resp) require.NotNil(t, err) require.Equal(t, err.Id, "model.plugin_command_error.error.app_error") @@ -365,12 +365,12 @@ func TestPluginCommand(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) require.Nil(t, nil, activationErrors[0]) args.Command = "/code" - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, resp) require.NotNil(t, err) require.Equal(t, err.Id, "model.plugin_command_crash.error.app_error") diff --git a/app/plugin_context.go b/app/plugin_context.go index 0ac6e08eb94..9c5d89fe5ca 100644 --- a/app/plugin_context.go +++ b/app/plugin_context.go @@ -2,18 +2,3 @@ // See LICENSE.txt for license information. package app - -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(), - } - return context -} diff --git a/app/plugin_deadlock_test.go b/app/plugin_deadlock_test.go index 2518e27c164..8a4041ccde1 100644 --- a/app/plugin_deadlock_test.go +++ b/app/plugin_deadlock_test.go @@ -89,7 +89,7 @@ func TestPluginDeadlock(t *testing.T) { done := make(chan bool) go func() { - SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI) + SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI) close(done) }() @@ -196,7 +196,7 @@ func TestPluginDeadlock(t *testing.T) { done := make(chan bool) go func() { - SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI) + SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI) close(done) }() @@ -291,7 +291,7 @@ func TestPluginDeadlock(t *testing.T) { } require.False(t, messageWillBePostedCalled, "MessageWillBePosted should not have been called") - SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI) + SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI) th.TearDown() posts, appErr = th.App.GetPosts(th.BasicChannel.Id, 0, 2) diff --git a/app/plugin_event.go b/app/plugin_event.go index f2a307cfdb5..e3fbd78f2e8 100644 --- a/app/plugin_event.go +++ b/app/plugin_event.go @@ -7,10 +7,9 @@ import ( "github.com/mattermost/mattermost-server/v5/model" ) -// notifyClusterPluginEvent publishes `event` to other clusters. -func (a *App) notifyClusterPluginEvent(event string, data model.PluginEventData) { - if a.Cluster() != nil { - a.Cluster().SendClusterMessage(&model.ClusterMessage{ +func (s *Server) notifyClusterPluginEvent(event string, data model.PluginEventData) { + if s.Cluster != nil { + s.Cluster.SendClusterMessage(&model.ClusterMessage{ Event: event, SendType: model.CLUSTER_SEND_RELIABLE, WaitForAllToSend: true, diff --git a/app/plugin_health_check_test.go b/app/plugin_health_check_test.go index 058d00716bc..fb07cd1689b 100644 --- a/app/plugin_health_check_test.go +++ b/app/plugin_health_check_test.go @@ -37,7 +37,7 @@ func TestHealthCheckJob(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() env := th.App.GetPluginsEnvironment() diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index 0b159355663..02edfbfdb81 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -5,6 +5,7 @@ package app import ( "bytes" + "context" "io" "io/ioutil" "net/http" @@ -19,6 +20,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces/mocks" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" @@ -87,7 +89,7 @@ func TestHookMessageWillBePosted(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -96,7 +98,7 @@ func TestHookMessageWillBePosted(t *testing.T) { Message: "message_", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.CreatePost(post, th.BasicChannel, false, true) + _, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) if assert.NotNil(t, err) { assert.Equal(t, "Post rejected by plugin. rejected", err.Message) } @@ -128,7 +130,7 @@ func TestHookMessageWillBePosted(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -137,7 +139,7 @@ func TestHookMessageWillBePosted(t *testing.T) { Message: "message_", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.CreatePost(post, th.BasicChannel, false, true) + _, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) if assert.NotNil(t, err) { assert.Equal(t, "Post rejected by plugin. rejected", err.Message) } @@ -168,7 +170,7 @@ func TestHookMessageWillBePosted(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -177,7 +179,7 @@ func TestHookMessageWillBePosted(t *testing.T) { Message: "message", CreateAt: model.GetMillis() - 10000, } - post, err := th.App.CreatePost(post, th.BasicChannel, false, true) + post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "message", post.Message) @@ -212,7 +214,7 @@ func TestHookMessageWillBePosted(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -221,7 +223,7 @@ func TestHookMessageWillBePosted(t *testing.T) { Message: "message", CreateAt: model.GetMillis() - 10000, } - post, err := th.App.CreatePost(post, th.BasicChannel, false, true) + post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "message_fromplugin", post.Message) @@ -278,7 +280,7 @@ func TestHookMessageWillBePosted(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -287,7 +289,7 @@ func TestHookMessageWillBePosted(t *testing.T) { Message: "message", CreateAt: model.GetMillis() - 10000, } - post, err := th.App.CreatePost(post, th.BasicChannel, false, true) + post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "prefix_message_suffix", post.Message) }) @@ -331,7 +333,7 @@ func TestHookMessageHasBeenPosted(t *testing.T) { Message: "message", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.CreatePost(post, th.BasicChannel, false, true) + _, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) } @@ -361,7 +363,7 @@ func TestHookMessageWillBeUpdated(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() post := &model.Post{ @@ -370,11 +372,11 @@ func TestHookMessageWillBeUpdated(t *testing.T) { Message: "message_", CreateAt: model.GetMillis() - 10000, } - post, err := th.App.CreatePost(post, th.BasicChannel, false, true) + post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "message_", post.Message) post.Message = post.Message + "edited_" - post, err = th.App.UpdatePost(post, true) + post, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err) assert.Equal(t, "message_edited_fromplugin", post.Message) } @@ -418,11 +420,11 @@ func TestHookMessageHasBeenUpdated(t *testing.T) { Message: "message_", CreateAt: model.GetMillis() - 10000, } - post, err := th.App.CreatePost(post, th.BasicChannel, false, true) + post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "message_", post.Message) post.Message = post.Message + "edited" - _, err = th.App.UpdatePost(post, true) + _, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err) } @@ -460,7 +462,7 @@ func TestHookFileWillBeUploaded(t *testing.T) { }, th.App, func(*model.Manifest) plugin.API { return &mockAPI }) defer tearDown() - _, err := th.App.UploadFiles( + _, err := th.App.UploadFiles(th.Context, "noteam", th.BasicChannel.Id, th.BasicUser.Id, @@ -513,7 +515,7 @@ func TestHookFileWillBeUploaded(t *testing.T) { }, th.App, func(*model.Manifest) plugin.API { return &mockAPI }) defer tearDown() - _, err := th.App.UploadFiles( + _, err := th.App.UploadFiles(th.Context, "noteam", th.BasicChannel.Id, th.BasicUser.Id, @@ -560,7 +562,7 @@ func TestHookFileWillBeUploaded(t *testing.T) { }, th.App, func(*model.Manifest) plugin.API { return &mockAPI }) defer tearDown() - response, err := th.App.UploadFiles( + response, err := th.App.UploadFiles(th.Context, "noteam", th.BasicChannel.Id, th.BasicUser.Id, @@ -636,7 +638,7 @@ func TestHookFileWillBeUploaded(t *testing.T) { }, th.App, func(*model.Manifest) plugin.API { return &mockAPI }) defer tearDown() - response, err := th.App.UploadFiles( + response, err := th.App.UploadFiles(th.Context, "noteam", th.BasicChannel.Id, th.BasicUser.Id, @@ -690,12 +692,12 @@ func TestUserWillLogIn_Blocked(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() r := &http.Request{} w := httptest.NewRecorder() - err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false) + err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false) assert.Contains(t, err.Id, "Login rejected by plugin", "Expected Login rejected by plugin, got %s", err.Id) } @@ -729,15 +731,15 @@ func TestUserWillLogInIn_Passed(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() r := &http.Request{} w := httptest.NewRecorder() - err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false) + err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false) assert.Nil(t, err, "Expected nil, got %s", err) - assert.Equal(t, th.App.Session().UserId, th.BasicUser.Id) + assert.Equal(t, th.Context.Session().UserId, th.BasicUser.Id) } func TestUserHasLoggedIn(t *testing.T) { @@ -770,12 +772,12 @@ func TestUserHasLoggedIn(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() r := &http.Request{} w := httptest.NewRecorder() - err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false) + err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false) assert.Nil(t, err, "Expected nil, got %s", err) @@ -812,7 +814,7 @@ func TestUserHasBeenCreated(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() user := &model.User{ @@ -822,7 +824,7 @@ func TestUserHasBeenCreated(t *testing.T) { Password: "passwd1", AuthService: "", } - _, err := th.App.CreateUser(user) + _, err := th.App.CreateUser(th.Context, user) require.Nil(t, err) time.Sleep(1 * time.Second) @@ -859,7 +861,7 @@ func TestErrorString(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) @@ -889,7 +891,7 @@ func TestErrorString(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, activationErrors, 1) @@ -909,19 +911,16 @@ 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() + ctx := request.NewContext(context.Background(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.Session{}, nil) + ctx.Session().Id = 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", ctx.Session().Id).Return(nil) + mockAPI.On("LogInfo", ctx.RequestId()).Return(nil) + mockAPI.On("LogError", ctx.IpAddress()).Return(nil) + mockAPI.On("LogWarn", ctx.AcceptLanguage()).Return(nil) + mockAPI.On("DeleteTeam", ctx.UserAgent()).Return(nil) tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{ @@ -957,7 +956,7 @@ func TestHookContext(t *testing.T) { Message: "not this", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.CreatePost(post, th.BasicChannel, false, true) + _, err := th.App.CreatePost(ctx, post, th.BasicChannel, false, true) require.Nil(t, err) } @@ -996,7 +995,7 @@ func TestActiveHooks(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `}, th.App, th.App.NewPluginAPI) + `}, th.App, th.NewPluginAPI) defer tearDown() require.Len(t, pluginIDs, 1) @@ -1010,7 +1009,7 @@ func TestActiveHooks(t *testing.T) { Password: "passwd1", AuthService: "", } - _, appErr := th.App.CreateUser(user1) + _, appErr := th.App.CreateUser(th.Context, user1) require.Nil(t, appErr) time.Sleep(1 * time.Second) user1, appErr = th.App.GetUser(user1.Id) @@ -1046,7 +1045,7 @@ func TestHookMetrics(t *testing.T) { defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) - env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock) + env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock) require.NoError(t, err) th.App.SetPluginsEnvironment(env) @@ -1116,7 +1115,7 @@ func TestHookMetrics(t *testing.T) { Password: "passwd1", AuthService: "", } - _, appErr := th.App.CreateUser(user1) + _, appErr := th.App.CreateUser(th.Context, user1) require.Nil(t, appErr) time.Sleep(1 * time.Second) user1, appErr = th.App.GetUser(user1.Id) @@ -1169,7 +1168,7 @@ func TestHookReactionHasBeenAdded(t *testing.T) { EmojiName: "smile", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.SaveReactionForPost(reaction) + _, err := th.App.SaveReactionForPost(th.Context, reaction) require.Nil(t, err) } @@ -1212,7 +1211,7 @@ func TestHookReactionHasBeenRemoved(t *testing.T) { CreateAt: model.GetMillis() - 10000, } - err := th.App.DeleteReactionForPost(reaction) + err := th.App.DeleteReactionForPost(th.Context, reaction) require.Nil(t, err) } diff --git a/app/plugin_install.go b/app/plugin_install.go index f0e4b7a3d09..0aade1809ea 100644 --- a/app/plugin_install.go +++ b/app/plugin_install.go @@ -62,9 +62,13 @@ const managedPluginFileName = ".filestore" const fileStorePluginFolder = "plugins" func (a *App) InstallPluginFromData(data model.PluginEventData) { + a.Srv().installPluginFromData(data) +} + +func (s *Server) installPluginFromData(data model.PluginEventData) { mlog.Debug("Installing plugin as per cluster message", mlog.String("plugin_id", data.Id)) - pluginSignaturePathMap, appErr := a.getPluginsFromFolder() + pluginSignaturePathMap, appErr := s.getPluginsFromFolder() if appErr != nil { mlog.Error("Failed to get plugin signatures from filestore. Can't install plugin from data.", mlog.Err(appErr)) return @@ -75,7 +79,7 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) { return } - reader, appErr := a.FileReader(plugin.path) + reader, appErr := s.fileReader(plugin.path) if appErr != nil { mlog.Error("Failed to open plugin bundle from file store.", mlog.String("bundle", plugin.path), mlog.Err(appErr)) return @@ -83,8 +87,8 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) { defer reader.Close() var signature filestore.ReadCloseSeeker - if *a.Config().PluginSettings.RequirePluginSignature { - signature, appErr = a.FileReader(plugin.signaturePath) + if *s.Config().PluginSettings.RequirePluginSignature { + signature, appErr = s.fileReader(plugin.signaturePath) if appErr != nil { mlog.Error("Failed to open plugin signature from file store.", mlog.Err(appErr)) return @@ -92,36 +96,44 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) { defer signature.Close() } - manifest, appErr := a.installPluginLocally(reader, signature, installPluginLocallyAlways) + manifest, appErr := s.installPluginLocally(reader, signature, installPluginLocallyAlways) if appErr != nil { mlog.Error("Failed to sync plugin from file store", mlog.String("bundle", plugin.path), mlog.Err(appErr)) return } - if err := a.notifyPluginEnabled(manifest); err != nil { + if err := s.notifyPluginEnabled(manifest); err != nil { mlog.Error("Failed notify plugin enabled", mlog.Err(err)) } - if err := a.notifyPluginStatusesChanged(); err != nil { + if err := s.notifyPluginStatusesChanged(); err != nil { mlog.Error("Failed to notify plugin status changed", mlog.Err(err)) } } func (a *App) RemovePluginFromData(data model.PluginEventData) { + a.Srv().removePluginFromData(data) +} + +func (s *Server) removePluginFromData(data model.PluginEventData) { mlog.Debug("Removing plugin as per cluster message", mlog.String("plugin_id", data.Id)) - if err := a.removePluginLocally(data.Id); err != nil { + if err := s.removePluginLocally(data.Id); err != nil { mlog.Warn("Failed to remove plugin locally", mlog.Err(err), mlog.String("id", data.Id)) } - if err := a.notifyPluginStatusesChanged(); err != nil { + if err := s.notifyPluginStatusesChanged(); err != nil { mlog.Warn("failed to notify plugin status changed", mlog.Err(err)) } } // InstallPluginWithSignature verifies and installs plugin. func (a *App) InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) { - return a.installPlugin(pluginFile, signature, installPluginLocallyAlways) + return a.Srv().installPluginWithSignature(pluginFile, signature) +} + +func (s *Server) installPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) { + return s.installPlugin(pluginFile, signature, installPluginLocallyAlways) } // InstallPlugin unpacks and installs a plugin but does not enable or activate it. @@ -135,36 +147,40 @@ func (a *App) InstallPlugin(pluginFile io.ReadSeeker, replace bool) (*model.Mani } func (a *App) installPlugin(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { - manifest, appErr := a.installPluginLocally(pluginFile, signature, installationStrategy) + return a.Srv().installPlugin(pluginFile, signature, installationStrategy) +} + +func (s *Server) installPlugin(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { + manifest, appErr := s.installPluginLocally(pluginFile, signature, installationStrategy) if appErr != nil { return nil, appErr } if signature != nil { signature.Seek(0, 0) - if _, appErr = a.WriteFile(signature, a.getSignatureStorePath(manifest.Id)); appErr != nil { + if _, appErr = s.writeFile(signature, getSignatureStorePath(manifest.Id)); appErr != nil { return nil, model.NewAppError("saveSignature", "app.plugin.store_signature.app_error", nil, appErr.Error(), http.StatusInternalServerError) } } // Store bundle in the file store to allow access from other servers. pluginFile.Seek(0, 0) - if _, appErr := a.WriteFile(pluginFile, a.getBundleStorePath(manifest.Id)); appErr != nil { + if _, appErr := s.writeFile(pluginFile, getBundleStorePath(manifest.Id)); appErr != nil { return nil, model.NewAppError("uploadPlugin", "app.plugin.store_bundle.app_error", nil, appErr.Error(), http.StatusInternalServerError) } - a.notifyClusterPluginEvent( + s.notifyClusterPluginEvent( model.CLUSTER_EVENT_INSTALL_PLUGIN, model.PluginEventData{ Id: manifest.Id, }, ) - if err := a.notifyPluginEnabled(manifest); err != nil { + if err := s.notifyPluginEnabled(manifest); err != nil { mlog.Warn("Failed notify plugin enabled", mlog.Err(err)) } - if err := a.notifyPluginStatusesChanged(); err != nil { + if err := s.notifyPluginStatusesChanged(); err != nil { mlog.Warn("Failed to notify plugin status changed", mlog.Err(err)) } @@ -174,9 +190,13 @@ func (a *App) installPlugin(pluginFile, signature io.ReadSeeker, installationStr // InstallMarketplacePlugin installs a plugin listed in the marketplace server. It will get the plugin bundle // from the prepackaged folder, if available, or remotely if EnableRemoteMarketplace is true. func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) { + return a.Srv().installMarketplacePlugin(request) +} + +func (s *Server) installMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) { var pluginFile, signatureFile io.ReadSeeker - prepackagedPlugin, appErr := a.getPrepackagedPlugin(request.Id, request.Version) + prepackagedPlugin, appErr := s.getPrepackagedPlugin(request.Id, request.Version) if appErr != nil && appErr.Id != "app.plugin.marketplace_plugins.not_found.app_error" { return nil, appErr } @@ -192,14 +212,14 @@ func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRe signatureFile = bytes.NewReader(prepackagedPlugin.Signature) } - if *a.Config().PluginSettings.EnableRemoteMarketplace && pluginFile == nil { + if *s.Config().PluginSettings.EnableRemoteMarketplace && pluginFile == nil { var plugin *model.BaseMarketplacePlugin - plugin, appErr = a.getRemoteMarketplacePlugin(request.Id, request.Version) + plugin, appErr = s.getRemoteMarketplacePlugin(request.Id, request.Version) if appErr != nil { return nil, appErr } - downloadedPluginBytes, err := a.DownloadFromURL(plugin.DownloadURL) + downloadedPluginBytes, err := s.downloadFromURL(plugin.DownloadURL) if err != nil { return nil, model.NewAppError("InstallMarketplacePlugin", "app.plugin.install_marketplace_plugin.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -218,7 +238,7 @@ func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRe return nil, model.NewAppError("InstallMarketplacePlugin", "app.plugin.marketplace_plugins.signature_not_found.app_error", nil, "", http.StatusInternalServerError) } - manifest, appErr := a.InstallPluginWithSignature(pluginFile, signatureFile) + manifest, appErr := s.installPluginWithSignature(pluginFile, signatureFile) if appErr != nil { return nil, appErr } @@ -238,14 +258,18 @@ const ( ) func (a *App) installPluginLocally(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { - pluginsEnvironment := a.GetPluginsEnvironment() + return a.Srv().installPluginLocally(pluginFile, signature, installationStrategy) +} + +func (s *Server) installPluginLocally(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil, model.NewAppError("installPluginLocally", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } // verify signature if signature != nil { - if err := a.VerifyPlugin(pluginFile, signature); err != nil { + if err := s.verifyPlugin(pluginFile, signature); err != nil { return nil, err } } @@ -261,7 +285,7 @@ func (a *App) installPluginLocally(pluginFile, signature io.ReadSeeker, installa return nil, appErr } - manifest, appErr = a.installExtractedPlugin(manifest, pluginDir, installationStrategy) + manifest, appErr = s.installExtractedPlugin(manifest, pluginDir, installationStrategy) if appErr != nil { return nil, appErr } @@ -296,8 +320,8 @@ func extractPlugin(pluginFile io.ReadSeeker, extractDir string) (*model.Manifest return manifest, extractDir, nil } -func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir string, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) installExtractedPlugin(manifest *model.Manifest, fromPluginDir string, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil, model.NewAppError("installExtractedPlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -344,12 +368,12 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str // Otherwise remove the existing installation prior to install below. mlog.Debug("Removing existing installation of plugin before local install", mlog.String("plugin_id", existingManifest.Id), mlog.String("version", existingManifest.Version)) - if err := a.removePluginLocally(existingManifest.Id); err != nil { + if err := s.removePluginLocally(existingManifest.Id); err != nil { return nil, model.NewAppError("installExtractedPlugin", "app.plugin.install_id_failed_remove.app_error", nil, "", http.StatusBadRequest) } } - pluginPath := filepath.Join(*a.Config().PluginSettings.Directory, manifest.Id) + pluginPath := filepath.Join(*s.Config().PluginSettings.Directory, manifest.Id) err = utils.CopyDir(fromPluginDir, pluginPath) if err != nil { return nil, model.NewAppError("installExtractedPlugin", "app.plugin.mvdir.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -371,9 +395,9 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str } // Activate the plugin if enabled. - pluginState := a.Config().PluginSettings.PluginStates[manifest.Id] + pluginState := s.Config().PluginSettings.PluginStates[manifest.Id] if pluginState != nil && pluginState.Enable { - if manifest.Id == "com.mattermost.apps" && !a.Config().FeatureFlags.AppsEnabled { + if manifest.Id == "com.mattermost.apps" && !s.Config().FeatureFlags.AppsEnabled { return manifest, nil } updatedManifest, _, err := pluginsEnvironment.Activate(manifest.Id) @@ -389,44 +413,44 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str } func (a *App) RemovePlugin(id string) *model.AppError { - return a.removePlugin(id) + return a.Srv().removePlugin(id) } -func (a *App) removePlugin(id string) *model.AppError { +func (s *Server) removePlugin(id string) *model.AppError { // Disable plugin before removal to make sure this // plugin remains disabled on re-install. - if err := a.DisablePlugin(id); err != nil { + if err := s.disablePlugin(id); err != nil { return err } - if err := a.removePluginLocally(id); err != nil { + if err := s.removePluginLocally(id); err != nil { return err } // Remove bundle from the file store. - storePluginFileName := a.getBundleStorePath(id) - bundleExist, err := a.FileExists(storePluginFileName) + storePluginFileName := getBundleStorePath(id) + bundleExist, err := s.fileExists(storePluginFileName) if err != nil { return model.NewAppError("removePlugin", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError) } if !bundleExist { return nil } - if err = a.RemoveFile(storePluginFileName); err != nil { + if err = s.removeFile(storePluginFileName); err != nil { return model.NewAppError("removePlugin", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError) } - if err = a.removeSignature(id); err != nil { + if err = s.removeSignature(id); err != nil { mlog.Warn("Can't remove signature", mlog.Err(err)) } - a.notifyClusterPluginEvent( + s.notifyClusterPluginEvent( model.CLUSTER_EVENT_REMOVE_PLUGIN, model.PluginEventData{ Id: id, }, ) - if err := a.notifyPluginStatusesChanged(); err != nil { + if err := s.notifyPluginStatusesChanged(); err != nil { mlog.Warn("Failed to notify plugin status changed", mlog.Err(err)) } @@ -434,7 +458,11 @@ func (a *App) removePlugin(id string) *model.AppError { } func (a *App) removePluginLocally(id string) *model.AppError { - pluginsEnvironment := a.GetPluginsEnvironment() + return a.Srv().removePluginLocally(id) +} + +func (s *Server) removePluginLocally(id string) *model.AppError { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return model.NewAppError("removePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -460,7 +488,7 @@ func (a *App) removePluginLocally(id string) *model.AppError { pluginsEnvironment.Deactivate(id) pluginsEnvironment.RemovePlugin(id) - a.UnregisterPluginCommands(id) + s.unregisterPluginCommands(id) if err := os.RemoveAll(pluginPath); err != nil { return model.NewAppError("removePlugin", "app.plugin.remove.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -469,9 +497,9 @@ func (a *App) removePluginLocally(id string) *model.AppError { return nil } -func (a *App) removeSignature(pluginID string) *model.AppError { - filePath := a.getSignatureStorePath(pluginID) - exists, err := a.FileExists(filePath) +func (s *Server) removeSignature(pluginID string) *model.AppError { + filePath := getSignatureStorePath(pluginID) + exists, err := s.fileExists(filePath) if err != nil { return model.NewAppError("removeSignature", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -479,16 +507,16 @@ func (a *App) removeSignature(pluginID string) *model.AppError { mlog.Debug("no plugin signature to remove", mlog.String("plugin_id", pluginID)) return nil } - if err = a.RemoveFile(filePath); err != nil { + if err = s.removeFile(filePath); err != nil { return model.NewAppError("removeSignature", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) getBundleStorePath(id string) string { +func getBundleStorePath(id string) string { return filepath.Join(fileStorePluginFolder, fmt.Sprintf("%s.tar.gz", id)) } -func (a *App) getSignatureStorePath(id string) string { +func getSignatureStorePath(id string) string { return filepath.Join(fileStorePluginFolder, fmt.Sprintf("%s.tar.gz.sig", id)) } diff --git a/app/plugin_shutdown_test.go b/app/plugin_shutdown_test.go index 8db076d9324..09f158b3b76 100644 --- a/app/plugin_shutdown_test.go +++ b/app/plugin_shutdown_test.go @@ -57,7 +57,7 @@ func TestPluginShutdownTest(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) defer tearDown() done := make(chan bool) diff --git a/app/plugin_signature.go b/app/plugin_signature.go index c550973648a..3dcc4234e9c 100644 --- a/app/plugin_signature.go +++ b/app/plugin_signature.go @@ -21,12 +21,20 @@ import ( // GetPluginPublicKeyFiles returns all public keys listed in the config. func (a *App) GetPluginPublicKeyFiles() ([]string, *model.AppError) { - return a.Config().PluginSettings.SignaturePublicKeyFiles, nil + return a.Srv().getPluginPublicKeyFiles() +} + +func (s *Server) getPluginPublicKeyFiles() ([]string, *model.AppError) { + return s.Config().PluginSettings.SignaturePublicKeyFiles, nil } // 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) + return a.Srv().getPublicKey(name) +} + +func (s *Server) getPublicKey(name string) ([]byte, *model.AppError) { + data, err := s.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) } @@ -75,15 +83,19 @@ func (a *App) DeletePublicKey(name string) *model.AppError { // VerifyPlugin checks that the given signature corresponds to the given plugin and matches a trusted certificate. func (a *App) VerifyPlugin(plugin, signature io.ReadSeeker) *model.AppError { + return a.Srv().verifyPlugin(plugin, signature) +} + +func (s *Server) verifyPlugin(plugin, signature io.ReadSeeker) *model.AppError { if err := verifySignature(bytes.NewReader(mattermostPluginPublicKey), plugin, signature); err == nil { return nil } - publicKeys, appErr := a.GetPluginPublicKeyFiles() + publicKeys, appErr := s.getPluginPublicKeyFiles() if appErr != nil { return appErr } for _, pk := range publicKeys { - pkBytes, appErr := a.GetPublicKey(pk) + pkBytes, appErr := s.getPublicKey(pk) if appErr != nil { mlog.Warn("Unable to get public key for ", mlog.String("filename", pk)) continue diff --git a/app/plugin_statuses.go b/app/plugin_statuses.go index 79245cb7851..17e335266fc 100644 --- a/app/plugin_statuses.go +++ b/app/plugin_statuses.go @@ -71,13 +71,17 @@ func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { // GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster. func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) { - pluginStatuses, err := a.GetPluginStatuses() + return a.Srv().getClusterPluginStatuses() +} + +func (s *Server) getClusterPluginStatuses() (model.PluginStatuses, *model.AppError) { + pluginStatuses, err := s.GetPluginStatuses() if err != nil { return nil, err } - if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { - clusterPluginStatuses, err := a.Cluster().GetPluginStatuses() + if s.Cluster != nil && *s.Config().ClusterSettings.Enable { + clusterPluginStatuses, err := s.Cluster.GetPluginStatuses() if err != nil { return nil, model.NewAppError("GetClusterPluginStatuses", "app.plugin.get_cluster_plugin_statuses.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -88,8 +92,8 @@ func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) return pluginStatuses, nil } -func (a *App) notifyPluginStatusesChanged() error { - pluginStatuses, err := a.GetClusterPluginStatuses() +func (s *Server) notifyPluginStatusesChanged() error { + pluginStatuses, err := s.getClusterPluginStatuses() if err != nil { return err } @@ -98,7 +102,7 @@ func (a *App) notifyPluginStatusesChanged() error { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED, "", "", "", nil) message.Add("plugin_statuses", pluginStatuses) message.GetBroadcast().ContainsSensitiveData = true - a.Publish(message) + s.Publish(message) return nil } diff --git a/app/plugin_test.go b/app/plugin_test.go index ea5a8d411ba..15e6f7d5a9b 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -527,7 +527,7 @@ func TestPluginSync(t *testing.T) { require.NoError(t, err) defer fileReader.Close() - _, appErr := th.App.WriteFile(fileReader, th.App.getBundleStorePath("testplugin")) + _, appErr := th.App.WriteFile(fileReader, getBundleStorePath("testplugin")) checkNoError(t, appErr) appErr = th.App.SyncPlugins() @@ -545,7 +545,7 @@ func TestPluginSync(t *testing.T) { *cfg.PluginSettings.RequirePluginSignature = false }) - appErr := th.App.RemoveFile(th.App.getBundleStorePath("testplugin")) + appErr := th.App.RemoveFile(getBundleStorePath("testplugin")) checkNoError(t, appErr) appErr = th.App.SyncPlugins() @@ -565,7 +565,7 @@ func TestPluginSync(t *testing.T) { pluginFileReader, err := os.Open(filepath.Join(path, "testplugin.tar.gz")) require.NoError(t, err) defer pluginFileReader.Close() - _, appErr := th.App.WriteFile(pluginFileReader, th.App.getBundleStorePath("testplugin")) + _, appErr := th.App.WriteFile(pluginFileReader, getBundleStorePath("testplugin")) checkNoError(t, appErr) appErr = th.App.SyncPlugins() @@ -583,7 +583,7 @@ func TestPluginSync(t *testing.T) { signatureFileReader, err := os.Open(filepath.Join(path, "testplugin2.tar.gz.sig")) require.NoError(t, err) defer signatureFileReader.Close() - _, appErr := th.App.WriteFile(signatureFileReader, th.App.getSignatureStorePath("testplugin")) + _, appErr := th.App.WriteFile(signatureFileReader, getSignatureStorePath("testplugin")) checkNoError(t, appErr) appErr = th.App.SyncPlugins() @@ -607,7 +607,7 @@ func TestPluginSync(t *testing.T) { signatureFileReader, err := os.Open(filepath.Join(path, "testplugin.tar.gz.sig")) require.NoError(t, err) defer signatureFileReader.Close() - _, appErr = th.App.WriteFile(signatureFileReader, th.App.getSignatureStorePath("testplugin")) + _, appErr = th.App.WriteFile(signatureFileReader, getSignatureStorePath("testplugin")) checkNoError(t, appErr) appErr = th.App.SyncPlugins() @@ -648,7 +648,7 @@ func TestSyncPluginsActiveState(t *testing.T) { require.NoError(t, err) defer fileReader.Close() - _, appErr := th.App.WriteFile(fileReader, th.App.getBundleStorePath("testplugin")) + _, appErr := th.App.WriteFile(fileReader, getBundleStorePath("testplugin")) checkNoError(t, appErr) // Sync with file store so the plugin environment has access to this plugin. @@ -691,6 +691,7 @@ func TestPluginPanicLogs(t *testing.T) { t.Run("should panic", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() + tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{ ` package main @@ -713,7 +714,7 @@ func TestPluginPanicLogs(t *testing.T) { plugin.ClientMain(&MyPlugin{}) } `, - }, th.App, th.App.NewPluginAPI) + }, th.App, th.NewPluginAPI) post := &model.Post{ UserId: th.BasicUser.Id, @@ -721,7 +722,7 @@ func TestPluginPanicLogs(t *testing.T) { Message: "message_", CreateAt: model.GetMillis() - 10000, } - _, err := th.App.CreatePost(post, th.BasicChannel, false, true) + _, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) assert.Nil(t, err) // We shutdown plugins first so that the read on the log buffer is race-free. th.App.Srv().ShutDownPlugins() @@ -771,7 +772,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { *cfg.PluginSettings.EnableRemoteMarketplace = false }) - plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir) + plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir) require.Len(t, plugins, 1) require.Equal(t, plugins[0].Manifest.Id, "testplugin") require.Empty(t, plugins[0].Signature, 0) @@ -798,7 +799,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { env := th.App.GetPluginsEnvironment() - plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir) + plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir) require.Len(t, plugins, 1) require.Equal(t, plugins[0].Manifest.Id, "testplugin") require.Empty(t, plugins[0].Signature, 0) @@ -831,7 +832,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig")) require.NoError(t, err) - plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir) + plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir) require.Len(t, plugins, 2) require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id) require.NotEmpty(t, plugins[0].Signature) @@ -880,7 +881,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig")) require.NoError(t, err) - plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir) + plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir) require.Len(t, plugins, 2) require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id) require.NotEmpty(t, plugins[0].Signature) @@ -917,7 +918,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig")) require.NoError(t, err) - plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir) + plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir) require.Len(t, plugins, 2) require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id) require.NotEmpty(t, plugins[0].Signature) diff --git a/app/post.go b/app/post.go index 600319ea539..3c6eef5e690 100644 --- a/app/post.go +++ b/app/post.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/services/cache" @@ -28,7 +29,7 @@ const ( PageDefault = 0 ) -func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { +func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { // Check that channel has not been deleted channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) if errCh != nil { @@ -46,7 +47,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl return nil, err } - rp, err := a.CreatePost(post, channel, true, setOnline) + rp, err := a.CreatePost(c, post, channel, true, setOnline) if err != nil { if err.Id == "api.post.create_post.root_id.app_error" || err.Id == "api.post.create_post.channel_root_id.app_error" || @@ -100,7 +101,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl return rp, nil } -func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *App) CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { channel, err := a.Srv().Store.Channel().Get(post.ChannelId, true) if err != nil { var nfErr *store.ErrNotFound @@ -112,7 +113,7 @@ func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) ( } } - return a.CreatePost(post, channel, triggerWebhooks, true) + return a.CreatePost(c, post, channel, triggerWebhooks, true) } // deduplicateCreatePost attempts to make posting idempotent within a caching window. @@ -157,7 +158,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er return actualPost, nil } -func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) { +func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) { foundPost, err := a.deduplicateCreatePost(post) if err != nil { return nil, err @@ -281,7 +282,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { var rejectionError *model.AppError - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { replacementPost, rejectionReason := hooks.MessageWillBePosted(pluginContext, post) if rejectionReason != "" { @@ -326,7 +327,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo rPostCopy := rpost.Clone() if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.MessageHasBeenPosted(pluginContext, rPostCopy) return true @@ -352,7 +353,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo // to be done when we send the post over the websocket in handlePostEvents rpost = a.PreparePostForClient(rpost, true, false) - if err := a.handlePostEvents(rpost, user, channel, triggerWebhooks, parentPostList, setOnline); err != nil { + if err := a.handlePostEvents(c, rpost, user, channel, triggerWebhooks, parentPostList, setOnline); err != nil { mlog.Warn("Failed to handle post events", mlog.Err(err)) } @@ -439,7 +440,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A return nil } -func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { +func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { var team *model.Team if channel.TeamId != "" { t, err := a.Srv().Store.Team().Get(channel.TeamId) @@ -461,7 +462,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode if post.Type != model.POST_AUTO_RESPONDER { // don't respond to an auto-responder a.Srv().Go(func() { - _, err := a.SendAutoResponseIfNecessary(channel, user, post) + _, err := a.SendAutoResponseIfNecessary(c, channel, user, post) 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)) } @@ -470,7 +471,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode if triggerWebhooks { a.Srv().Go(func() { - if err := a.handleWebhookEvents(post, team, channel, user); err != nil { + if err := a.handleWebhookEvents(c, post, team, channel, user); err != nil { mlog.Error(err.Error()) } }) @@ -535,7 +536,7 @@ func (a *App) DeleteEphemeralPost(userID, postID string) { a.Publish(message) } -func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { +func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { post.SanitizeProps() postLists, nErr := a.Srv().Store.Post().Get(context.Background(), post.Id, false, false, false, "") @@ -615,7 +616,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { var rejectionReason string - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { newPost, rejectionReason = hooks.MessageWillBeUpdated(pluginContext, newPost, oldPost) return post != nil @@ -638,7 +639,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.MessageHasBeenUpdated(pluginContext, newPost, oldPost) return true @@ -657,7 +658,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model return rpost, nil } -func (a *App) PatchPost(postID string, patch *model.PostPatch) (*model.Post, *model.AppError) { +func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) { post, err := a.GetSinglePost(postID) if err != nil { return nil, err @@ -679,7 +680,7 @@ func (a *App) PatchPost(postID string, patch *model.PostPatch) (*model.Post, *mo post.Patch(patch) - updatedPost, err := a.UpdatePost(post, false) + updatedPost, err := a.UpdatePost(c, post, false) if err != nil { return nil, err } @@ -790,7 +791,7 @@ func (a *App) GetFlaggedPostsForChannel(userID, channelID string, offset int, li return postList, nil } -func (a *App) GetPermalinkPost(postID string, userID string) (*model.PostList, *model.AppError) { +func (a *App) GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) { list, nErr := a.Srv().Store.Post().Get(context.Background(), postID, false, false, false, userID) if nErr != nil { var nfErr *store.ErrNotFound @@ -815,7 +816,7 @@ func (a *App) GetPermalinkPost(postID string, userID string) (*model.PostList, * return nil, err } - if err = a.JoinChannel(channel, userID); err != nil { + if err = a.JoinChannel(c, channel, userID); err != nil { return nil, err } @@ -1082,7 +1083,7 @@ func (a *App) DeletePostFiles(post *model.Post) { } } -func (a *App) parseAndFetchChannelIdByNameFromInFilter(channelName, userID, teamID string, includeDeleted bool) (*model.Channel, error) { +func (a *App) parseAndFetchChannelIdByNameFromInFilter(c *request.Context, channelName, userID, teamID string, includeDeleted bool) (*model.Channel, error) { if strings.HasPrefix(channelName, "@") && strings.Contains(channelName, ",") { var userIDs []string users, err := a.GetUsersByUsernames(strings.Split(channelName[1:], ","), false, nil) @@ -1105,7 +1106,7 @@ func (a *App) parseAndFetchChannelIdByNameFromInFilter(channelName, userID, team if err != nil { return nil, err } - channel, err := a.GetOrCreateDirectChannel(userID, user.Id) + channel, err := a.GetOrCreateDirectChannel(c, userID, user.Id) if err != nil { return nil, err } @@ -1156,9 +1157,9 @@ func (a *App) searchPostsInTeam(teamID string, userID string, paramsList []*mode return posts, nil } -func (a *App) convertChannelNamesToChannelIds(channels []string, userID string, teamID string, includeDeletedChannels bool) []string { +func (a *App) convertChannelNamesToChannelIds(c *request.Context, channels []string, userID string, teamID string, includeDeletedChannels bool) []string { for idx, channelName := range channels { - channel, err := a.parseAndFetchChannelIdByNameFromInFilter(channelName, userID, teamID, includeDeletedChannels) + channel, err := a.parseAndFetchChannelIdByNameFromInFilter(c, channelName, userID, teamID, includeDeletedChannels) if err != nil { mlog.Warn("error getting channel id by name from in filter", mlog.Err(err)) continue @@ -1189,7 +1190,7 @@ func (a *App) SearchPostsInTeam(teamID string, paramsList []*model.SearchParams) }) } -func (a *App) SearchPostsInTeamForUser(terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) { +func (a *App) SearchPostsInTeamForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) { var postSearchResults *model.PostSearchResults paramsList := model.ParseSearchParams(strings.TrimSpace(terms), timeZoneOffset) includeDeleted := includeDeletedChannels && *a.Config().TeamSettings.ExperimentalViewArchivedChannels @@ -1206,8 +1207,8 @@ func (a *App) SearchPostsInTeamForUser(terms string, userID string, teamID strin // Don't allow users to search for "*" if params.Terms != "*" { // Convert channel names to channel IDs - params.InChannels = a.convertChannelNamesToChannelIds(params.InChannels, userID, teamID, includeDeletedChannels) - params.ExcludedChannels = a.convertChannelNamesToChannelIds(params.ExcludedChannels, userID, teamID, includeDeletedChannels) + params.InChannels = a.convertChannelNamesToChannelIds(c, params.InChannels, userID, teamID, includeDeletedChannels) + params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userID, teamID, includeDeletedChannels) // Convert usernames to user IDs params.FromUsers = a.convertUserNameToUserIds(params.FromUsers) diff --git a/app/post_metadata.go b/app/post_metadata.go index aabec5504b1..ad3107da6e1 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -36,9 +36,9 @@ var linkCache = cache.NewLRU(cache.LRUOptions{ Size: LinkCacheSize, }) -func (a *App) InitPostMetadata() { +func (s *Server) initPostMetadata() { // Dump any cached links if the proxy settings have changed so image URLs can be updated - a.AddConfigListener(func(before, after *model.Config) { + s.AddConfigListener(func(before, after *model.Config) { if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) || (before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) || (before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) || diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index af16d3727dd..0b71b1c090d 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -176,11 +176,11 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - fileInfo, err := th.App.DoUploadFile(time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test")) + fileInfo, err := th.App.DoUploadFile(th.Context, time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test")) fileInfo.Content = "test" require.Nil(t, err) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, FileIds: []string{fileInfo.Id}, @@ -204,7 +204,7 @@ func TestPreparePostForClient(t *testing.T) { emoji := th.CreateEmoji() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: ":" + emoji.Name + ": :taco:", @@ -248,7 +248,7 @@ func TestPreparePostForClient(t *testing.T) { emoji3 := th.CreateEmoji() emoji4 := th.CreateEmoji() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: ":" + emoji3.Name + ": :taco:", @@ -289,7 +289,7 @@ func TestPreparePostForClient(t *testing.T) { *cfg.ServiceSettings.EnablePostIconOverride = override }) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "Test", @@ -347,7 +347,7 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: fmt.Sprintf("This is ![our logo](%s/test-image2.png) and ![our icon](%s/test-image1.png)", server.URL, server.URL), @@ -376,7 +376,7 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "some post", @@ -409,7 +409,7 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: `This is our logo: ` + server.URL + `/test-image2.png @@ -445,7 +445,7 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: `This is our web page: ` + server.URL, @@ -482,7 +482,7 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Props: map[string]interface{}{ @@ -520,10 +520,10 @@ func TestPreparePostForClient(t *testing.T) { th := setup(t) defer th.TearDown() - fileInfo, err := th.App.DoUploadFile(time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test")) + fileInfo, err := th.App.DoUploadFile(th.Context, time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test")) require.Nil(t, err) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ Message: "test", FileIds: []string{fileInfo.Id}, UserId: th.BasicUser.Id, @@ -633,7 +633,7 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) { serverURL = server.URL defer server.Close() - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: `This is our web page: ` + server.URL, diff --git a/app/post_test.go b/app/post_test.go index ae08441f92e..f7b9bed5d3e 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -31,7 +31,7 @@ func TestCreatePostDeduplicate(t *testing.T) { t.Run("duplicate create post is idempotent", func(t *testing.T) { pendingPostId := model.NewId() - post, err := th.App.CreatePostAsUser(&model.Post{ + post, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -40,7 +40,7 @@ func TestCreatePostDeduplicate(t *testing.T) { require.Nil(t, err) require.Equal(t, "message", post.Message) - duplicatePost, err := th.App.CreatePostAsUser(&model.Post{ + duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -77,10 +77,10 @@ func TestCreatePostDeduplicate(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `, `{"id": "testrejectfirstpost", "backend": {"executable": "backend.exe"}}`, "testrejectfirstpost", th.App) + `, `{"id": "testrejectfirstpost", "backend": {"executable": "backend.exe"}}`, "testrejectfirstpost", th.App, th.Context) pendingPostId := model.NewId() - post, err := th.App.CreatePostAsUser(&model.Post{ + post, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -90,7 +90,7 @@ func TestCreatePostDeduplicate(t *testing.T) { require.Equal(t, "Post rejected by plugin. rejected", err.Id) require.Nil(t, post) - duplicatePost, err := th.App.CreatePostAsUser(&model.Post{ + duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -127,7 +127,7 @@ func TestCreatePostDeduplicate(t *testing.T) { func main() { plugin.ClientMain(&MyPlugin{}) } - `, `{"id": "testdelayfirstpost", "backend": {"executable": "backend.exe"}}`, "testdelayfirstpost", th.App) + `, `{"id": "testdelayfirstpost", "backend": {"executable": "backend.exe"}}`, "testdelayfirstpost", th.App, th.Context) var post *model.Post pendingPostId := model.NewId() @@ -140,7 +140,7 @@ func TestCreatePostDeduplicate(t *testing.T) { go func() { defer wg.Done() var appErr *model.AppError - post, appErr = th.App.CreatePostAsUser(&model.Post{ + post, appErr = th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "plugin delayed", @@ -154,7 +154,7 @@ func TestCreatePostDeduplicate(t *testing.T) { time.Sleep(2 * time.Second) // Try creating a duplicate post - duplicatePost, err := th.App.CreatePostAsUser(&model.Post{ + duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "plugin delayed", @@ -170,7 +170,7 @@ func TestCreatePostDeduplicate(t *testing.T) { t.Run("duplicate create post after cache expires is not idempotent", func(t *testing.T) { pendingPostId := model.NewId() - post, err := th.App.CreatePostAsUser(&model.Post{ + post, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -181,7 +181,7 @@ func TestCreatePostDeduplicate(t *testing.T) { time.Sleep(PendingPostIDsCacheTTL) - duplicatePost, err := th.App.CreatePostAsUser(&model.Post{ + duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "message", @@ -263,7 +263,7 @@ func TestUpdatePostEditAt(t *testing.T) { post := th.BasicPost.Clone() post.IsPinned = true - saved, err := th.App.UpdatePost(post, true) + saved, err := th.App.UpdatePost(th.Context, post, true) require.Nil(t, err) assert.Equal(t, saved.EditAt, post.EditAt, "shouldn't have updated post.EditAt when pinning post") post = saved.Clone() @@ -271,7 +271,7 @@ func TestUpdatePostEditAt(t *testing.T) { time.Sleep(time.Millisecond * 100) post.Message = model.NewId() - saved, err = th.App.UpdatePost(post, true) + saved, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err) assert.NotEqual(t, saved.EditAt, post.EditAt, "should have updated post.EditAt when updating post message") @@ -289,7 +289,7 @@ func TestUpdatePostTimeLimit(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.PostEditTimeLimit = -1 }) - _, err := th.App.UpdatePost(post, true) + _, err := th.App.UpdatePost(th.Context, post, true) require.Nil(t, err) th.App.UpdateConfig(func(cfg *model.Config) { @@ -297,14 +297,14 @@ func TestUpdatePostTimeLimit(t *testing.T) { }) post.Message = model.NewId() - _, err = th.App.UpdatePost(post, true) + _, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err, "should allow you to edit the post") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.PostEditTimeLimit = 1 }) post.Message = model.NewId() - _, err = th.App.UpdatePost(post, true) + _, err = th.App.UpdatePost(th.Context, post, true) require.NotNil(t, err, "should fail on update old post") th.App.UpdateConfig(func(cfg *model.Config) { @@ -318,9 +318,9 @@ func TestUpdatePostInArchivedChannel(t *testing.T) { archivedChannel := th.CreateChannel(th.BasicTeam) post := th.CreatePost(archivedChannel) - th.App.DeleteChannel(archivedChannel, "") + th.App.DeleteChannel(th.Context, archivedChannel, "") - _, err := th.App.UpdatePost(post, true) + _, err := th.App.UpdatePost(th.Context, post, true) require.NotNil(t, err) require.Equal(t, "api.post.update_post.can_not_update_post_in_deleted.error", err.Id) } @@ -339,7 +339,7 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { _, err := th.App.AddUserToChannel(userInChannel, channel, false) require.Nil(t, err) - err = th.App.RemoveUserFromChannel(userNotInChannel.Id, "", channel) + err = th.App.RemoveUserFromChannel(th.Context, userNotInChannel.Id, "", channel) require.Nil(t, err) replyPost := model.Post{ Message: "asd", @@ -351,7 +351,7 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { CreateAt: 0, } - _, err = th.App.CreatePostAsUser(&replyPost, "", true) + _, err = th.App.CreatePostAsUser(th.Context, &replyPost, "", true) require.Nil(t, err) } @@ -373,7 +373,7 @@ func TestPostAttachPostToChildPost(t *testing.T) { CreateAt: 0, } - res1, err := th.App.CreatePostAsUser(&replyPost1, "", true) + res1, err := th.App.CreatePostAsUser(th.Context, &replyPost1, "", true) require.Nil(t, err) replyPost2 := model.Post{ @@ -386,7 +386,7 @@ func TestPostAttachPostToChildPost(t *testing.T) { CreateAt: 0, } - _, err = th.App.CreatePostAsUser(&replyPost2, "", true) + _, err = th.App.CreatePostAsUser(th.Context, &replyPost2, "", true) assert.Equalf(t, err.StatusCode, http.StatusBadRequest, "Expected BadRequest error, got %v", err) replyPost3 := model.Post{ @@ -399,7 +399,7 @@ func TestPostAttachPostToChildPost(t *testing.T) { CreateAt: 0, } - _, err = th.App.CreatePostAsUser(&replyPost3, "", true) + _, err = th.App.CreatePostAsUser(th.Context, &replyPost3, "", true) assert.Nil(t, err) } @@ -410,7 +410,7 @@ func TestPostChannelMentions(t *testing.T) { channel := th.BasicChannel user := th.BasicUser - channelToMention, err := th.App.CreateChannel(&model.Channel{ + channelToMention, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "Mention Test", Name: "mention-test", Type: model.CHANNEL_OPEN, @@ -430,7 +430,7 @@ func TestPostChannelMentions(t *testing.T) { CreateAt: 0, } - result, err := th.App.CreatePostAsUser(post, "", true) + result, err := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, err) assert.Equal(t, map[string]interface{}{ "mention-test": map[string]interface{}{ @@ -440,7 +440,7 @@ func TestPostChannelMentions(t *testing.T) { }, result.GetProp("channel_mentions")) post.Message = fmt.Sprintf("goodbye, ~%v!", channelToMention.Name) - result, err = th.App.UpdatePost(post, false) + result, err = th.App.UpdatePost(th.Context, post, false) require.Nil(t, err) assert.Equal(t, map[string]interface{}{ "mention-test": map[string]interface{}{ @@ -630,7 +630,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) + info1, err := th.App.DoUploadFile(th.Context, 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) @@ -646,7 +646,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) { FileIds: []string{info1.Id}, } - post, err = th.App.CreatePost(post, th.BasicChannel, false, true) + post, err = th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) assert.Nil(t, err) // Delete the post. @@ -667,7 +667,7 @@ func TestDeletePostInArchivedChannel(t *testing.T) { archivedChannel := th.CreateChannel(th.BasicTeam) post := th.CreatePost(archivedChannel) - th.App.DeleteChannel(archivedChannel, "") + th.App.DeleteChannel(th.Context, archivedChannel, "") _, err := th.App.DeletePost(post.Id, "") require.NotNil(t, err) @@ -698,7 +698,7 @@ func TestCreatePost(t *testing.T) { UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, "![image]("+proxiedImageURL+")", rpost.Message) }) @@ -714,7 +714,7 @@ func TestCreatePost(t *testing.T) { Message: "This post does not have mentions", UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(postWithNoMention, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, postWithNoMention, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) @@ -723,7 +723,7 @@ func TestCreatePost(t *testing.T) { Message: "This post has @here mention @all", UserId: th.BasicUser.Id, } - rpost, err = th.App.CreatePost(postWithMention, th.BasicChannel, false, true) + rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) }) @@ -737,7 +737,7 @@ func TestCreatePost(t *testing.T) { Message: "This post does not have mentions", UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(postWithNoMention, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, postWithNoMention, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) @@ -746,7 +746,7 @@ func TestCreatePost(t *testing.T) { Message: "This post has @here mention @all", UserId: th.BasicUser.Id, } - rpost, err = th.App.CreatePost(postWithMention, th.BasicChannel, false, true) + rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true) require.Nil(t, err) assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true) @@ -780,7 +780,7 @@ func TestPatchPost(t *testing.T) { UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.NotEqual(t, "![image]("+proxiedImageURL+")", rpost.Message) @@ -788,7 +788,7 @@ func TestPatchPost(t *testing.T) { Message: model.NewString("![image](" + imageURL + ")"), } - rpost, err = th.App.PatchPost(rpost.Id, patch) + rpost, err = th.App.PatchPost(th.Context, rpost.Id, patch) require.Nil(t, err) assert.Equal(t, "![image]("+proxiedImageURL+")", rpost.Message) }) @@ -805,19 +805,19 @@ func TestPatchPost(t *testing.T) { UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) t.Run("Does not set prop when user has USE_CHANNEL_MENTIONS", func(t *testing.T) { patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch has no channel mention")} - rpost, err = th.App.PatchPost(rpost.Id, patchWithNoMention) + rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) patchWithMention := &model.PostPatch{Message: model.NewString("This patch has a mention now @here")} - rpost, err = th.App.PatchPost(rpost.Id, patchWithMention) + rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) }) @@ -827,13 +827,13 @@ func TestPatchPost(t *testing.T) { th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID) patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch still does not have a mention")} - rpost, err = th.App.PatchPost(rpost.Id, patchWithNoMention) + rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention) require.Nil(t, err) assert.Equal(t, rpost.GetProps(), model.StringInterface{}) patchWithMention := &model.PostPatch{Message: model.NewString("This patch has a mention now @here")} - rpost, err = th.App.PatchPost(rpost.Id, patchWithMention) + rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention) require.Nil(t, err) assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true) @@ -858,7 +858,7 @@ func TestCreatePostAsUser(t *testing.T) { require.NoError(t, err) time.Sleep(1 * time.Millisecond) - _, appErr := th.App.CreatePostAsUser(post, "", true) + _, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) @@ -882,7 +882,7 @@ func TestCreatePostAsUser(t *testing.T) { require.NoError(t, err) time.Sleep(1 * time.Millisecond) - _, appErr := th.App.CreatePostAsUser(post, "", true) + _, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) @@ -913,7 +913,7 @@ func TestCreatePostAsUser(t *testing.T) { require.NoError(t, nErr) time.Sleep(1 * time.Millisecond) - _, appErr = th.App.CreatePostAsUser(post, "", true) + _, appErr = th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) channelMemberAfter, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) @@ -935,7 +935,7 @@ func TestCreatePostAsUser(t *testing.T) { UserId: user.Id, } - _, appErr := th.App.CreatePostAsUser(post, "", true) + _, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) testlib.AssertLog(t, th.LogBuffer, mlog.LevelWarn, "Failed to get membership") @@ -958,7 +958,7 @@ func TestCreatePostAsUser(t *testing.T) { UserId: bot.UserId, } - _, appErr = th.App.CreatePostAsUser(post, "", true) + _, appErr = th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) testlib.AssertNoLog(t, th.LogBuffer, mlog.LevelWarn, "Failed to get membership") @@ -971,9 +971,9 @@ func TestPatchPostInArchivedChannel(t *testing.T) { archivedChannel := th.CreateChannel(th.BasicTeam) post := th.CreatePost(archivedChannel) - th.App.DeleteChannel(archivedChannel, "") + th.App.DeleteChannel(th.Context, archivedChannel, "") - _, err := th.App.PatchPost(post.Id, &model.PostPatch{IsPinned: model.NewBool(true)}) + _, err := th.App.PatchPost(th.Context, post.Id, &model.PostPatch{IsPinned: model.NewBool(true)}) require.NotNil(t, err) require.Equal(t, "api.post.patch_post.can_not_update_post_in_deleted.error", err.Id) } @@ -1002,14 +1002,14 @@ func TestUpdatePost(t *testing.T) { UserId: th.BasicUser.Id, } - rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true) + rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true) require.Nil(t, err) assert.NotEqual(t, "![image]("+proxiedImageURL+")", rpost.Message) post.Id = rpost.Id post.Message = "![image](" + imageURL + ")" - rpost, err = th.App.UpdatePost(post, false) + rpost, err = th.App.UpdatePost(th.Context, post, false) require.Nil(t, err) assert.Equal(t, "![image]("+proxiedImageURL+")", rpost.Message) }) @@ -1024,7 +1024,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { posts := make([]*model.Post, 7) for i := 0; i < cap(posts); i++ { - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: searchTerm, @@ -1057,7 +1057,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { page := 0 - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, []string{ @@ -1077,7 +1077,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { page := 1 - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, []string{}, results.Order) @@ -1107,7 +1107,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, resultsPage, results.Order) @@ -1135,7 +1135,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, resultsPage, results.Order) @@ -1159,7 +1159,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, []string{ @@ -1191,7 +1191,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { th.App.Srv().SearchEngine.ElasticsearchEngine = nil }() - results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) + results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage) assert.Nil(t, err) assert.Equal(t, []string{}, results.Order) @@ -1210,19 +1210,19 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test3", @@ -1247,19 +1247,19 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP] = "apple" - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "apple", @@ -1286,19 +1286,19 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true" - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@channel", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@all", @@ -1325,19 +1325,19 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "false" - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@channel", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@all", @@ -1367,19 +1367,19 @@ func TestCountMentionsFromPost(t *testing.T) { }, channel.Id, user2.Id) require.Nil(t, err) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@channel", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "@all", @@ -1404,33 +1404,33 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: post1.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - post3, err := th.App.CreatePost(&model.Post{ + post3, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test3", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, RootId: post3.Id, Message: "test4", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: post3.Id, @@ -1458,33 +1458,33 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: post1.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - post3, err := th.App.CreatePost(&model.Post{ + post3, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test3", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, RootId: post3.Id, Message: "test4", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: post3.Id, @@ -1510,7 +1510,7 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", @@ -1520,7 +1520,7 @@ func TestCountMentionsFromPost(t *testing.T) { }, }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test2", @@ -1530,7 +1530,7 @@ func TestCountMentionsFromPost(t *testing.T) { }, }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test3", @@ -1559,14 +1559,14 @@ func TestCountMentionsFromPost(t *testing.T) { channel, err := th.App.createDirectChannel(user1.Id, user2.Id) require.Nil(t, err) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test2", @@ -1594,19 +1594,19 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - _, err := th.App.CreatePost(&model.Post{ + _, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), }, channel, false, true) require.Nil(t, err) - post2, err := th.App.CreatePost(&model.Post{ + post2, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), @@ -1631,13 +1631,13 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), @@ -1664,26 +1664,26 @@ func TestCountMentionsFromPost(t *testing.T) { user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test1", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, RootId: post1.Id, Message: "test2", }, channel, false, true) require.Nil(t, err) - post3, err := th.App.CreatePost(&model.Post{ + post3, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test3", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: post1.Id, @@ -1709,19 +1709,19 @@ func TestCountMentionsFromPost(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test1", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), @@ -1751,7 +1751,7 @@ func TestCountMentionsFromPost(t *testing.T) { numPosts := 215 - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), @@ -1759,7 +1759,7 @@ func TestCountMentionsFromPost(t *testing.T) { require.Nil(t, err) for i := 0; i < numPosts-1; i++ { - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: fmt.Sprintf("@%s", user2.Username), @@ -1786,7 +1786,7 @@ func TestFillInPostProps(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "test123123 @group1 @group2 blah blah blah", @@ -1811,14 +1811,14 @@ func TestFillInPostProps(t *testing.T) { Password: "Password1", EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) th.LinkUserToTeam(guest, th.BasicTeam) channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(guest, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: guest.Id, ChannelId: channel.Id, Message: "test123123 @group1 @group2 blah blah blah", @@ -1844,14 +1844,14 @@ func TestFillInPostProps(t *testing.T) { Password: "Password1", EmailVerified: true, } - guest, err := th.App.CreateGuest(guest) + guest, err := th.App.CreateGuest(th.Context, guest) require.Nil(t, err) th.LinkUserToTeam(guest, th.BasicTeam) channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(guest, channel) - post1, err := th.App.CreatePost(&model.Post{ + post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: guest.Id, ChannelId: channel.Id, Message: "test123123 @group1 @group2 blah blah blah", @@ -1876,14 +1876,14 @@ func TestThreadMembership(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - postRoot, err := th.App.CreatePost(&model.Post{ + postRoot, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "root post", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: postRoot.Id, @@ -1900,14 +1900,14 @@ func TestThreadMembership(t *testing.T) { require.NoError(t, err2) require.Len(t, memberships, 1) - post2, err := th.App.CreatePost(&model.Post{ + post2, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, Message: "second post", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user2.Id, ChannelId: channel.Id, RootId: post2.Id, @@ -1938,25 +1938,25 @@ func TestFollowThreadSkipsParticipants(t *testing.T) { user2 := th.BasicUser2 sysadmin := th.SystemAdminUser - appErr := th.App.JoinChannel(channel, user.Id) + appErr := th.App.JoinChannel(th.Context, channel, user.Id) require.Nil(t, appErr) - appErr = th.App.JoinChannel(channel, user2.Id) + appErr = th.App.JoinChannel(th.Context, channel, user2.Id) require.Nil(t, appErr) - _, appErr = th.App.JoinUserToTeam(th.BasicTeam, sysadmin, sysadmin.Id) + _, appErr = th.App.JoinUserToTeam(th.Context, th.BasicTeam, sysadmin, sysadmin.Id) require.Nil(t, appErr) - appErr = th.App.JoinChannel(channel, sysadmin.Id) + appErr = th.App.JoinChannel(th.Context, channel, sysadmin.Id) require.Nil(t, appErr) - p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + sysadmin.Username}, channel, false, false) + p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + sysadmin.Username}, channel, false, false) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) + _, err = th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) require.Nil(t, err) thread, err := th.App.GetThreadForUser(user.Id, th.BasicTeam.Id, p1.Id, false) require.Nil(t, err) require.Len(t, thread.Participants, 1) // length should be 1, the original poster, since sysadmin was just mentioned but didn't post - _, err = th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: sysadmin.Id, ChannelId: channel.Id, Message: "sysadmin reply"}, channel, false, false) + _, err = th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: sysadmin.Id, ChannelId: channel.Id, Message: "sysadmin reply"}, channel, false, false) require.Nil(t, err) thread, err = th.App.GetThreadForUser(user.Id, th.BasicTeam.Id, p1.Id, false) @@ -1988,16 +1988,16 @@ func TestAutofollowBasedOnRootPost(t *testing.T) { channel := th.BasicChannel user := th.BasicUser user2 := th.BasicUser2 - appErr := th.App.JoinChannel(channel, user.Id) + appErr := th.App.JoinChannel(th.Context, channel, user.Id) require.Nil(t, appErr) - appErr = th.App.JoinChannel(channel, user2.Id) + appErr = th.App.JoinChannel(th.Context, channel, user2.Id) require.Nil(t, appErr) - p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false) + p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false) require.Nil(t, err) m, e := th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id) require.NoError(t, e) require.Len(t, m, 0) - _, err2 := th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) + _, err2 := th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) require.Nil(t, err2) m, e = th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id) require.NoError(t, e) @@ -2018,13 +2018,13 @@ func TestViewChannelShouldNotUpdateThreads(t *testing.T) { channel := th.BasicChannel user := th.BasicUser user2 := th.BasicUser2 - appErr := th.App.JoinChannel(channel, user.Id) + appErr := th.App.JoinChannel(th.Context, channel, user.Id) require.Nil(t, appErr) - appErr = th.App.JoinChannel(channel, user2.Id) + appErr = th.App.JoinChannel(th.Context, channel, user2.Id) require.Nil(t, appErr) - p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false) + p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false) require.Nil(t, err) - _, err2 := th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) + _, err2 := th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false) require.Nil(t, err2) m, e := th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id) require.NoError(t, e) @@ -2053,16 +2053,16 @@ func TestCollapsedThreadFetch(t *testing.T) { t.Run("should only return root posts, enriched", func(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - defer th.App.DeleteChannel(channel, user1.Id) + defer th.App.DeleteChannel(th.Context, channel, user1.Id) - postRoot, err := th.App.CreatePost(&model.Post{ + postRoot, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "root post", }, channel, false, true) require.Nil(t, err) - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: postRoot.Id, @@ -2098,9 +2098,9 @@ func TestCollapsedThreadFetch(t *testing.T) { channel := th.CreateChannel(th.BasicTeam) th.AddUserToChannel(user2, channel) - defer th.App.DeleteChannel(channel, user1.Id) + defer th.App.DeleteChannel(th.Context, channel, user1.Id) - postRoot, err := th.App.CreatePost(&model.Post{ + postRoot, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, Message: "root post", @@ -2116,7 +2116,7 @@ func TestCollapsedThreadFetch(t *testing.T) { }() require.NotPanics(t, func() { - _, err = th.App.CreatePost(&model.Post{ + _, err = th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, ChannelId: channel.Id, RootId: postRoot.Id, @@ -2150,14 +2150,14 @@ func TestReplyToPostWithLag(t *testing.T) { mainHelper.ToggleReplicasOn() defer mainHelper.ToggleReplicasOff() - root, appErr := th.App.CreatePost(&model.Post{ + root, appErr := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "root post", }, th.BasicChannel, false, true) require.Nil(t, appErr) - reply, appErr := th.App.CreatePost(&model.Post{ + reply, appErr := th.App.CreatePost(th.Context, &model.Post{ UserId: th.BasicUser2.Id, ChannelId: th.BasicChannel.Id, RootId: root.Id, @@ -2183,7 +2183,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - _, err := th.App.CreatePost(&model.Post{ + _, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, ChannelId: channel.Id, Message: "Hello folks", @@ -2207,14 +2207,14 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, ChannelId: channel.Id, Message: "Hello folks", }, channel, false, true) require.Nil(t, err, "Creating a post should not error") - _, err = th.App.UpdatePost(post, true) + _, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err, "Updating a post should not error") assert.Len(t, remoteClusterService.notifications, 2) @@ -2235,7 +2235,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, ChannelId: channel.Id, Message: "Hello folks", diff --git a/app/product_notices.go b/app/product_notices.go index ed81e9a34e8..91c0e6139b6 100644 --- a/app/product_notices.go +++ b/app/product_notices.go @@ -15,6 +15,7 @@ import ( "github.com/pkg/errors" date_constraints "github.com/reflog/dateconstraints" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -237,9 +238,9 @@ func validateConfigEntry(conf *model.Config, path string, expectedValue interfac } // GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller -func (a *App) GetProductNotices(userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) { - isSystemAdmin := a.SessionHasPermissionTo(*a.Session(), model.PERMISSION_MANAGE_SYSTEM) - isTeamAdmin := a.SessionHasPermissionToTeam(*a.Session(), teamID, model.PERMISSION_MANAGE_TEAM) +func (a *App) GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) { + isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM) + isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PERMISSION_MANAGE_TEAM) // check if notices for regular users are disabled if !*a.Srv().Config().AnnouncementSettings.UserNoticesEnabled && !isSystemAdmin { diff --git a/app/product_notices_test.go b/app/product_notices_test.go index b519e53c269..6f6a184c230 100644 --- a/app/product_notices_test.go +++ b/app/product_notices_test.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" ) @@ -718,7 +719,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them for specified user - messages, appErr := th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 1) @@ -727,7 +728,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them again, see that none are returned - messages, appErr = th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 0) @@ -746,7 +747,7 @@ func TestNoticeFetch(t *testing.T) { require.Nil(t, appErr) // get them again, since conditions don't match we should be zero - messages, appErr = th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") + messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en") require.Nil(t, appErr) require.Len(t, messages, 0) diff --git a/app/reaction.go b/app/reaction.go index 2d0395ddf37..c699ffc0237 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -7,11 +7,12 @@ import ( "errors" "net/http" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" ) -func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { +func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) { post, err := a.GetSinglePost(reaction.PostId) if err != nil { return nil, err @@ -54,7 +55,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ReactionHasBeenAdded(pluginContext, reaction) return true @@ -105,7 +106,7 @@ func populateEmptyReactions(postIDs []string, reactions map[string][]*model.Reac return reactions } -func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { +func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError { post, err := a.GetSinglePost(reaction.PostId) if err != nil { return err @@ -140,7 +141,7 @@ func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.ReactionHasBeenRemoved(pluginContext, reaction) return true diff --git a/app/reaction_test.go b/app/reaction_test.go index 9acf3f2d333..098ebb434f6 100644 --- a/app/reaction_test.go +++ b/app/reaction_test.go @@ -26,7 +26,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, ChannelId: channel.Id, Message: "Hello folks", @@ -39,7 +39,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { EmojiName: "+1", } - _, err = th.App.SaveReactionForPost(reaction) + _, err = th.App.SaveReactionForPost(th.Context, reaction) require.Nil(t, err, "Adding a reaction should not error") th.TearDown() // We need to enforce teardown because reaction instrumentation happens in a goroutine @@ -61,7 +61,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { channel := th.CreateChannel(th.BasicTeam, WithShared(true)) - post, err := th.App.CreatePost(&model.Post{ + post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, ChannelId: channel.Id, Message: "Hello folks", @@ -74,7 +74,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { EmojiName: "+1", } - err = th.App.DeleteReactionForPost(reaction) + err = th.App.DeleteReactionForPost(th.Context, reaction) require.Nil(t, err, "Adding a reaction should not error") th.TearDown() // We need to enforce teardown because reaction instrumentation happens in a goroutine diff --git a/app/remote_cluster_service_mock.go b/app/remote_cluster_service_mock.go index 4a42e64a15c..d10915cb203 100644 --- a/app/remote_cluster_service_mock.go +++ b/app/remote_cluster_service_mock.go @@ -6,6 +6,7 @@ package app import ( "context" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" ) @@ -70,6 +71,6 @@ func (mrcs *mockRemoteClusterService) AcceptInvitation(invite *model.RemoteClust return nil, nil } -func (mrcs *mockRemoteClusterService) ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.RemoteClusterMsg) remotecluster.Response { +func (mrcs *mockRemoteClusterService) ReceiveIncomingMsg(_ *request.Context, rc *model.RemoteCluster, msg model.RemoteClusterMsg) remotecluster.Response { return remotecluster.Response{} } diff --git a/app/request/context.go b/app/request/context.go new file mode 100644 index 00000000000..7b67e5c1a59 --- /dev/null +++ b/app/request/context.go @@ -0,0 +1,99 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package request + +import ( + "context" + + "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/shared/i18n" +) + +type Context struct { + t i18n.TranslateFunc + session model.Session + requestId string + ipAddress string + path string + userAgent string + acceptLanguage string + + context context.Context +} + +func NewContext(ctx context.Context, requestId, ipAddress, path, userAgent, acceptLanguage string, session model.Session, t i18n.TranslateFunc) *Context { + return &Context{ + t: t, + session: session, + requestId: requestId, + ipAddress: ipAddress, + path: path, + userAgent: userAgent, + acceptLanguage: acceptLanguage, + context: ctx, + } +} + +func EmptyContext() *Context { + return &Context{ + t: i18n.T, + context: context.Background(), + } +} + +func (c *Context) T(translationID string, args ...interface{}) string { + return c.t(translationID, args...) +} +func (c *Context) Session() *model.Session { + return &c.session +} +func (c *Context) RequestId() string { + return c.requestId +} +func (c *Context) IpAddress() string { + return c.ipAddress +} +func (c *Context) Path() string { + return c.path +} +func (c *Context) UserAgent() string { + return c.userAgent +} +func (c *Context) AcceptLanguage() string { + return c.acceptLanguage +} + +func (c *Context) Context() context.Context { + return c.context +} + +func (c *Context) SetSession(s *model.Session) { + c.session = *s +} + +func (c *Context) SetT(t i18n.TranslateFunc) { + c.t = t +} +func (c *Context) SetRequestId(s string) { + c.requestId = s +} +func (c *Context) SetIpAddress(s string) { + c.ipAddress = s +} +func (c *Context) SetUserAgent(s string) { + c.userAgent = s +} +func (c *Context) SetAcceptLanguage(s string) { + c.acceptLanguage = s +} +func (c *Context) SetPath(s string) { + c.path = s +} +func (c *Context) SetContext(ctx context.Context) { + c.context = ctx +} + +func (c *Context) GetT() i18n.TranslateFunc { + return c.t +} diff --git a/app/server.go b/app/server.go index f76e6562c68..fd3425b8e60 100644 --- a/app/server.go +++ b/app/server.go @@ -11,7 +11,6 @@ import ( "fmt" "hash/maphash" "html/template" - "io" "io/ioutil" "net" "net/http" @@ -39,6 +38,7 @@ import ( "github.com/rs/cors" "golang.org/x/crypto/acme/autocert" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/einterfaces" @@ -77,10 +77,9 @@ var MaxNotificationsPerChannelDefault int64 = 1000000 var SentryDSN = "placeholder_sentry_dsn" type Server struct { - sqlStore *sqlstore.SqlStore - Store store.Store - WebSocketRouter *WebSocketRouter - AppInitializedOnce sync.Once + sqlStore *sqlstore.SqlStore + Store store.Store + WebSocketRouter *WebSocketRouter // RootRouter is the starting point for all HTTP requests to the server. RootRouter *mux.Router @@ -176,6 +175,7 @@ type Server struct { joinCluster bool startMetrics bool startSearchEngine bool + skipPostInit bool SearchEngine *searchengine.Broker @@ -642,6 +642,48 @@ func NewServer(options ...Option) (*Server, error) { }() } + if s.skipPostInit { + return s, nil + } + + c := request.EmptyContext() + s.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { + if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable { + if appErr := fakeApp.DeactivateGuests(c); appErr != nil { + mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) + } + } + }) + + // Disable active guest accounts on first run if guest accounts are disabled + if !*s.Config().GuestAccountsSettings.Enable { + if appErr := fakeApp.DeactivateGuests(c); appErr != nil { + mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) + } + } + + s.doAppMigrations() + + s.initPostMetadata() + + s.initPlugins(c, *s.Config().PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory) + s.AddConfigListener(func(prevCfg, cfg *model.Config) { + if *cfg.PluginSettings.Enable { + s.initPlugins(c, *cfg.PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory) + } else { + s.ShutDownPlugins() + } + }) + if s.runEssentialJobs { + s.Go(func() { + s.runLicenseExpirationCheckJob() + runCheckAdminSupportStatusJob(fakeApp, c) + runCheckWarnMetricStatusJob(fakeApp, c) + runDNDStatusExpireJob(fakeApp) + }) + s.runJobs() + } + return s, nil } @@ -1400,10 +1442,10 @@ func runSessionCleanupJob(s *Server) { }, time.Hour*24) } -func runLicenseExpirationCheckJob(a *App) { - doLicenseExpirationCheck(a) +func (s *Server) runLicenseExpirationCheckJob() { + s.doLicenseExpirationCheck() model.CreateRecurringTask("License Expiration Check", func() { - doLicenseExpirationCheck(a) + s.doLicenseExpirationCheck() }, time.Hour*24) } @@ -1426,17 +1468,17 @@ func doReportUsageToAWSMeteringService(s *Server) { } //nolint:golint,unused,deadcode -func runCheckWarnMetricStatusJob(a *App) { - doCheckWarnMetricStatus(a) +func runCheckWarnMetricStatusJob(a *App, c *request.Context) { + doCheckWarnMetricStatus(a, c) model.CreateRecurringTask("Check Warn Metric Status Job", func() { - doCheckWarnMetricStatus(a) + doCheckWarnMetricStatus(a, c) }, time.Hour*model.WARN_METRIC_JOB_INTERVAL) } -func runCheckAdminSupportStatusJob(a *App) { - doCheckAdminSupportStatus(a) +func runCheckAdminSupportStatusJob(a *App, c *request.Context) { + doCheckAdminSupportStatus(a, c) model.CreateRecurringTask("Check Admin Support Status Job", func() { - doCheckAdminSupportStatus(a) + doCheckAdminSupportStatus(a, c) }, time.Hour*model.WARN_METRIC_JOB_INTERVAL) } @@ -1461,7 +1503,7 @@ func doSessionCleanup(s *Server) { } //nolint:golint,unused,deadcode -func doCheckWarnMetricStatus(a *App) { +func doCheckWarnMetricStatus(a *App, c *request.Context) { license := a.Srv().License() if license != nil { mlog.Debug("License is present, skip") @@ -1592,7 +1634,7 @@ func doCheckWarnMetricStatus(a *App) { } } - if nerr := a.notifyAdminsOfWarnMetricStatus(warnMetric.Id, isE0Edition); nerr != nil { + if nerr := a.notifyAdminsOfWarnMetricStatus(c, warnMetric.Id, isE0Edition); nerr != nil { mlog.Error("Failed to send notifications to admin users.", mlog.Err(nerr)) } @@ -1604,11 +1646,11 @@ func doCheckWarnMetricStatus(a *App) { } } -func doCheckAdminSupportStatus(a *App) { +func doCheckAdminSupportStatus(a *App, c *request.Context) { isE0Edition := model.BuildEnterpriseReady == "true" if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL { - if err := a.notifyAdminsOfWarnMetricStatus(model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil { + if err := a.notifyAdminsOfWarnMetricStatus(c, model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil { mlog.Error("Failed to send notifications to admin users.", mlog.Err(err)) } } @@ -1714,9 +1756,9 @@ func (s *Server) startMetricsServer() { s.Log.Info("Metrics and profiling server is started", mlog.String("address", l.Addr().String())) } -func doLicenseExpirationCheck(a *App) { - a.Srv().LoadLicense() - license := a.Srv().License() +func (s *Server) doLicenseExpirationCheck() { + s.LoadLicense() + license := s.License() if license == nil { mlog.Debug("License cannot be found.") @@ -1728,7 +1770,7 @@ func doLicenseExpirationCheck(a *App) { return } - users, err := a.Srv().Store.User().GetSystemAdminProfiles() + users, err := s.Store.User().GetSystemAdminProfiles() if err != nil { mlog.Error("Failed to get system admins for license expired message from Mattermost.") return @@ -1743,15 +1785,15 @@ func doLicenseExpirationCheck(a *App) { } mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email)) - a.Srv().Go(func() { - if err := a.Srv().EmailService.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *a.Config().ServiceSettings.SiteURL); err != nil { + s.Go(func() { + if err := s.EmailService.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *s.Config().ServiceSettings.SiteURL); err != nil { mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err)) } }) } //remove the license - a.Srv().RemoveLicense() + s.RemoveLicense() } func (s *Server) StartSearchEngine() (string, string) { @@ -1884,6 +1926,50 @@ func (s *Server) initJobs() { if jobsMigrationsInterface != nil { s.Jobs.Migrations = jobsMigrationsInterface(s) } + if jobsLdapSyncInterface != nil { + s.Jobs.LdapSync = jobsLdapSyncInterface(s) + } + if jobsPluginsInterface != nil { + s.Jobs.Plugins = jobsPluginsInterface(s) + } + if jobsExpiryNotifyInterface != nil { + s.Jobs.ExpiryNotify = jobsExpiryNotifyInterface(s) + } + if productNoticesJobInterface != nil { + s.Jobs.ProductNotices = productNoticesJobInterface(s) + } + if jobsImportProcessInterface != nil { + s.Jobs.ImportProcess = jobsImportProcessInterface(s) + } + if jobsImportDeleteInterface != nil { + s.Jobs.ImportDelete = jobsImportDeleteInterface(s) + } + if jobsExportDeleteInterface != nil { + s.Jobs.ExportDelete = jobsExportDeleteInterface(s) + } + + if jobsExportProcessInterface != nil { + s.Jobs.ExportProcess = jobsExportProcessInterface(s) + } + + if jobsExportProcessInterface != nil { + s.Jobs.ExportProcess = jobsExportProcessInterface(s) + } + + if jobsActiveUsersInterface != nil { + s.Jobs.ActiveUsers = jobsActiveUsersInterface(s) + } + + if jobsCloudInterface != nil { + s.Jobs.Cloud = jobsCloudInterface(s) + } + + if jobsResendInvitationEmailInterface != nil { + s.Jobs.ResendInvitationEmails = jobsResendInvitationEmailInterface(s) + } + + s.Jobs.InitWorkers() + s.Jobs.InitSchedulers() } func (s *Server) TelemetryId() string { @@ -2135,7 +2221,7 @@ func (s *Server) GetProfileImage(user *model.User) ([]byte, bool, *model.AppErro } if user.LastPictureUpdate == 0 { - if _, err := s.WriteFile(bytes.NewReader(img), path); err != nil { + if _, err := s.writeFile(bytes.NewReader(img), path); err != nil { return nil, false, err } } @@ -2173,18 +2259,18 @@ func (s *Server) ReadFile(path string) ([]byte, *model.AppError) { return result, nil } -func (s *Server) WriteFile(fr io.Reader, path string) (int64, *model.AppError) { - backend, err := s.FileBackend() - if err != nil { - return 0, err - } +// func (s *Server) WriteFile(fr io.Reader, path string) (int64, *model.AppError) { +// backend, err := s.FileBackend() +// if err != nil { +// return 0, err +// } - result, nErr := backend.WriteFile(fr, path) - if nErr != nil { - return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError) - } - return result, nil -} +// result, nErr := backend.WriteFile(fr, path) +// if nErr != nil { +// return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError) +// } +// return result, nil +// } func runDNDStatusExpireJob(a *App) { if a.IsLeader() { diff --git a/app/server_test.go b/app/server_test.go index df19ea62469..18dbd908c82 100644 --- a/app/server_test.go +++ b/app/server_test.go @@ -709,12 +709,12 @@ func TestAdminAdvisor(t *testing.T) { AuthService: "", Roles: model.SYSTEM_ADMIN_ROLE_ID, } - ruser, err := th.App.CreateUser(&user) + ruser, err := th.App.CreateUser(th.Context, &user) assert.Nil(t, err, "User should be created") - defer th.App.PermanentDeleteUser(&user) + defer th.App.PermanentDeleteUser(th.Context, &user) t.Run("Should notify admin of un-configured support email", func(t *testing.T) { - doCheckAdminSupportStatus(th.App) + doCheckAdminSupportStatus(th.App, th.Context) bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME) assert.NotNil(t, bot, "Bot should have been created now") @@ -742,7 +742,7 @@ func TestAdminAdvisor(t *testing.T) { err = th.App.PermanentDeleteChannel(channel) assert.Nil(t, err, "No error should be generated") - doCheckAdminSupportStatus(th.App) + doCheckAdminSupportStatus(th.App, th.Context) channel, err = th.App.getDirectChannel(bot.Id, ruser.Id) assert.NotNil(t, channel, "DM channel should exist between Admin Advisor and system admin") diff --git a/app/session_test.go b/app/session_test.go index dcfe91b961f..3b1c27b72af 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -148,7 +148,7 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) { require.Nil(t, err) assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST]) - err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) rsession, err = th.App.GetSession(session.Token) diff --git a/app/slack.go b/app/slack.go index 22f5afac1b2..5c7c078e9d1 100644 --- a/app/slack.go +++ b/app/slack.go @@ -10,21 +10,31 @@ import ( "mime/multipart" "regexp" "strings" + "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/slackimport" "github.com/mattermost/mattermost-server/v5/store" ) -func (a *App) SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { +func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { actions := slackimport.Actions{ - UpdateActive: a.UpdateActive, - AddUserToChannel: a.AddUserToChannel, - JoinUserToTeam: a.JoinUserToTeam, - CreateDirectChannel: a.createDirectChannel, - CreateGroupChannel: a.createGroupChannel, - CreateChannel: a.CreateChannel, - DoUploadFile: a.DoUploadFile, + UpdateActive: func(user *model.User, active bool) (*model.User, *model.AppError) { + return a.UpdateActive(c, user, active) + }, + AddUserToChannel: a.AddUserToChannel, + JoinUserToTeam: func(team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) { + return a.JoinUserToTeam(c, team, user, userRequestorId) + }, + CreateDirectChannel: a.createDirectChannel, + CreateGroupChannel: a.createGroupChannel, + CreateChannel: func(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { + return a.CreateChannel(c, channel, addMember) + }, + DoUploadFile: func(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { + return a.DoUploadFile(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data) + }, GenerateThumbnailImage: a.generateThumbnailImage, GeneratePreviewImage: a.generatePreviewImage, InvalidateAllCaches: func() { a.srv.InvalidateAllCaches() }, diff --git a/app/slashcommands/auto_channels.go b/app/slashcommands/auto_channels.go index b81c96c3b71..e5f479d0f90 100644 --- a/app/slashcommands/auto_channels.go +++ b/app/slashcommands/auto_channels.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/utils" ) @@ -35,7 +36,7 @@ func NewAutoChannelCreator(a *app.App, team *model.Team, userID string) *AutoCha } } -func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, error) { +func (cfg *AutoChannelCreator) createRandomChannel(c *request.Context) (*model.Channel, error) { var displayName string if cfg.Fuzzy { displayName = utils.FuzzName() @@ -52,20 +53,20 @@ func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, error) { CreatorId: cfg.userID, } - channel, err := cfg.a.CreateChannel(channel, true) + channel, err := cfg.a.CreateChannel(c, channel, true) if err != nil { return nil, err } return channel, nil } -func (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, error) { +func (cfg *AutoChannelCreator) CreateTestChannels(c *request.Context, num utils.Range) ([]*model.Channel, error) { numChannels := utils.RandIntFromRange(num) channels := make([]*model.Channel, numChannels) for i := 0; i < numChannels; i++ { var err error - channels[i], err = cfg.createRandomChannel() + channels[i], err = cfg.createRandomChannel(c) if err != nil { return nil, err } diff --git a/app/slashcommands/auto_environment.go b/app/slashcommands/auto_environment.go index 8270d328acc..8e283174432 100644 --- a/app/slashcommands/auto_environment.go +++ b/app/slashcommands/auto_environment.go @@ -8,6 +8,7 @@ import ( "time" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/utils" ) @@ -17,7 +18,7 @@ type TestEnvironment struct { Environments []TeamEnvironment } -func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeams utils.Range, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TestEnvironment, error) { +func CreateTestEnvironmentWithTeams(a *app.App, c *request.Context, client *model.Client4, rangeTeams utils.Range, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TestEnvironment, error) { rand.Seed(time.Now().UTC().UnixNano()) teamCreator := NewAutoTeamCreator(client) @@ -32,12 +33,12 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam for i, team := range teams { userCreator := NewAutoUserCreator(a, client, team) userCreator.Fuzzy = fuzzy - randomUser, err := userCreator.createRandomUser() + randomUser, err := userCreator.createRandomUser(c) if err != nil { return TestEnvironment{}, err } client.LoginById(randomUser.Id, UserPassword) - teamEnvironment, err := CreateTestEnvironmentInTeam(a, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy) + teamEnvironment, err := CreateTestEnvironmentInTeam(a, c, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy) if err != nil { return TestEnvironment{}, err } @@ -47,7 +48,7 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam return environment, nil } -func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.Team, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TeamEnvironment, error) { +func CreateTestEnvironmentInTeam(a *app.App, c *request.Context, client *model.Client4, team *model.Team, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TeamEnvironment, error) { rand.Seed(time.Now().UTC().UnixNano()) // We need to create at least one user @@ -57,7 +58,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model. userCreator := NewAutoUserCreator(a, client, team) userCreator.Fuzzy = fuzzy - users, err := userCreator.CreateTestUsers(rangeUsers) + users, err := userCreator.CreateTestUsers(c, rangeUsers) if err != nil { return TeamEnvironment{}, nil } @@ -68,7 +69,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model. channelCreator := NewAutoChannelCreator(a, team, users[0].Id) channelCreator.Fuzzy = fuzzy - channels, err := channelCreator.CreateTestChannels(rangeChannels) + channels, err := channelCreator.CreateTestChannels(c, rangeChannels) if err != nil { return TeamEnvironment{}, nil } @@ -102,7 +103,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model. postCreator.HasImage = i < numImages postCreator.Users = usernames postCreator.Fuzzy = fuzzy - _, err := postCreator.CreateRandomPost() + _, err := postCreator.CreateRandomPost(c) if err != nil { return TeamEnvironment{}, err } diff --git a/app/slashcommands/auto_posts.go b/app/slashcommands/auto_posts.go index dc78f2134cc..979f9d050d2 100644 --- a/app/slashcommands/auto_posts.go +++ b/app/slashcommands/auto_posts.go @@ -10,6 +10,7 @@ import ( "path/filepath" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/utils" "github.com/mattermost/mattermost-server/v5/utils/fileutils" @@ -44,7 +45,7 @@ func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator { } } -func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) { +func (cfg *AutoPostCreator) UploadTestFile(c *request.Context) ([]string, error) { filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})] path, _ := fileutils.FindDir("tests") @@ -60,7 +61,7 @@ func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) { return nil, err } - fileResp, err2 := cfg.a.UploadFile(data.Bytes(), cfg.channelid, filename) + fileResp, err2 := cfg.a.UploadFile(c, data.Bytes(), cfg.channelid, filename) if err2 != nil { return nil, err2 } @@ -68,15 +69,15 @@ func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) { return []string{fileResp.Id}, nil } -func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, error) { - return cfg.CreateRandomPostNested("", "") +func (cfg *AutoPostCreator) CreateRandomPost(c *request.Context) (*model.Post, error) { + return cfg.CreateRandomPostNested(c, "", "") } -func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*model.Post, error) { +func (cfg *AutoPostCreator) CreateRandomPostNested(c *request.Context, parentId, rootId string) (*model.Post, error) { var fileIDs []string if cfg.HasImage { var err error - fileIDs, err = cfg.UploadTestFile() + fileIDs, err = cfg.UploadTestFile(c) if err != nil { return nil, err } @@ -97,7 +98,7 @@ func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*mo Message: postText, FileIds: fileIDs, } - rpost, err := cfg.a.CreatePostMissingChannel(post, true) + rpost, err := cfg.a.CreatePostMissingChannel(c, post, true) if err != nil { return nil, err } diff --git a/app/slashcommands/auto_users.go b/app/slashcommands/auto_users.go index cf76741e8dd..b376a40525d 100644 --- a/app/slashcommands/auto_users.go +++ b/app/slashcommands/auto_users.go @@ -8,6 +8,7 @@ import ( "net/http" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/store" "github.com/mattermost/mattermost-server/v5/utils" @@ -77,7 +78,7 @@ func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError { return nil } -func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) { +func (cfg *AutoUserCreator) createRandomUser(c *request.Context) (*model.User, error) { var userEmail string var userName string if cfg.Fuzzy { @@ -93,7 +94,7 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) { Nickname: userName, Password: UserPassword} - ruser, appErr := cfg.app.CreateUserWithInviteId(user, cfg.team.InviteId, "") + ruser, appErr := cfg.app.CreateUserWithInviteId(c, user, cfg.team.InviteId, "") if appErr != nil { return nil, appErr } @@ -112,13 +113,13 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) { return ruser, nil } -func (cfg *AutoUserCreator) CreateTestUsers(num utils.Range) ([]*model.User, error) { +func (cfg *AutoUserCreator) CreateTestUsers(c *request.Context, num utils.Range) ([]*model.User, error) { numUsers := utils.RandIntFromRange(num) users := make([]*model.User, numUsers) for i := 0; i < numUsers; i++ { var err error - users[i], err = cfg.createRandomUser() + users[i], err = cfg.createRandomUser(c) if err != nil { return nil, err } diff --git a/app/slashcommands/command_away.go b/app/slashcommands/command_away.go index 19250583d0c..c29b1baaa56 100644 --- a/app/slashcommands/command_away.go +++ b/app/slashcommands/command_away.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (*AwayProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*AwayProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*AwayProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusAwayIfNeeded(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")} diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index ab09aab9500..57f4ce63169 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -7,6 +7,7 @@ import ( "context" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -36,7 +37,7 @@ func (*HeaderProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{ @@ -92,7 +93,7 @@ func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message st } *patch.Header = message - _, err = a.PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(c, channel, patch, args.UserId) if err != nil { text := args.T("api.command_channel_header.update_channel.app_error") if err.Id == "model.channel.is_valid.header.app_error" { diff --git a/app/slashcommands/command_channel_header_test.go b/app/slashcommands/command_channel_header_test.go index e64d814a84e..adfa6f265dd 100644 --- a/app/slashcommands/command_channel_header_test.go +++ b/app/slashcommands/command_channel_header_test.go @@ -30,7 +30,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { "": "api.command_channel_header.message.app_error", "hello": "", } { - actual := hp.DoCommand(th.App, args, msg).Text + actual := hp.DoCommand(th.App, th.Context, args, msg).Text assert.Equal(t, expected, actual) } @@ -43,7 +43,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual := hp.DoCommand(th.App, args, "hello").Text + actual := hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_header.permission.app_error", actual) th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) @@ -57,7 +57,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID) @@ -69,7 +69,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_header.permission.app_error", actual) // Try a group channel *with* being a member. @@ -85,7 +85,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: user1.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) // Try a group channel *without* being a member. @@ -95,7 +95,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: user3.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_header.permission.app_error", actual) // Try a direct channel *with* being a member. @@ -107,7 +107,7 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) // Try a direct channel *without* being a member. @@ -117,6 +117,6 @@ func TestHeaderProviderDoCommand(t *testing.T) { UserId: user2.Id, } - actual = hp.DoCommand(th.App, args, "hello").Text + actual = hp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_header.permission.app_error", actual) } diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index 1d350b84990..128492788ad 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (*PurposeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comm } } -func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{ @@ -77,7 +78,7 @@ func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message s } *patch.Purpose = message - _, err = a.PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(c, channel, patch, args.UserId) if err != nil { text := args.T("api.command_channel_purpose.update_channel.app_error") if err.Id == "model.channel.is_valid.purpose.app_error" { diff --git a/app/slashcommands/command_channel_purpose_test.go b/app/slashcommands/command_channel_purpose_test.go index 02b8db328fa..0a31d1039e3 100644 --- a/app/slashcommands/command_channel_purpose_test.go +++ b/app/slashcommands/command_channel_purpose_test.go @@ -30,7 +30,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { "": "api.command_channel_purpose.message.app_error", "hello": "", } { - actual := pp.DoCommand(th.App, args, msg).Text + actual := pp.DoCommand(th.App, th.Context, args, msg).Text assert.Equal(t, expected, actual) } @@ -42,7 +42,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { ChannelId: th.BasicChannel.Id, } - actual := pp.DoCommand(th.App, args, "hello").Text + actual := pp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual) // Try a private channel *with* permission. @@ -56,7 +56,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = pp.DoCommand(th.App, args, "hello").Text + actual = pp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) // Try a private channel *without* permission. @@ -67,7 +67,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { ChannelId: privateChannel.Id, } - actual = pp.DoCommand(th.App, args, "hello").Text + actual = pp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual) // Try a group channel *with* being a member. @@ -81,7 +81,7 @@ func TestPurposeProviderDoCommand(t *testing.T) { ChannelId: groupChannel.Id, } - actual = pp.DoCommand(th.App, args, "hello").Text + actual = pp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual) // Try a direct channel *with* being a member. @@ -92,6 +92,6 @@ func TestPurposeProviderDoCommand(t *testing.T) { ChannelId: directChannel.Id, } - actual = pp.DoCommand(th.App, args, "hello").Text + actual = pp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual) } diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index 3aba972b3f4..13d747b62f8 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -37,7 +38,7 @@ func (*RenameProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{ @@ -91,7 +92,7 @@ func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message st } *patch.DisplayName = message - _, err = a.PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(c, channel, patch, args.UserId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.update_channel.app_error"), diff --git a/app/slashcommands/command_channel_rename_test.go b/app/slashcommands/command_channel_rename_test.go index a65b96ce63b..e5bfaf7be26 100644 --- a/app/slashcommands/command_channel_rename_test.go +++ b/app/slashcommands/command_channel_rename_test.go @@ -33,7 +33,7 @@ func TestRenameProviderDoCommand(t *testing.T) { "More than 22 chars but less than 64": "", strings.Repeat("12345", 13): "api.command_channel_rename.too_long.app_error", } { - actual := rp.DoCommand(th.App, args, msg).Text + actual := rp.DoCommand(th.App, th.Context, args, msg).Text assert.Equal(t, expected, actual) } @@ -46,7 +46,7 @@ func TestRenameProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual := rp.DoCommand(th.App, args, "hello").Text + actual := rp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_rename.permission.app_error", actual) // Try a private channel *with* permission. @@ -60,7 +60,7 @@ func TestRenameProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, "hello").Text + actual = rp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "", actual) // Try a private channel *without* permission. @@ -72,7 +72,7 @@ func TestRenameProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, "hello").Text + actual = rp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_rename.permission.app_error", actual) // Try a group channel *with* being a member. @@ -87,7 +87,7 @@ func TestRenameProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, "hello").Text + actual = rp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual) // Try a direct channel *with* being a member. @@ -99,6 +99,6 @@ func TestRenameProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, "hello").Text + actual = rp.DoCommand(th.App, th.Context, args, "hello").Text assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual) } diff --git a/app/slashcommands/command_code.go b/app/slashcommands/command_code.go index a4f821a014d..f61e614fc65 100644 --- a/app/slashcommands/command_code.go +++ b/app/slashcommands/command_code.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -36,7 +37,7 @@ func (*CodeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*CodeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if message == "" { return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/slashcommands/command_code_test.go b/app/slashcommands/command_code_test.go index c8888398710..d331a1977a0 100644 --- a/app/slashcommands/command_code_test.go +++ b/app/slashcommands/command_code_test.go @@ -21,7 +21,7 @@ func TestCodeProviderDoCommand(t *testing.T) { "foo\nbar": " foo\n bar", "foo\nbar\n": " foo\n bar\n ", } { - actual := cp.DoCommand(nil, args, msg).Text + actual := cp.DoCommand(nil, nil, args, msg).Text if actual != expected { t.Errorf("expected `%v`, got `%v`", expected, actual) } diff --git a/app/slashcommands/command_custom_status.go b/app/slashcommands/command_custom_status.go index b93884c40ea..8851bfbcf58 100644 --- a/app/slashcommands/command_custom_status.go +++ b/app/slashcommands/command_custom_status.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -40,7 +41,7 @@ func (*CustomStatusProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model } } -func (*CustomStatusProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*CustomStatusProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !*a.Config().TeamSettings.EnableCustomUserStatuses { return nil } diff --git a/app/slashcommands/command_dnd.go b/app/slashcommands/command_dnd.go index 45d4aafe32a..86f238e9990 100644 --- a/app/slashcommands/command_dnd.go +++ b/app/slashcommands/command_dnd.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (*DndProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*DndProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*DndProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusDoNotDisturb(args.UserId) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.success")} diff --git a/app/slashcommands/command_echo.go b/app/slashcommands/command_echo.go index 2b24c3268fb..504dfe7a42d 100644 --- a/app/slashcommands/command_echo.go +++ b/app/slashcommands/command_echo.go @@ -9,6 +9,7 @@ import ( "time" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -41,7 +42,7 @@ func (*EchoProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*EchoProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if message == "" { return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -89,7 +90,7 @@ func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri time.Sleep(time.Duration(delay) * time.Second) - if _, err := a.CreatePostMissingChannel(post, true); err != nil { + if _, err := a.CreatePostMissingChannel(c, post, true); err != nil { mlog.Error("Unable to create /echo post.", mlog.Err(err)) } }) diff --git a/app/slashcommands/command_expand_collapse.go b/app/slashcommands/command_expand_collapse.go index 8f74e831bc7..fe43a100ba5 100644 --- a/app/slashcommands/command_expand_collapse.go +++ b/app/slashcommands/command_expand_collapse.go @@ -7,6 +7,7 @@ import ( "strconv" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -53,11 +54,11 @@ func (*CollapseProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com } } -func (*ExpandProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*ExpandProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return setCollapsePreference(a, args, false) } -func (*CollapseProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*CollapseProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return setCollapsePreference(a, args, true) } diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index d48aabe9555..4537089516c 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -38,7 +39,7 @@ func (*groupmsgProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com } } -func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { targetUsers := map[string]*model.User{} targetUsersSlice := []string{args.UserId} invalidUsernames := []string{} @@ -82,7 +83,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message } if len(targetUsersSlice) == 2 { - return app.GetCommandProvider("msg").DoCommand(a, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage)) + return app.GetCommandProvider("msg").DoCommand(a, c, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage)) } if len(targetUsersSlice) < model.CHANNEL_GROUP_MIN_USERS { @@ -126,7 +127,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message post.Message = parsedMessage post.ChannelId = groupChannel.Id post.UserId = args.UserId - if _, err := a.CreatePostMissingChannel(post, true); err != nil { + if _, err := a.CreatePostMissingChannel(c, post, true); err != nil { return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } diff --git a/app/slashcommands/command_groupmsg_test.go b/app/slashcommands/command_groupmsg_test.go index e351b9b4cbd..bbd34533239 100644 --- a/app/slashcommands/command_groupmsg_test.go +++ b/app/slashcommands/command_groupmsg_test.go @@ -67,7 +67,7 @@ func TestGroupMsgProvider(t *testing.T) { th.removePermissionFromRole(model.PERMISSION_CREATE_GROUP_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) t.Run("Check without permission to create a GM channel.", func(t *testing.T) { - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -83,7 +83,7 @@ func TestGroupMsgProvider(t *testing.T) { t.Run("Check without permissions to view a user in the list.", func(t *testing.T) { th.removePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) defer th.addPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID) - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -95,7 +95,7 @@ func TestGroupMsgProvider(t *testing.T) { }) t.Run("Check with permission to create a GM channel.", func(t *testing.T) { - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -108,7 +108,7 @@ func TestGroupMsgProvider(t *testing.T) { }) t.Run("Check without permission to post to an existing GM channel.", func(t *testing.T) { - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, diff --git a/app/slashcommands/command_help.go b/app/slashcommands/command_help.go index f1424b470fc..26984083cb0 100644 --- a/app/slashcommands/command_help.go +++ b/app/slashcommands/command_help.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (h *HelpProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (h *HelpProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (h *HelpProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { helpLink := *a.Config().SupportSettings.HelpLink if helpLink == "" { diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index b8f54263eac..5a94146738b 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -38,7 +39,7 @@ func (*InviteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (*InviteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if message == "" { return &model.CommandResponse{ Text: args.T("api.command_invite.missing_message.app_error"), @@ -140,7 +141,7 @@ func (*InviteProvider) DoCommand(a *app.App, args *model.CommandArgs, message st } } - if _, err := a.AddChannelMember(userProfile.Id, channelToJoin, app.ChannelMemberOpts{ + if _, err := a.AddChannelMember(c, userProfile.Id, channelToJoin, app.ChannelMemberOpts{ UserRequestorID: args.UserId, }); err != nil { var text string diff --git a/app/slashcommands/command_invite_people.go b/app/slashcommands/command_invite_people.go index b005b8509fc..a27f2594b92 100644 --- a/app/slashcommands/command_invite_people.go +++ b/app/slashcommands/command_invite_people.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -41,7 +42,7 @@ func (*InvitePeopleProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model } } -func (*InvitePeopleProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*InvitePeopleProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PERMISSION_INVITE_USER) { return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/slashcommands/command_invite_people_test.go b/app/slashcommands/command_invite_people_test.go index 89e2f17fc99..7eb1db7105f 100644 --- a/app/slashcommands/command_invite_people_test.go +++ b/app/slashcommands/command_invite_people_test.go @@ -32,11 +32,11 @@ func TestInvitePeopleProvider(t *testing.T) { UserId: notTeamUser.Id, } - actual := cmd.DoCommand(th.App, args, model.NewId()+"@simulator.amazonses.com") + actual := cmd.DoCommand(th.App, th.Context, args, model.NewId()+"@simulator.amazonses.com") assert.Equal(t, "api.command_invite_people.permission.app_error", actual.Text) // Test with required permissions. args.UserId = th.BasicUser.Id - actual = cmd.DoCommand(th.App, args, model.NewId()+"@simulator.amazonses.com") + actual = cmd.DoCommand(th.App, th.Context, args, model.NewId()+"@simulator.amazonses.com") assert.Equal(t, "api.command.invite_people.sent", actual.Text) } diff --git a/app/slashcommands/command_invite_test.go b/app/slashcommands/command_invite_test.go index d3f84cc7cd8..7b37d7ad47d 100644 --- a/app/slashcommands/command_invite_test.go +++ b/app/slashcommands/command_invite_test.go @@ -26,34 +26,34 @@ func TestInviteProvider(t *testing.T) { th.linkUserToTeam(basicUser3, th.BasicTeam) basicUser4 := th.createUser() deactivatedUser := th.createUser() - th.App.UpdateActive(deactivatedUser, false) + th.App.UpdateActive(th.Context, deactivatedUser, false) var err *model.AppError - _, err = th.App.CreateBot(&model.Bot{ + _, err = th.App.CreateBot(th.Context, &model.Bot{ Username: "bot1", OwnerId: basicUser3.Id, Description: "a test bot", }) require.Nil(t, err) - bot2, err := th.App.CreateBot(&model.Bot{ + bot2, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "bot2", OwnerId: basicUser3.Id, Description: "a test bot", }) require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, bot2.UserId, basicUser3.Id) + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, bot2.UserId, basicUser3.Id) require.Nil(t, err) - bot3, err := th.App.CreateBot(&model.Bot{ + bot3, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "bot3", OwnerId: basicUser3.Id, Description: "a test bot", }) require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, bot3.UserId, basicUser3.Id) + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, bot3.UserId, basicUser3.Id) require.Nil(t, err) - err = th.App.RemoveUserFromTeam(th.BasicTeam.Id, bot3.UserId, basicUser3.Id) + err = th.App.RemoveUserFromTeam(th.Context, th.BasicTeam.Id, bot3.UserId, basicUser3.Id) require.Nil(t, err) InviteP := InviteProvider{} @@ -73,7 +73,7 @@ func TestInviteProvider(t *testing.T) { deactivatedUserPublicChannel := "@" + deactivatedUser.Username + " ~" + channel.Name groupChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE) - _, err = th.App.AddChannelMember(th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{}) require.Nil(t, err) groupChannel.GroupConstrained = model.NewBool(true) groupChannel, _ = th.App.UpdateChannel(groupChannel) @@ -169,7 +169,7 @@ func TestInviteProvider(t *testing.T) { for _, test := range tests { t.Run(test.desc, func(t *testing.T) { - actual := InviteP.DoCommand(th.App, args, test.msg).Text + actual := InviteP.DoCommand(th.App, th.Context, args, test.msg).Text assert.Equal(t, test.expected, actual) }) } @@ -181,8 +181,8 @@ func TestInviteGroup(t *testing.T) { th.BasicTeam.GroupConstrained = model.NewBool(true) var err *model.AppError - _, _ = th.App.AddTeamMember(th.BasicTeam.Id, th.BasicUser.Id) - _, err = th.App.AddTeamMember(th.BasicTeam.Id, th.BasicUser2.Id) + _, _ = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, th.BasicUser.Id) + _, err = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, th.BasicUser2.Id) require.Nil(t, err) th.BasicTeam, _ = th.App.UpdateTeam(th.BasicTeam) @@ -225,7 +225,7 @@ func TestInviteGroup(t *testing.T) { for _, test := range tests { t.Run(test.desc, func(t *testing.T) { - actual := InviteP.DoCommand(th.App, args, test.msg).Text + actual := InviteP.DoCommand(th.App, th.Context, args, test.msg).Text assert.Equal(t, test.expected, actual) }) } diff --git a/app/slashcommands/command_join.go b/app/slashcommands/command_join.go index af5234cc125..56ee55aca70 100644 --- a/app/slashcommands/command_join.go +++ b/app/slashcommands/command_join.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -36,7 +37,7 @@ func (*JoinProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*JoinProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*JoinProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { channelName := strings.ToLower(message) if strings.HasPrefix(message, "~") { @@ -65,7 +66,7 @@ func (*JoinProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if appErr := a.JoinChannel(channel, args.UserId); appErr != nil { + if appErr := a.JoinChannel(c, channel, args.UserId); appErr != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/slashcommands/command_join_test.go b/app/slashcommands/command_join_test.go index e70da6ec132..09f10509737 100644 --- a/app/slashcommands/command_join_test.go +++ b/app/slashcommands/command_join_test.go @@ -21,7 +21,7 @@ func TestJoinCommandNoChannel(t *testing.T) { } cmd := &JoinProvider{} - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), UserId: th.BasicUser2.Id, SiteURL: "http://test.url", @@ -39,7 +39,7 @@ func TestJoinCommandForExistingChannel(t *testing.T) { t.SkipNow() } - channel2, _ := th.App.CreateChannel(&model.Channel{ + channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -48,7 +48,7 @@ func TestJoinCommandForExistingChannel(t *testing.T) { }, false) cmd := &JoinProvider{} - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), UserId: th.BasicUser2.Id, SiteURL: "http://test.url", @@ -67,7 +67,7 @@ func TestJoinCommandWithTilde(t *testing.T) { t.SkipNow() } - channel2, _ := th.App.CreateChannel(&model.Channel{ + channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -76,7 +76,7 @@ func TestJoinCommandWithTilde(t *testing.T) { }, false) cmd := &JoinProvider{} - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), UserId: th.BasicUser2.Id, SiteURL: "http://test.url", @@ -91,7 +91,7 @@ func TestJoinCommandPermissions(t *testing.T) { th := setup(t).initBasic() defer th.tearDown() - channel2, _ := th.App.CreateChannel(&model.Channel{ + channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -111,7 +111,7 @@ func TestJoinCommandPermissions(t *testing.T) { TeamId: th.BasicTeam.Id, } - actual := cmd.DoCommand(th.App, args, "~"+channel2.Name).Text + actual := cmd.DoCommand(th.App, th.Context, args, "~"+channel2.Name).Text assert.Equal(t, "api.command_join.fail.app_error", actual) // Try a public channel with permission. @@ -122,11 +122,11 @@ func TestJoinCommandPermissions(t *testing.T) { TeamId: th.BasicTeam.Id, } - actual = cmd.DoCommand(th.App, args, "~"+channel2.Name).Text + actual = cmd.DoCommand(th.App, th.Context, args, "~"+channel2.Name).Text assert.Equal(t, "", actual) // Try a private channel *without* permission. - channel3, _ := th.App.CreateChannel(&model.Channel{ + channel3, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_PRIVATE, @@ -141,6 +141,6 @@ func TestJoinCommandPermissions(t *testing.T) { TeamId: th.BasicTeam.Id, } - actual = cmd.DoCommand(th.App, args, "~"+channel3.Name).Text + actual = cmd.DoCommand(th.App, th.Context, args, "~"+channel3.Name).Text assert.Equal(t, "api.command_join.fail.app_error", actual) } diff --git a/app/slashcommands/command_leave.go b/app/slashcommands/command_leave.go index e6c7b7314bb..b3c884dd3ec 100644 --- a/app/slashcommands/command_leave.go +++ b/app/slashcommands/command_leave.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (*LeaveProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comman } } -func (*LeaveProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { var channel *model.Channel var noChannelErr *model.AppError if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { @@ -45,7 +46,7 @@ func (*LeaveProvider) DoCommand(a *app.App, args *model.CommandArgs, message str return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - err = a.LeaveChannel(args.ChannelId, args.UserId) + err = a.LeaveChannel(c, args.ChannelId, args.UserId) if err != nil { if channel.Name == model.DEFAULT_CHANNEL { return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} diff --git a/app/slashcommands/command_leave_test.go b/app/slashcommands/command_leave_test.go index 54cd0e48d14..cf824bab8bd 100644 --- a/app/slashcommands/command_leave_test.go +++ b/app/slashcommands/command_leave_test.go @@ -19,7 +19,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { lp := LeaveProvider{} - publicChannel, _ := th.App.CreateChannel(&model.Channel{ + publicChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -27,7 +27,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { CreatorId: th.BasicUser.Id, }, false) - privateChannel, _ := th.App.CreateChannel(&model.Channel{ + privateChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -40,10 +40,10 @@ func TestLeaveProviderDoCommand(t *testing.T) { guest := th.createGuest() - th.App.AddUserToTeam(th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id) + th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id) th.App.AddUserToChannel(th.BasicUser, publicChannel, false) th.App.AddUserToChannel(th.BasicUser, privateChannel, false) - th.App.AddUserToTeam(th.BasicTeam.Id, guest.Id, guest.Id) + th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, guest.Id) th.App.AddUserToChannel(guest, publicChannel, false) th.App.AddUserToChannel(guest, defaultChannel, false) @@ -52,7 +52,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, T: func(s string, args ...interface{}) string { return s }, } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType) }) @@ -63,7 +63,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { ChannelId: publicChannel.Id, T: func(s string, args ...interface{}) string { return s }, } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.command_leave.fail.app_error", actual.Text) assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType) }) @@ -76,7 +76,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "", actual.Text) assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+model.DEFAULT_CHANNEL, actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) @@ -94,7 +94,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "", actual.Text) }) @@ -106,7 +106,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "api.channel.leave.default.app_error", actual.Text) }) @@ -118,7 +118,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "", actual.Text) assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+publicChannel.Name, actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) @@ -136,7 +136,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { TeamId: th.BasicTeam.Id, SiteURL: "http://localhost:8065", } - actual := lp.DoCommand(th.App, args, "") + actual := lp.DoCommand(th.App, th.Context, args, "") assert.Equal(t, "", actual.Text) assert.Equal(t, args.SiteURL+"/", actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index 3ddd2b426ed..daea6c5039e 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -15,6 +15,7 @@ import ( "github.com/pkg/errors" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -108,8 +109,8 @@ func (*LoadTestProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com } } -func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { - commandResponse, err := lt.doCommand(a, args, message) +func (lt *LoadTestProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { + commandResponse, err := lt.doCommand(a, c, args, message) if err != nil { mlog.Error("failed command /"+CmdTest, mlog.Err(err)) } @@ -117,34 +118,34 @@ func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, messa return commandResponse } -func (lt *LoadTestProvider) doCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (lt *LoadTestProvider) doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { //This command is only available when EnableTesting is true if !*a.Config().ServiceSettings.EnableTesting { return &model.CommandResponse{}, nil } if strings.HasPrefix(message, "setup") { - return lt.SetupCommand(a, args, message) + return lt.SetupCommand(a, c, args, message) } if strings.HasPrefix(message, "users") { - return lt.UsersCommand(a, args, message) + return lt.UsersCommand(a, c, args, message) } if strings.HasPrefix(message, "activate_user") { - return lt.ActivateUserCommand(a, args, message) + return lt.ActivateUserCommand(a, c, args, message) } if strings.HasPrefix(message, "deactivate_user") { - return lt.DeActivateUserCommand(a, args, message) + return lt.DeActivateUserCommand(a, c, args, message) } if strings.HasPrefix(message, "channels") { - return lt.ChannelsCommand(a, args, message) + return lt.ChannelsCommand(a, c, args, message) } if strings.HasPrefix(message, "posts") { - return lt.PostsCommand(a, args, message) + return lt.PostsCommand(a, c, args, message) } if strings.HasPrefix(message, "post") { @@ -152,15 +153,15 @@ func (lt *LoadTestProvider) doCommand(a *app.App, args *model.CommandArgs, messa } if strings.HasPrefix(message, "threaded_post") { - return lt.ThreadedPostCommand(a, args, message) + return lt.ThreadedPostCommand(a, c, args, message) } if strings.HasPrefix(message, "url") { - return lt.UrlCommand(a, args, message) + return lt.UrlCommand(a, c, args, message) } if strings.HasPrefix(message, "json") { - return lt.JsonCommand(a, args, message) + return lt.JsonCommand(a, c, args, message) } return lt.HelpCommand(args, message), nil @@ -170,7 +171,7 @@ func (*LoadTestProvider) HelpCommand(args *model.CommandArgs, message string) *m return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { tokens := strings.Fields(strings.TrimPrefix(message, "setup")) doTeams := contains(tokens, "teams") doFuzz := contains(tokens, "fuzz") @@ -220,6 +221,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa } environment, err := CreateTestEnvironmentWithTeams( a, + c, client, utils.Range{Begin: numTeams, End: numTeams}, utils.Range{Begin: numChannels, End: numChannels}, @@ -243,6 +245,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa CreateTestEnvironmentInTeam( a, + c, client, team, utils.Range{Begin: numChannels, End: numChannels}, @@ -254,25 +257,25 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa return &model.CommandResponse{Text: "Created environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) ActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) ActivateUserCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { user_id := strings.TrimSpace(strings.TrimPrefix(message, "activate_user")) - if err := a.UpdateUserActive(user_id, true); err != nil { + if err := a.UpdateUserActive(c, user_id, true); err != nil { return &model.CommandResponse{Text: "Failed to activate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } return &model.CommandResponse{Text: "Activated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) DeActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) DeActivateUserCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { user_id := strings.TrimSpace(strings.TrimPrefix(message, "deactivate_user")) - if err := a.UpdateUserActive(user_id, false); err != nil { + if err := a.UpdateUserActive(c, user_id, false); err != nil { return &model.CommandResponse{Text: "Failed to deactivate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } return &model.CommandResponse{Text: "DeActivated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) UsersCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) UsersCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { cmd := strings.TrimSpace(strings.TrimPrefix(message, "users")) doFuzz := false @@ -294,14 +297,14 @@ func (*LoadTestProvider) UsersCommand(a *app.App, args *model.CommandArgs, messa client := model.NewAPIv4Client(args.SiteURL) userCreator := NewAutoUserCreator(a, client, team) userCreator.Fuzzy = doFuzz - if _, err := userCreator.CreateTestUsers(usersr); err != nil { + if _, err := userCreator.CreateTestUsers(c, usersr); err != nil { return &model.CommandResponse{Text: "Failed to add users: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) ChannelsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) ChannelsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels")) doFuzz := false @@ -322,14 +325,14 @@ func (*LoadTestProvider) ChannelsCommand(a *app.App, args *model.CommandArgs, me channelCreator := NewAutoChannelCreator(a, team, args.UserId) channelCreator.Fuzzy = doFuzz - if _, err := channelCreator.CreateTestChannels(channelsr); err != nil { + if _, err := channelCreator.CreateTestChannels(c, channelsr); err != nil { return &model.CommandResponse{Text: "Failed to create test channels: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) ThreadedPostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) ThreadedPostCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { var usernames []string options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000} if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil { @@ -344,18 +347,18 @@ func (*LoadTestProvider) ThreadedPostCommand(a *app.App, args *model.CommandArgs testPoster := NewAutoPostCreator(a, args.ChannelId, args.UserId) testPoster.Fuzzy = true testPoster.Users = usernames - rpost, err2 := testPoster.CreateRandomPost() + rpost, err2 := testPoster.CreateRandomPost(c) if err2 != nil { return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err2 } for i := 0; i < 1000; i++ { - testPoster.CreateRandomPostNested(rpost.Id, rpost.Id) + testPoster.CreateRandomPostNested(c, rpost.Id, rpost.Id) } return &model.CommandResponse{Text: "Added threaded post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) PostsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) PostsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts")) doFuzz := false @@ -396,7 +399,7 @@ func (*LoadTestProvider) PostsCommand(a *app.App, args *model.CommandArgs, messa numPosts := utils.RandIntFromRange(postsr) for i := 0; i < numPosts; i++ { testPoster.HasImage = (i < numImages) - _, err := testPoster.CreateRandomPost() + _, err := testPoster.CreateRandomPost(c) if err != nil { return &model.CommandResponse{Text: "Failed to add posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } @@ -457,7 +460,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "url")) if url == "" { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil @@ -503,7 +506,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message post.ChannelId = args.ChannelId post.UserId = args.UserId - if _, err := a.CreatePostMissingChannel(post, false); err != nil { + if _, err := a.CreatePostMissingChannel(c, post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } } @@ -511,7 +514,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil } -func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) { url := strings.TrimSpace(strings.TrimPrefix(message, "json")) if url == "" { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil @@ -549,7 +552,7 @@ func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, messag post.Message = message } - if _, err := a.CreatePostMissingChannel(post, false); err != nil { + if _, err := a.CreatePostMissingChannel(c, post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } diff --git a/app/slashcommands/command_logout.go b/app/slashcommands/command_logout.go index b41d00e4e1f..caeb0d019da 100644 --- a/app/slashcommands/command_logout.go +++ b/app/slashcommands/command_logout.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (*LogoutProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (*LogoutProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*LogoutProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { // Actual logout is handled client side. return &model.CommandResponse{GotoLocation: "/login"} } diff --git a/app/slashcommands/command_me.go b/app/slashcommands/command_me.go index 510b438ca9d..a1d597bfbf6 100644 --- a/app/slashcommands/command_me.go +++ b/app/slashcommands/command_me.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (*MeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command { } } -func (*MeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*MeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { return &model.CommandResponse{ ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Type: model.POST_ME, diff --git a/app/slashcommands/command_me_test.go b/app/slashcommands/command_me_test.go index 7afd422d249..71ebbed187e 100644 --- a/app/slashcommands/command_me_test.go +++ b/app/slashcommands/command_me_test.go @@ -19,7 +19,7 @@ func TestMeProviderDoCommand(t *testing.T) { msg := "hello" - resp := mp.DoCommand(th.App, &model.CommandArgs{}, msg) + resp := mp.DoCommand(th.App, th.Context, &model.CommandArgs{}, msg) assert.Equal(t, model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, resp.ResponseType) assert.Equal(t, model.POST_ME, resp.Type) diff --git a/app/slashcommands/command_msg.go b/app/slashcommands/command_msg.go index 046db8de053..5d90f57a82e 100644 --- a/app/slashcommands/command_msg.go +++ b/app/slashcommands/command_msg.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -39,7 +40,7 @@ func (*msgProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*msgProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { splitMessage := strings.SplitN(message, " ", 2) parsedMessage := "" @@ -82,7 +83,7 @@ func (*msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message strin } var directChannel *model.Channel - if directChannel, err = a.GetOrCreateDirectChannel(args.UserId, userProfile.Id); err != nil { + if directChannel, err = a.GetOrCreateDirectChannel(c, args.UserId, userProfile.Id); err != nil { mlog.Error(err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -100,7 +101,7 @@ func (*msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message strin post.Message = parsedMessage post.ChannelId = targetChannelId post.UserId = args.UserId - if _, err = a.CreatePostMissingChannel(post, true); err != nil { + if _, err = a.CreatePostMissingChannel(c, post, true); err != nil { return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } diff --git a/app/slashcommands/command_msg_test.go b/app/slashcommands/command_msg_test.go index defae6de585..175e26b66c3 100644 --- a/app/slashcommands/command_msg_test.go +++ b/app/slashcommands/command_msg_test.go @@ -23,7 +23,7 @@ func TestMsgProvider(t *testing.T) { th.removePermissionFromRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) // Check without permission to create a DM channel. - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -37,7 +37,7 @@ func TestMsgProvider(t *testing.T) { th.addPermissionToRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID) // Check with permission to create a DM channel. - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -48,7 +48,7 @@ func TestMsgProvider(t *testing.T) { assert.Equal(t, "http://test.url/"+team.Name+"/channels/"+channelName, resp.GotoLocation) // Check without permission to post to an existing DM channel. - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: team.Id, @@ -66,7 +66,7 @@ func TestMsgProvider(t *testing.T) { th.linkUserToTeam(guest, th.BasicTeam) th.addUserToChannel(guest, th.BasicChannel) - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: th.BasicTeam.Id, @@ -80,7 +80,7 @@ func TestMsgProvider(t *testing.T) { th.linkUserToTeam(user, th.BasicTeam) th.addUserToChannel(user, th.BasicChannel) - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), SiteURL: "http://test.url", TeamId: th.BasicTeam.Id, diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index 5ade3df5c3c..e15fe13d527 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -36,7 +37,7 @@ func (*MuteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*MuteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { var channel *model.Channel var noChannelErr *model.AppError diff --git a/app/slashcommands/command_mute_test.go b/app/slashcommands/command_mute_test.go index 6ef3afb83cb..f0b9b053cfa 100644 --- a/app/slashcommands/command_mute_test.go +++ b/app/slashcommands/command_mute_test.go @@ -34,7 +34,7 @@ func TestMuteCommandNoChannel(t *testing.T) { ) cmd := &MuteProvider{} - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), UserId: th.BasicUser.Id, }, "") @@ -53,7 +53,7 @@ func TestMuteCommandNoArgs(t *testing.T) { cmd := &MuteProvider{} // First mute the channel - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -62,7 +62,7 @@ func TestMuteCommandNoArgs(t *testing.T) { // Now unmute the channel time.Sleep(time.Millisecond) - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -80,7 +80,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { } channel1 := th.BasicChannel - channel2, _ := th.App.CreateChannel(&model.Channel{ + channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -95,7 +95,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { cmd := &MuteProvider{} // First mute the channel - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -105,7 +105,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) // Now unmute the channel - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -125,7 +125,7 @@ func TestMuteCommandNotMember(t *testing.T) { } channel1 := th.BasicChannel - channel2, _ := th.App.CreateChannel(&model.Channel{ + channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -136,7 +136,7 @@ func TestMuteCommandNotMember(t *testing.T) { cmd := &MuteProvider{} // First mute the channel - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -157,7 +157,7 @@ func TestMuteCommandNotChannel(t *testing.T) { cmd := &MuteProvider{} // First mute the channel - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel1.Id, UserId: th.BasicUser.Id, @@ -173,7 +173,7 @@ func TestMuteCommandDMChannel(t *testing.T) { t.SkipNow() } - channel2, _ := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + channel2, _ := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) channel2M, _ := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) @@ -181,7 +181,7 @@ func TestMuteCommandDMChannel(t *testing.T) { cmd := &MuteProvider{} // First mute the channel - resp := cmd.DoCommand(th.App, &model.CommandArgs{ + resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel2.Id, UserId: th.BasicUser.Id, @@ -192,7 +192,7 @@ func TestMuteCommandDMChannel(t *testing.T) { assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP]) // Now unmute the channel - resp = cmd.DoCommand(th.App, &model.CommandArgs{ + resp = cmd.DoCommand(th.App, th.Context, &model.CommandArgs{ T: i18n.IdentityTfunc(), ChannelId: channel2.Id, UserId: th.BasicUser.Id, diff --git a/app/slashcommands/command_offline.go b/app/slashcommands/command_offline.go index b97ebbc07f0..313e4dd7527 100644 --- a/app/slashcommands/command_offline.go +++ b/app/slashcommands/command_offline.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (*OfflineProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comm } } -func (*OfflineProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*OfflineProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusOffline(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")} diff --git a/app/slashcommands/command_online.go b/app/slashcommands/command_online.go index d60e003f821..c0797454ce0 100644 --- a/app/slashcommands/command_online.go +++ b/app/slashcommands/command_online.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -33,7 +34,7 @@ func (*OnlineProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } } -func (*OnlineProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*OnlineProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { a.SetStatusOnline(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")} diff --git a/app/slashcommands/command_remote.go b/app/slashcommands/command_remote.go index 99fd913afa1..646c59ee424 100644 --- a/app/slashcommands/command_remote.go +++ b/app/slashcommands/command_remote.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -68,7 +69,7 @@ func (rp *RemoteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Co } } -func (rp *RemoteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (rp *RemoteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !a.HasPermissionTo(args.UserId, model.PERMISSION_MANAGE_SECURE_CONNECTIONS) { return responsef(args.T("api.command_remote.permission_required", map[string]interface{}{"Permission": "manage_secure_connections"})) } diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index 45284aa2629..96a5cfb6fee 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -57,15 +58,15 @@ func (*KickProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command } } -func (*RemoveProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { - return doCommand(a, args, message) +func (*RemoveProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { + return doCommand(a, c, args, message) } -func (*KickProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { - return doCommand(a, args, message) +func (*KickProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { + return doCommand(a, c, args, message) } -func doCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{ @@ -134,7 +135,7 @@ func doCommand(a *app.App, args *model.CommandArgs, message string) *model.Comma } } - if err = a.RemoveUserFromChannel(userProfile.Id, args.UserId, channel); err != nil { + if err = a.RemoveUserFromChannel(c, userProfile.Id, args.UserId, channel); err != nil { var text string if err.Id == "api.channel.remove_members.denied" { text = args.T("api.command_remove.group_constrained_user_denied") diff --git a/app/slashcommands/command_remove_test.go b/app/slashcommands/command_remove_test.go index 1e8a68c19dc..862fa804c4f 100644 --- a/app/slashcommands/command_remove_test.go +++ b/app/slashcommands/command_remove_test.go @@ -17,7 +17,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { rp := RemoveProvider{} - publicChannel, _ := th.App.CreateChannel(&model.Channel{ + publicChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -25,7 +25,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { CreatorId: th.BasicUser.Id, }, false) - privateChannel, _ := th.App.CreateChannel(&model.Channel{ + privateChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "BB", Name: "aa" + model.NewId() + "a", Type: model.CHANNEL_OPEN, @@ -34,7 +34,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { }, false) targetUser := th.createUser() - th.App.AddUserToTeam(th.BasicTeam.Id, targetUser.Id, targetUser.Id) + th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, targetUser.Id, targetUser.Id) th.App.AddUserToChannel(targetUser, publicChannel, false) th.App.AddUserToChannel(targetUser, privateChannel, false) @@ -45,7 +45,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual := rp.DoCommand(th.App, args, targetUser.Username).Text + actual := rp.DoCommand(th.App, th.Context, args, targetUser.Username).Text assert.Equal(t, "api.command_remove.permission.app_error", actual) // Try a public channel *with* permission. @@ -56,7 +56,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, targetUser.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, targetUser.Username).Text assert.Equal(t, "", actual) // Try a private channel *without* permission. @@ -66,7 +66,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, targetUser.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, targetUser.Username).Text assert.Equal(t, "api.command_remove.permission.app_error", actual) // Try a private channel *with* permission. @@ -77,7 +77,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, targetUser.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, targetUser.Username).Text assert.Equal(t, "", actual) // Try a group channel @@ -92,7 +92,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, user1.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, user1.Username).Text assert.Equal(t, "api.command_remove.direct_group.app_error", actual) // Try a direct channel *with* being a member. @@ -104,14 +104,14 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, user1.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, user1.Username).Text assert.Equal(t, "api.command_remove.direct_group.app_error", actual) // Try a public channel with a deactivated user. deactivatedUser := th.createUser() - th.App.AddUserToTeam(th.BasicTeam.Id, deactivatedUser.Id, deactivatedUser.Id) + th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, deactivatedUser.Id, deactivatedUser.Id) th.App.AddUserToChannel(deactivatedUser, publicChannel, false) - th.App.UpdateActive(deactivatedUser, false) + th.App.UpdateActive(th.Context, deactivatedUser, false) args = &model.CommandArgs{ T: func(s string, args ...interface{}) string { return s }, @@ -119,6 +119,6 @@ func TestRemoveProviderDoCommand(t *testing.T) { UserId: th.BasicUser.Id, } - actual = rp.DoCommand(th.App, args, deactivatedUser.Username).Text + actual = rp.DoCommand(th.App, th.Context, args, deactivatedUser.Username).Text assert.Equal(t, "api.command_remove.missing.app_error", actual) } diff --git a/app/slashcommands/command_search.go b/app/slashcommands/command_search.go index a0892c7e8fb..174780e9827 100644 --- a/app/slashcommands/command_search.go +++ b/app/slashcommands/command_search.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (search *SearchProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *mode } } -func (search *SearchProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (search *SearchProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_search.unsupported.app_error"), diff --git a/app/slashcommands/command_settings.go b/app/slashcommands/command_settings.go index 814266f5e3e..80782a2be7e 100644 --- a/app/slashcommands/command_settings.go +++ b/app/slashcommands/command_settings.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (settings *SettingsProvider) GetCommand(a *app.App, T i18n.TranslateFunc) * } } -func (settings *SettingsProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (settings *SettingsProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_settings.unsupported.app_error"), diff --git a/app/slashcommands/command_share.go b/app/slashcommands/command_share.go index 29685a91ac3..204394eebd9 100644 --- a/app/slashcommands/command_share.go +++ b/app/slashcommands/command_share.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -119,7 +120,7 @@ func (sp *ShareProvider) getAutoCompleteUnInviteRemote(a *app.App, _ *model.Comm } } -func (sp *ShareProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { if !a.HasPermissionTo(args.UserId, model.PERMISSION_MANAGE_SHARED_CHANNELS) { return responsef(args.T("api.command_share.permission_required", map[string]interface{}{"Permission": "manage_shared_channels"})) } diff --git a/app/slashcommands/command_share_test.go b/app/slashcommands/command_share_test.go index c3787d5f731..43e7eaa969d 100644 --- a/app/slashcommands/command_share_test.go +++ b/app/slashcommands/command_share_test.go @@ -46,7 +46,7 @@ func TestShareProviderDoCommand(t *testing.T) { Command: "/share-channel share", } - response := commandProvider.DoCommand(th.App, args, "") + response := commandProvider.DoCommand(th.App, th.Context, args, "") require.Equal(t, "##### "+args.T("api.command_share.channel_shared"), response.Text) channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool { @@ -81,7 +81,7 @@ func TestShareProviderDoCommand(t *testing.T) { Command: "/share-channel unshare", } - response := commandProvider.DoCommand(th.App, args, "") + response := commandProvider.DoCommand(th.App, th.Context, args, "") require.Equal(t, "##### "+args.T("api.command_share.shared_channel_unavailable"), response.Text) channelConvertedMessages := testCluster.SelectMessages(func(msg *model.ClusterMessage) bool { diff --git a/app/slashcommands/command_shortcuts.go b/app/slashcommands/command_shortcuts.go index 07bcfe2d317..30fa1661d84 100644 --- a/app/slashcommands/command_shortcuts.go +++ b/app/slashcommands/command_shortcuts.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (*ShortcutsProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Co } } -func (*ShortcutsProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*ShortcutsProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_shortcuts.unsupported.app_error"), diff --git a/app/slashcommands/command_shrug.go b/app/slashcommands/command_shrug.go index 138308ff500..54a07ca9085 100644 --- a/app/slashcommands/command_shrug.go +++ b/app/slashcommands/command_shrug.go @@ -5,6 +5,7 @@ package slashcommands import ( "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" ) @@ -34,7 +35,7 @@ func (*ShrugProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comman } } -func (*ShrugProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { +func (*ShrugProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { rmsg := `¯\\\_(ツ)\_/¯` if message != "" { rmsg = message + " " + rmsg diff --git a/app/slashcommands/command_test.go b/app/slashcommands/command_test.go index b6080efe889..3fedcc43468 100644 --- a/app/slashcommands/command_test.go +++ b/app/slashcommands/command_test.go @@ -82,7 +82,7 @@ func TestCreateCommandPost(t *testing.T) { } skipSlackParsing := false - _, err := th.App.CreateCommandPost(post, th.BasicTeam.Id, resp, skipSlackParsing) + _, err := th.App.CreateCommandPost(th.Context, post, th.BasicTeam.Id, resp, skipSlackParsing) require.NotNil(t, err) require.Equal(t, err.Id, "api.context.invalid_param.app_error") } @@ -108,7 +108,7 @@ func TestExecuteCommand(t *testing.T) { UserId: th.BasicUser.Id, T: func(s string, args ...interface{}) string { return s }, } - resp, err := th.App.ExecuteCommand(args) + resp, err := th.App.ExecuteCommand(th.Context, args) require.Nil(t, err) require.NotNil(t, resp) @@ -121,7 +121,7 @@ func TestExecuteCommand(t *testing.T) { Command: "missing leading slash character", T: func(s string, args ...interface{}) string { return s }, } - _, err := th.App.ExecuteCommand(argsMissingSlashCharacter) + _, err := th.App.ExecuteCommand(th.Context, argsMissingSlashCharacter) require.Equal(t, "api.command.execute_command.format.app_error", err.Id) }) @@ -130,7 +130,7 @@ func TestExecuteCommand(t *testing.T) { Command: "", T: func(s string, args ...interface{}) string { return s }, } - _, err := th.App.ExecuteCommand(argsMissingSlashCharacter) + _, err := th.App.ExecuteCommand(th.Context, argsMissingSlashCharacter) require.Equal(t, "api.command.execute_command.format.app_error", err.Id) }) } @@ -157,7 +157,7 @@ func TestHandleCommandResponsePost(t *testing.T) { builtIn := true - post, err := th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err := th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, args.ChannelId, post.ChannelId) assert.Equal(t, args.RootId, post.RootId) @@ -172,7 +172,7 @@ func TestHandleCommandResponsePost(t *testing.T) { // Command is not built in, so it is a bot command. builtIn = false - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -183,7 +183,7 @@ func TestHandleCommandResponsePost(t *testing.T) { resp.ChannelId = channel.Id th.addUserToChannel(th.BasicUser, channel) - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, resp.ChannelId, post.ChannelId) assert.NotEqual(t, args.ChannelId, post.ChannelId) @@ -194,14 +194,14 @@ func TestHandleCommandResponsePost(t *testing.T) { command.Username = "Command username" resp.Username = "Response username" - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Nil(t, post.GetProp("override_username")) *th.App.Config().ServiceSettings.EnablePostUsernameOverride = true // Override username config is turned on. Override username through command property. - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, command.Username, post.GetProp("override_username")) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -209,7 +209,7 @@ func TestHandleCommandResponsePost(t *testing.T) { command.Username = "" // Override username through response property. - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, resp.Username, post.GetProp("override_username")) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -221,14 +221,14 @@ func TestHandleCommandResponsePost(t *testing.T) { command.IconURL = "Command icon url" resp.IconURL = "Response icon url" - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Nil(t, post.GetProp("override_icon_url")) *th.App.Config().ServiceSettings.EnablePostIconOverride = true // Override icon url config is turned on. Override icon url through command property. - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, command.IconURL, post.GetProp("override_icon_url")) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -236,7 +236,7 @@ func TestHandleCommandResponsePost(t *testing.T) { command.IconURL = "" // Override icon url through response property. - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, resp.IconURL, post.GetProp("override_icon_url")) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -244,7 +244,7 @@ func TestHandleCommandResponsePost(t *testing.T) { // Test Slack text conversion. resp.Text = "" - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, "@channel", post.Message) assert.Equal(t, "true", post.GetProp("from_webhook")) @@ -256,7 +256,7 @@ func TestHandleCommandResponsePost(t *testing.T) { }, } - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) assert.Nil(t, err) assert.Equal(t, "@channel", post.Message) if assert.Len(t, post.Attachments(), 1) { @@ -267,7 +267,7 @@ func TestHandleCommandResponsePost(t *testing.T) { channel = th.createPrivateChannel(th.BasicTeam) resp.ChannelId = channel.Id args.UserId = th.BasicUser2.Id - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) require.NotNil(t, err) require.Equal(t, err.Id, "api.command.command_post.forbidden.app_error") @@ -284,7 +284,7 @@ func TestHandleCommandResponsePost(t *testing.T) { // set and unset SkipSlackParsing here seems the nicest way as no separate response objects are created for every testcase. resp.SkipSlackParsing = true - post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn) + post, err = th.App.HandleCommandResponsePost(th.Context, command, args, resp, builtIn) resp.SkipSlackParsing = false assert.Nil(t, err) @@ -311,7 +311,7 @@ func TestHandleCommandResponse(t *testing.T) { builtIn := true - _, err := th.App.HandleCommandResponse(command, args, resp, builtIn) + _, err := th.App.HandleCommandResponse(th.Context, command, args, resp, builtIn) require.NotNil(t, err) require.Equal(t, err.Id, "api.command.execute_command.create_post_failed.app_error") @@ -319,7 +319,7 @@ func TestHandleCommandResponse(t *testing.T) { Text: "message 1", } - _, err = th.App.HandleCommandResponse(command, args, resp, builtIn) + _, err = th.App.HandleCommandResponse(th.Context, command, args, resp, builtIn) assert.Nil(t, err) resp = &model.CommandResponse{ @@ -335,7 +335,7 @@ func TestHandleCommandResponse(t *testing.T) { }, } - _, err = th.App.HandleCommandResponse(command, args, resp, builtIn) + _, err = th.App.HandleCommandResponse(th.Context, command, args, resp, builtIn) require.NotNil(t, err) require.Equal(t, err.Id, "api.command.execute_command.create_post_failed.app_error") @@ -346,7 +346,7 @@ func TestHandleCommandResponse(t *testing.T) { }, } - _, err = th.App.HandleCommandResponse(command, args, resp, builtIn) + _, err = th.App.HandleCommandResponse(th.Context, command, args, resp, builtIn) assert.Nil(t, err) } diff --git a/app/slashcommands/helper_test.go b/app/slashcommands/helper_test.go index 38dc6c86159..073743488eb 100644 --- a/app/slashcommands/helper_test.go +++ b/app/slashcommands/helper_test.go @@ -15,6 +15,7 @@ import ( "time" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -25,6 +26,7 @@ import ( type TestHelper struct { App *app.App + Context *request.Context Server *app.Server BasicTeam *model.Team BasicUser *model.User @@ -80,6 +82,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th := &TestHelper{ App: app.New(app.ServerConnector(s)), + Context: &request.Context{}, Server: s, LogBuffer: buffer, IncludeCacheLayer: includeCacheLayer, @@ -113,6 +116,8 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo if enterprise { th.App.Srv().SetLicense(model.NewTestLicense()) + th.App.Srv().Jobs.InitWorkers() + th.App.Srv().Jobs.InitSchedulers() } else { th.App.Srv().SetLicense(nil) } @@ -121,8 +126,6 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th.tempWorkspace = tempWorkspace } - th.App.InitServer() - return th } @@ -186,7 +189,7 @@ func (th *TestHelper) createTeam() *model.Team { utils.DisableDebugLogForTest() var err *model.AppError - if team, err = th.App.CreateTeam(team); err != nil { + if team, err = th.App.CreateTeam(th.Context, team); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -215,11 +218,11 @@ func (th *TestHelper) createUserOrGuest(guest bool) *model.User { utils.DisableDebugLogForTest() var err *model.AppError if guest { - if user, err = th.App.CreateGuest(user); err != nil { + if user, err = th.App.CreateGuest(th.Context, user); err != nil { panic(err) } } else { - if user, err = th.App.CreateUser(user); err != nil { + if user, err = th.App.CreateUser(th.Context, user); err != nil { panic(err) } } @@ -260,7 +263,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType string, option utils.DisableDebugLogForTest() var err *model.AppError - if channel, err = th.App.CreateChannel(channel, true); err != nil { + if channel, err = th.App.CreateChannel(th.Context, channel, true); err != nil { panic(err) } @@ -297,7 +300,7 @@ func (th *TestHelper) createChannelWithAnotherUser(team *model.Team, channelType utils.DisableDebugLogForTest() var err *model.AppError - if channel, err = th.App.CreateChannel(channel, true); err != nil { + if channel, err = th.App.CreateChannel(th.Context, channel, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -308,7 +311,7 @@ func (th *TestHelper) createDmChannel(user *model.User) *model.Channel { utils.DisableDebugLogForTest() var err *model.AppError var channel *model.Channel - if channel, err = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, user.Id); err != nil { + if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -338,7 +341,7 @@ func (th *TestHelper) createPost(channel *model.Channel) *model.Post { utils.DisableDebugLogForTest() var err *model.AppError - if post, err = th.App.CreatePost(post, channel, false, true); err != nil { + if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -348,7 +351,7 @@ func (th *TestHelper) createPost(channel *model.Channel) *model.Post { func (th *TestHelper) linkUserToTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - _, err := th.App.JoinUserToTeam(team, user, "") + _, err := th.App.JoinUserToTeam(th.Context, team, user, "") if err != nil { panic(err) } diff --git a/app/syncables.go b/app/syncables.go index b2fa0c81d00..4eaa72befd4 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) @@ -17,7 +18,7 @@ import ( // only that channel's members are created. If channelID is nil all channel memberships are created. // If includeRemovedMembers is true, then channel members who left or were removed from the channel will // be re-added; otherwise, they will not be re-added. -func (a *App) createDefaultChannelMemberships(since int64, channelID *string, includeRemovedMembers bool) error { +func (a *App) createDefaultChannelMemberships(c *request.Context, since int64, channelID *string, includeRemovedMembers bool) error { channelMembers, appErr := a.ChannelMembersToAdd(since, channelID, includeRemovedMembers) if appErr != nil { return appErr @@ -36,7 +37,7 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string, in // First add user to team if tmem == nil { - _, err = a.AddTeamMember(channel.TeamId, userChannel.UserID) + _, err = a.AddTeamMember(c, channel.TeamId, userChannel.UserID) if err != nil { if err.Id == "api.team.join_user_to_team.allowed_domains.app_error" { a.Log().Info("User not added to channel - the domain associated with the user is not in the list of allowed team domains", @@ -54,7 +55,7 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string, in ) } - _, err = a.AddChannelMember(userChannel.UserID, channel, ChannelMemberOpts{ + _, err = a.AddChannelMember(c, userChannel.UserID, channel, ChannelMemberOpts{ SkipTeamMemberIntegrityCheck: true, }) if err != nil { @@ -82,14 +83,14 @@ func (a *App) createDefaultChannelMemberships(since int64, channelID *string, in // only that team's members are created. If teamID is nil all team memberships are created. // If includeRemovedMembers is true, then team members who left or were removed from the team will // be re-added; otherwise, they will not be re-added. -func (a *App) createDefaultTeamMemberships(since int64, teamID *string, includeRemovedMembers bool) error { +func (a *App) createDefaultTeamMemberships(c *request.Context, since int64, teamID *string, includeRemovedMembers bool) error { teamMembers, appErr := a.TeamMembersToAdd(since, teamID, includeRemovedMembers) if appErr != nil { return appErr } for _, userTeam := range teamMembers { - _, err := a.AddTeamMember(userTeam.TeamID, userTeam.UserID) + _, err := a.AddTeamMember(c, userTeam.TeamID, userTeam.UserID) if err != nil { if err.Id == "api.team.join_user_to_team.allowed_domains.app_error" { a.Log().Info("User not added to team - the domain associated with the user is not in the list of allowed team domains", @@ -114,13 +115,13 @@ func (a *App) createDefaultTeamMemberships(since int64, teamID *string, includeR // are configured to sync with teams and channels for group members on or after the given timestamp. // If includeRemovedMembers is true, then members who left or were removed from a team/channel will // be re-added; otherwise, they will not be re-added. -func (a *App) CreateDefaultMemberships(since int64, includeRemovedMembers bool) error { - err := a.createDefaultTeamMemberships(since, nil, includeRemovedMembers) +func (a *App) CreateDefaultMemberships(c *request.Context, since int64, includeRemovedMembers bool) error { + err := a.createDefaultTeamMemberships(c, since, nil, includeRemovedMembers) if err != nil { return err } - err = a.createDefaultChannelMemberships(since, nil, includeRemovedMembers) + err = a.createDefaultChannelMemberships(c, since, nil, includeRemovedMembers) if err != nil { return err } @@ -130,13 +131,13 @@ func (a *App) CreateDefaultMemberships(since int64, includeRemovedMembers bool) // DeleteGroupConstrainedMemberships deletes team and channel memberships of users who aren't members of the allowed // groups of all group-constrained teams and channels. -func (a *App) DeleteGroupConstrainedMemberships() error { - err := a.deleteGroupConstrainedChannelMemberships(nil) +func (a *App) DeleteGroupConstrainedMemberships(c *request.Context) error { + err := a.deleteGroupConstrainedChannelMemberships(c, nil) if err != nil { return err } - err = a.deleteGroupConstrainedTeamMemberships(nil) + err = a.deleteGroupConstrainedTeamMemberships(c, nil) if err != nil { return err } @@ -147,14 +148,14 @@ func (a *App) DeleteGroupConstrainedMemberships() error { // deleteGroupConstrainedTeamMemberships deletes team memberships of users who aren't members of the allowed // groups of the given group-constrained team. If a teamID is given then the procedure is scoped to the given team, // if teamID is nil then the procedure affects all teams. -func (a *App) deleteGroupConstrainedTeamMemberships(teamID *string) error { +func (a *App) deleteGroupConstrainedTeamMemberships(c *request.Context, teamID *string) error { teamMembers, appErr := a.TeamMembersToRemove(teamID) if appErr != nil { return appErr } for _, userTeam := range teamMembers { - err := a.RemoveUserFromTeam(userTeam.TeamId, userTeam.UserId, "") + err := a.RemoveUserFromTeam(c, userTeam.TeamId, userTeam.UserId, "") if err != nil { return err } @@ -171,7 +172,7 @@ func (a *App) deleteGroupConstrainedTeamMemberships(teamID *string) error { // deleteGroupConstrainedChannelMemberships deletes channel memberships of users who aren't members of the allowed // groups of the given group-constrained channel. If a channelID is given then the procedure is scoped to the given team, // if channelID is nil then the procedure affects all teams. -func (a *App) deleteGroupConstrainedChannelMemberships(channelID *string) error { +func (a *App) deleteGroupConstrainedChannelMemberships(c *request.Context, channelID *string) error { channelMembers, appErr := a.ChannelMembersToRemove(channelID) if appErr != nil { return appErr @@ -183,7 +184,7 @@ func (a *App) deleteGroupConstrainedChannelMemberships(channelID *string) error return err } - err = a.RemoveUserFromChannel(userChannel.UserId, "", channel) + err = a.RemoveUserFromChannel(c, userChannel.UserId, "", channel) if err != nil { return err } @@ -232,7 +233,7 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca // SyncRolesAndMembership updates the SchemeAdmin status and membership of all of the members of the given // syncable. -func (a *App) SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { +func (a *App) SyncRolesAndMembership(c *request.Context, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { a.SyncSyncableRoles(syncableID, syncableType) lastJob, _ := a.Srv().Store.Job().GetNewestJobByStatusAndType(model.JOB_STATUS_SUCCESS, model.JOB_TYPE_LDAP_SYNC) @@ -243,12 +244,12 @@ func (a *App) SyncRolesAndMembership(syncableID string, syncableType model.Group switch syncableType { case model.GroupSyncableTypeTeam: - a.createDefaultTeamMemberships(since, &syncableID, includeRemovedMembers) - a.deleteGroupConstrainedTeamMemberships(&syncableID) + a.createDefaultTeamMemberships(c, since, &syncableID, includeRemovedMembers) + a.deleteGroupConstrainedTeamMemberships(c, &syncableID) a.ClearTeamMembersCache(syncableID) case model.GroupSyncableTypeChannel: - a.createDefaultChannelMemberships(since, &syncableID, includeRemovedMembers) - a.deleteGroupConstrainedChannelMemberships(&syncableID) + a.createDefaultChannelMemberships(c, since, &syncableID, includeRemovedMembers) + a.deleteGroupConstrainedChannelMemberships(c, &syncableID) a.ClearChannelMembersCache(syncableID) } } diff --git a/app/syncables_test.go b/app/syncables_test.go index ff723bc3678..623fde77079 100644 --- a/app/syncables_test.go +++ b/app/syncables_test.go @@ -16,7 +16,7 @@ func TestCreateDefaultMemberships(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - singersTeam, err := th.App.CreateTeam(&model.Team{ + singersTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "Singers", Name: "zz" + model.NewId(), Email: "singers@test.com", @@ -26,7 +26,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("test team not created: %s", err.Error()) } - nerdsTeam, err := th.App.CreateTeam(&model.Team{ + nerdsTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "Nerds", Name: "zz" + model.NewId(), Email: "nerds@test.com", @@ -36,7 +36,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("test team not created: %s", err.Error()) } - practiceChannel, err := th.App.CreateChannel(&model.Channel{ + practiceChannel, err := th.App.CreateChannel(th.Context, &model.Channel{ TeamId: singersTeam.Id, DisplayName: "Practices", Name: model.NewId(), @@ -46,7 +46,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("test channel not created: %s", err.Error()) } - experimentsChannel, err := th.App.CreateChannel(&model.Channel{ + experimentsChannel, err := th.App.CreateChannel(th.Context, &model.Channel{ TeamId: singersTeam.Id, DisplayName: "Experiments", Name: model.NewId(), @@ -104,7 +104,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("test groupmember not created: %s", err.Error()) } - pErr := th.App.CreateDefaultMemberships(0, false) + pErr := th.App.CreateDefaultMemberships(th.Context, 0, false) if pErr != nil { t.Errorf("faild to populate syncables: %s", pErr.Error()) } @@ -174,7 +174,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Sync everything after syncable was created (proving that team updates trigger re-sync) - pErr = th.App.CreateDefaultMemberships(scientistGroupMember.CreateAt+1, false) + pErr = th.App.CreateDefaultMemberships(th.Context, scientistGroupMember.CreateAt+1, false) if pErr != nil { t.Errorf("faild to populate syncables: %s", pErr.Error()) } @@ -217,7 +217,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Sync everything after syncable was created (proving that channel updates trigger re-sync) - pErr = th.App.CreateDefaultMemberships(scientistGroupMember.CreateAt+1, false) + pErr = th.App.CreateDefaultMemberships(th.Context, scientistGroupMember.CreateAt+1, false) if pErr != nil { t.Errorf("faild to populate syncables: %s", pErr.Error()) } @@ -232,17 +232,17 @@ func TestCreateDefaultMemberships(t *testing.T) { } // singer leaves team and channel - err = th.App.LeaveChannel(practiceChannel.Id, singer1.Id) + err = th.App.LeaveChannel(th.Context, practiceChannel.Id, singer1.Id) if err != nil { t.Errorf("error leaving channel: %s", err.Error()) } - err = th.App.LeaveTeam(singersTeam, singer1, "") + err = th.App.LeaveTeam(th.Context, singersTeam, singer1, "") if err != nil { t.Errorf("error leaving team: %s", err.Error()) } // Even re-syncing from the beginning doesn't re-add to channel or team - pErr = th.App.CreateDefaultMemberships(0, false) + pErr = th.App.CreateDefaultMemberships(th.Context, 0, false) if pErr != nil { t.Errorf("faild to populate syncables: %s", pErr.Error()) } @@ -262,17 +262,17 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Ensure members are in channel - _, err = th.App.AddChannelMember(scientist1.Id, experimentsChannel, ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, scientist1.Id, experimentsChannel, ChannelMemberOpts{}) if err != nil { t.Errorf("unable to add user to channel: %s", err.Error()) } // Add other user so that user can leave channel - _, err = th.App.AddTeamMember(singersTeam.Id, singer1.Id) + _, err = th.App.AddTeamMember(th.Context, singersTeam.Id, singer1.Id) if err != nil { t.Errorf("unable to add user to team: %s", err.Error()) } - _, err = th.App.AddChannelMember(singer1.Id, experimentsChannel, ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, singer1.Id, experimentsChannel, ChannelMemberOpts{}) if err != nil { t.Errorf("unable to add user to channel: %s", err.Error()) } @@ -283,7 +283,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("error updating group syncable: %s", err.Error()) } - pErr = th.App.CreateDefaultMemberships(0, false) + pErr = th.App.CreateDefaultMemberships(th.Context, 0, false) if pErr != nil { t.Errorf("faild to populate syncables: %s", pErr.Error()) } @@ -291,7 +291,7 @@ func TestCreateDefaultMemberships(t *testing.T) { timeBeforeLeaving := model.GetMillis() // User leaves channel - err = th.App.LeaveChannel(experimentsChannel.Id, scientist1.Id) + err = th.App.LeaveChannel(th.Context, experimentsChannel.Id, scientist1.Id) if err != nil { t.Errorf("unable to add user to channel: %s", err.Error()) } @@ -304,7 +304,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("error permanently deleting channelmemberhistory: %s", nErr.Error()) } - pErr = th.App.CreateDefaultMemberships(scienceChannelGroupSyncable.UpdateAt, false) + pErr = th.App.CreateDefaultMemberships(th.Context, scienceChannelGroupSyncable.UpdateAt, false) if pErr != nil { t.Errorf("failed to populate syncables: %s", pErr.Error()) } @@ -320,7 +320,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("error permanently deleting channelmemberhistory: %s", nErr.Error()) } - pErr = th.App.CreateDefaultMemberships(scienceChannelGroupSyncable.UpdateAt, false) + pErr = th.App.CreateDefaultMemberships(th.Context, scienceChannelGroupSyncable.UpdateAt, false) if pErr != nil { t.Errorf("failed to populate syncables: %s", pErr.Error()) } @@ -339,7 +339,7 @@ func TestCreateDefaultMemberships(t *testing.T) { _, err = th.App.UpsertGroupMember(scienceGroup.Id, restrictedUser.Id) require.Nil(t, err) - restrictedTeam, err := th.App.CreateTeam(&model.Team{ + restrictedTeam, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "Restricted", Name: "restricted" + model.NewId(), Email: "restricted@mattermost.org", @@ -350,7 +350,7 @@ func TestCreateDefaultMemberships(t *testing.T) { _, err = th.App.UpsertGroupSyncable(model.NewGroupTeam(scienceGroup.Id, restrictedTeam.Id, true)) require.Nil(t, err) - restrictedChannel, err := th.App.CreateChannel(&model.Channel{ + restrictedChannel, err := th.App.CreateChannel(th.Context, &model.Channel{ TeamId: restrictedTeam.Id, DisplayName: "Restricted", Name: "restricted" + model.NewId(), @@ -360,7 +360,7 @@ func TestCreateDefaultMemberships(t *testing.T) { _, err = th.App.UpsertGroupSyncable(model.NewGroupChannel(scienceGroup.Id, restrictedChannel.Id, true)) require.Nil(t, err) - pErr = th.App.CreateDefaultMemberships(0, false) + pErr = th.App.CreateDefaultMemberships(th.Context, 0, false) require.NoError(t, pErr) // Ensure only the restricted user was added to both the team and channel @@ -385,10 +385,10 @@ func TestDeleteGroupMemberships(t *testing.T) { var err *model.AppError // add users to teams and channels for _, userID := range userIDs { - _, err = th.App.AddTeamMember(th.BasicTeam.Id, userID) + _, err = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, userID) require.Nil(t, err) - _, err = th.App.AddChannelMember(userID, th.BasicChannel, ChannelMemberOpts{}) + _, err = th.App.AddChannelMember(th.Context, userID, th.BasicChannel, ChannelMemberOpts{}) require.Nil(t, err) } @@ -426,7 +426,7 @@ func TestDeleteGroupMemberships(t *testing.T) { require.Nil(t, err) // run the delete - appErr := th.App.DeleteGroupConstrainedMemberships() + appErr := th.App.DeleteGroupConstrainedMemberships(th.Context) require.NoError(t, appErr) // verify the new member counts @@ -475,7 +475,7 @@ func TestSyncSyncableRoles(t *testing.T) { require.Nil(t, err) var tm *model.TeamMember - tm, err = th.App.AddTeamMember(team.Id, user.Id) + tm, err = th.App.AddTeamMember(th.Context, team.Id, user.Id) require.Nil(t, err) require.False(t, tm.SchemeAdmin) diff --git a/app/team.go b/app/team.go index 9740fa27148..794a324bc5c 100644 --- a/app/team.go +++ b/app/team.go @@ -18,6 +18,7 @@ import ( "github.com/disintegration/imaging" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -26,7 +27,7 @@ import ( "github.com/mattermost/mattermost-server/v5/store/sqlstore" ) -func (a *App) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { +func (a *App) CreateTeam(c *request.Context, team *model.Team) (*model.Team, *model.AppError) { team.InviteId = "" rteam, err := a.Srv().Store.Team().Save(team) if err != nil { @@ -42,14 +43,14 @@ func (a *App) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { } } - if _, err := a.CreateDefaultChannels(rteam.Id); err != nil { + if _, err := a.CreateDefaultChannels(c, rteam.Id); err != nil { return nil, err } return rteam, nil } -func (a *App) CreateTeamWithUser(team *model.Team, userID string) (*model.Team, *model.AppError) { +func (a *App) CreateTeamWithUser(c *request.Context, team *model.Team, userID string) (*model.Team, *model.AppError) { user, err := a.GetUser(userID) if err != nil { return nil, err @@ -60,12 +61,12 @@ func (a *App) CreateTeamWithUser(team *model.Team, userID string) (*model.Team, return nil, model.NewAppError("isTeamEmailAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "", http.StatusBadRequest) } - rteam, err := a.CreateTeam(team) + rteam, err := a.CreateTeam(c, team) if err != nil { return nil, err } - if _, err := a.JoinUserToTeam(rteam, user, ""); err != nil { + if _, err := a.JoinUserToTeam(c, rteam, user, ""); err != nil { return nil, err } @@ -482,7 +483,7 @@ func (a *App) sendUpdatedMemberRoleEvent(userID string, member *model.TeamMember a.Publish(message) } -func (a *App) AddUserToTeam(teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *App) AddUserToTeam(c *request.Context, teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { team, err := a.Srv().Store.Team().Get(teamID) @@ -521,7 +522,7 @@ func (a *App) AddUserToTeam(teamID string, userID string, userRequestorId string } user := result.Data.(*model.User) - teamMember, err := a.JoinUserToTeam(team, user, userRequestorId) + teamMember, err := a.JoinUserToTeam(c, team, user, userRequestorId) if err != nil { return nil, nil, err } @@ -529,7 +530,7 @@ func (a *App) AddUserToTeam(teamID string, userID string, userRequestorId string return team, teamMember, nil } -func (a *App) AddUserToTeamByTeamId(teamID string, user *model.User) *model.AppError { +func (a *App) AddUserToTeamByTeamId(c *request.Context, teamID string, user *model.User) *model.AppError { team, err := a.Srv().Store.Team().Get(teamID) if err != nil { var nfErr *store.ErrNotFound @@ -541,13 +542,13 @@ func (a *App) AddUserToTeamByTeamId(teamID string, user *model.User) *model.AppE } } - if _, err := a.JoinUserToTeam(team, user, ""); err != nil { + if _, err := a.JoinUserToTeam(c, team, user, ""); err != nil { return err } return nil } -func (a *App) AddUserToTeamByToken(userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) { token, err := a.Srv().Store.Token().GetByToken(tokenID) if err != nil { return nil, nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, err.Error(), http.StatusBadRequest) @@ -613,7 +614,7 @@ func (a *App) AddUserToTeamByToken(userID string, tokenID string) (*model.Team, return nil, nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.invalid_invitation_type.app_error", nil, "", http.StatusBadRequest) } - teamMember, appErr := a.JoinUserToTeam(team, user, "") + teamMember, appErr := a.JoinUserToTeam(c, team, user, "") if appErr != nil { return nil, nil, appErr } @@ -639,7 +640,7 @@ func (a *App) AddUserToTeamByToken(userID string, tokenID string) (*model.Team, return team, teamMember, nil } -func (a *App) AddUserToTeamByInviteId(inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) { +func (a *App) AddUserToTeamByInviteId(c *request.Context, inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { team, err := a.Srv().Store.Team().GetByInviteId(inviteId) @@ -678,7 +679,7 @@ func (a *App) AddUserToTeamByInviteId(inviteId string, userID string) (*model.Te } user := result.Data.(*model.User) - teamMember, err := a.JoinUserToTeam(team, user, "") + teamMember, err := a.JoinUserToTeam(c, team, user, "") if err != nil { return nil, nil, err } @@ -761,7 +762,7 @@ func (a *App) joinUserToTeam(team *model.Team, user *model.User) (*model.TeamMem return member, false, nil } -func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) { +func (a *App) JoinUserToTeam(c *request.Context, team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) { if !a.isTeamEmailAllowed(user, team) { return nil, model.NewAppError("JoinUserToTeam", "api.team.join_user_to_team.allowed_domains.app_error", nil, "", http.StatusBadRequest) } @@ -780,7 +781,7 @@ func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId } a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasJoinedTeam(pluginContext, teamMember, actor) return true @@ -805,7 +806,7 @@ func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId if !user.IsGuest() { // Soft error if there is an issue joining the default channels - if err := a.JoinDefaultChannels(team.Id, user, shouldBeAdmin, userRequestorId); err != nil { + if err := a.JoinDefaultChannels(c, team.Id, user, shouldBeAdmin, userRequestorId); err != nil { mlog.Warn( "Encountered an issue joining default channels.", mlog.String("user_id", user.Id), @@ -1015,8 +1016,8 @@ func (a *App) GetTeamMembersByIds(teamID string, userIDs []string, restrictions return teamMembers, nil } -func (a *App) AddTeamMember(teamID, userID string) (*model.TeamMember, *model.AppError) { - _, teamMember, err := a.AddUserToTeam(teamID, userID, "") +func (a *App) AddTeamMember(c *request.Context, teamID, userID string) (*model.TeamMember, *model.AppError) { + _, teamMember, err := a.AddUserToTeam(c, teamID, userID, "") if err != nil { return nil, err } @@ -1029,11 +1030,11 @@ func (a *App) AddTeamMember(teamID, userID string) (*model.TeamMember, *model.Ap return teamMember, nil } -func (a *App) AddTeamMembers(teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) { +func (a *App) AddTeamMembers(c *request.Context, teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError) { var membersWithErrors []*model.TeamMemberWithError for _, userID := range userIDs { - _, teamMember, err := a.AddUserToTeam(teamID, userID, userRequestorId) + _, teamMember, err := a.AddUserToTeam(c, teamID, userID, userRequestorId) if err != nil { if graceful { membersWithErrors = append(membersWithErrors, &model.TeamMemberWithError{ @@ -1059,8 +1060,8 @@ func (a *App) AddTeamMembers(teamID string, userIDs []string, userRequestorId st return membersWithErrors, nil } -func (a *App) AddTeamMemberByToken(userID, tokenID string) (*model.TeamMember, *model.AppError) { - _, teamMember, err := a.AddUserToTeamByToken(userID, tokenID) +func (a *App) AddTeamMemberByToken(c *request.Context, userID, tokenID string) (*model.TeamMember, *model.AppError) { + _, teamMember, err := a.AddUserToTeamByToken(c, userID, tokenID) if err != nil { return nil, err } @@ -1068,8 +1069,8 @@ func (a *App) AddTeamMemberByToken(userID, tokenID string) (*model.TeamMember, * return teamMember, nil } -func (a *App) AddTeamMemberByInviteId(inviteId, userID string) (*model.TeamMember, *model.AppError) { - team, teamMember, err := a.AddUserToTeamByInviteId(inviteId, userID) +func (a *App) AddTeamMemberByInviteId(c *request.Context, inviteId, userID string) (*model.TeamMember, *model.AppError) { + team, teamMember, err := a.AddUserToTeamByInviteId(c, inviteId, userID) if err != nil { return nil, err } @@ -1108,7 +1109,7 @@ func (a *App) GetTeamUnread(teamID, userID string) (*model.TeamUnread, *model.Ap return teamUnread, nil } -func (a *App) RemoveUserFromTeam(teamID string, userID string, requestorId string) *model.AppError { +func (a *App) RemoveUserFromTeam(c *request.Context, teamID string, userID string, requestorId string) *model.AppError { tchan := make(chan store.StoreResult, 1) go func() { team, err := a.Srv().Store.Team().Get(teamID) @@ -1147,14 +1148,14 @@ func (a *App) RemoveUserFromTeam(teamID string, userID string, requestorId strin } user := result.Data.(*model.User) - if err := a.LeaveTeam(team, user, requestorId); err != nil { + if err := a.LeaveTeam(c, team, user, requestorId); err != nil { return err } return nil } -func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId string) *model.AppError { +func (a *App) RemoveTeamMemberFromTeam(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError { // Send the websocket message before we actually do the remove so the user being removed gets it. message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LEAVE_TEAM, teamMember.TeamId, "", "", nil) message.Add("user_id", teamMember.UserId) @@ -1192,7 +1193,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId } a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasLeftTeam(pluginContext, teamMember, actor) return true @@ -1220,7 +1221,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId return nil } -func (a *App) LeaveTeam(team *model.Team, user *model.User, requestorId string) *model.AppError { +func (a *App) LeaveTeam(c *request.Context, team *model.Team, user *model.User, requestorId string) *model.AppError { teamMember, err := a.GetTeamMember(team.Id, user.Id) if err != nil { return model.NewAppError("LeaveTeam", "api.team.remove_user_from_team.missing.app_error", nil, err.Error(), http.StatusBadRequest) @@ -1260,24 +1261,24 @@ func (a *App) LeaveTeam(team *model.Team, user *model.User, requestorId string) if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { if requestorId == user.Id { - if err = a.postLeaveTeamMessage(user, channel); err != nil { + if err = a.postLeaveTeamMessage(c, user, channel); err != nil { mlog.Warn("Failed to post join/leave message", mlog.Err(err)) } } else { - if err = a.postRemoveFromTeamMessage(user, channel); err != nil { + if err = a.postRemoveFromTeamMessage(c, user, channel); err != nil { mlog.Warn("Failed to post join/leave message", mlog.Err(err)) } } } - if err := a.RemoveTeamMemberFromTeam(teamMember, requestorId); err != nil { + if err := a.RemoveTeamMemberFromTeam(c, teamMember, requestorId); err != nil { return err } return nil } -func (a *App) postLeaveTeamMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postLeaveTeamMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.leave.left"), user.Username), @@ -1288,14 +1289,14 @@ func (a *App) postLeaveTeamMessage(user *model.User, channel *model.Channel) *mo }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postRemoveFromChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func (a *App) postRemoveFromTeamMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postRemoveFromTeamMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.remove_user_from_team.removed"), user.Username), @@ -1306,7 +1307,7 @@ func (a *App) postRemoveFromTeamMessage(user *model.User, channel *model.Channel }, } - if _, err := a.CreatePost(post, channel, false, true); err != nil { + if _, err := a.CreatePost(c, post, channel, false, true); err != nil { return model.NewAppError("postRemoveFromTeamMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/team_test.go b/app/team_test.go index a6302ecc0d4..a8112f527c2 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -30,10 +30,10 @@ func TestCreateTeam(t *testing.T) { Type: model.TEAM_OPEN, } - _, err := th.App.CreateTeam(team) + _, err := th.App.CreateTeam(th.Context, team) require.Nil(t, err, "Should create a new team") - _, err = th.App.CreateTeam(th.BasicTeam) + _, err = th.App.CreateTeam(th.Context, th.BasicTeam) require.NotNil(t, err, "Should not create a new team - team already exist") } @@ -49,10 +49,10 @@ func TestCreateTeamWithUser(t *testing.T) { Type: model.TEAM_OPEN, } - _, err := th.App.CreateTeamWithUser(team, th.BasicUser.Id) + _, err := th.App.CreateTeamWithUser(th.Context, team, th.BasicUser.Id) require.Nil(t, err, "Should create a new team with existing user") - _, err = th.App.CreateTeamWithUser(team, model.NewId()) + _, err = th.App.CreateTeamWithUser(th.Context, team, model.NewId()) require.NotNil(t, err, "Should not create a new team - user does not exist") } @@ -73,10 +73,10 @@ func TestAddUserToTeam(t *testing.T) { t.Run("add user", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err, "Should add user to the team") }) @@ -86,10 +86,10 @@ func TestAddUserToTeam(t *testing.T) { require.Nil(t, err, "Should update the team") user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err, "Should have allowed whitelisted user") }) @@ -99,31 +99,31 @@ func TestAddUserToTeam(t *testing.T) { require.Nil(t, err, "Should update the team") user := model.User{Email: strings.ToLower(model.NewId()) + "test@invalid.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, err := th.App.CreateUser(&user) + ruser, err := th.App.CreateUser(th.Context, &user) require.Nil(t, err, "Error creating user: %s", err) - defer th.App.PermanentDeleteUser(&user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.NotNil(t, err, "Should not add restricted user") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") user = model.User{Email: strings.ToLower(model.NewId()) + "test@invalid.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), AuthService: "notnil", AuthData: model.NewString("notnil")} - ruser, err = th.App.CreateUser(&user) + ruser, err = th.App.CreateUser(th.Context, &user) require.Nil(t, err, "Error creating authservice user: %s", err) - defer th.App.PermanentDeleteUser(&user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.NotNil(t, err, "Should not add authservice user") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "somebot", Description: "a bot", OwnerId: th.BasicUser.Id, }) require.Nil(t, err) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, bot.UserId, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, bot.UserId, "") assert.Nil(t, err, "should be able to add bot to domain restricted team") }) @@ -133,10 +133,10 @@ func TestAddUserToTeam(t *testing.T) { require.Nil(t, err, "Should update the team") user := model.User{Email: strings.ToLower(model.NewId()) + "test@invalid.example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.NotNil(t, err, "Should not add restricted user") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") }) @@ -147,25 +147,25 @@ func TestAddUserToTeam(t *testing.T) { require.Nil(t, err, "Should update the team") user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@foo.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser1, _ := th.App.CreateUser(&user1) + ruser1, _ := th.App.CreateUser(th.Context, &user1) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@bar.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser2, _ := th.App.CreateUser(&user2) + ruser2, _ := th.App.CreateUser(th.Context, &user2) user3 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@invalid.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser3, _ := th.App.CreateUser(&user3) + ruser3, _ := th.App.CreateUser(th.Context, &user3) - defer th.App.PermanentDeleteUser(&user1) - defer th.App.PermanentDeleteUser(&user2) - defer th.App.PermanentDeleteUser(&user3) + defer th.App.PermanentDeleteUser(th.Context, &user1) + defer th.App.PermanentDeleteUser(th.Context, &user2) + defer th.App.PermanentDeleteUser(th.Context, &user3) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser1.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser1.Id, "") require.Nil(t, err, "Should have allowed whitelisted user1") - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser2.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser2.Id, "") require.Nil(t, err, "Should have allowed whitelisted user2") - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser3.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser3.Id, "") require.NotNil(t, err, "Should not have allowed restricted user3") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") }) @@ -174,7 +174,7 @@ func TestAddUserToTeam(t *testing.T) { user := th.CreateUser() team := th.CreateTeam() - _, _, err := th.App.AddUserToTeam(team.Id, user.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, team.Id, user.Id, "") require.Nil(t, err) res, err := th.App.GetSidebarCategories(user.Id, team.Id) @@ -191,11 +191,11 @@ func TestAddUserToTeamByToken(t *testing.T) { defer th.TearDown() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) rguest := th.CreateGuest() t.Run("invalid token", func(t *testing.T) { - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, "123") + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, "123") require.NotNil(t, err, "Should fail on unexisting token") }) @@ -208,7 +208,7 @@ func TestAddUserToTeamByToken(t *testing.T) { require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should fail on bad token type") }) @@ -222,7 +222,7 @@ func TestAddUserToTeamByToken(t *testing.T) { require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should fail on expired token") }) @@ -234,7 +234,7 @@ func TestAddUserToTeamByToken(t *testing.T) { require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should fail on bad team id") }) @@ -246,7 +246,7 @@ func TestAddUserToTeamByToken(t *testing.T) { require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, _, err := th.App.AddUserToTeamByToken(model.NewId(), token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, model.NewId(), token.Token) require.NotNil(t, err, "Should fail on bad user id") }) @@ -256,7 +256,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.Nil(t, err, "Should add user to the team") _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) @@ -273,7 +273,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) assert.NotNil(t, err) }) @@ -283,7 +283,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) assert.NotNil(t, err) }) @@ -298,7 +298,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.NotNil(t, err) assert.Equal(t, "api.team.join_user_to_team.allowed_domains.app_error", err.Id) }) @@ -319,7 +319,7 @@ func TestAddUserToTeamByToken(t *testing.T) { th.App.InvalidateCacheForUser(rguest.Id) require.NoError(t, err) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, appErr := th.App.AddUserToTeamByToken(rguest.Id, token.Token) + _, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, appErr) rguest.Email = guestEmail _, err = th.App.Srv().Store.User().Update(rguest, false) @@ -342,7 +342,7 @@ func TestAddUserToTeamByToken(t *testing.T) { _, err = th.App.Srv().Store.User().Update(rguest, false) require.NoError(t, err) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, appErr := th.App.AddUserToTeamByToken(rguest.Id, token.Token) + _, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, appErr) th.BasicTeam.AllowedDomains = "" _, err = th.Server.Store.Team().Update(th.BasicTeam) @@ -356,7 +356,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(rguest.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, err, "Should add user to the team") _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) @@ -379,7 +379,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err = th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err = th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should return an error when trying to join a group-constrained team.") require.Equal(t, "app.team.invite_token.group_constrained.error", err.Id) @@ -394,8 +394,8 @@ func TestAddUserToTeamByToken(t *testing.T) { require.Nil(t, err, "Should update the team") user := model.User{Email: strings.ToLower(model.NewId()) + "test@invalid.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) token := model.NewToken( TokenTypeTeamInvitation, @@ -403,7 +403,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err = th.App.AddUserToTeamByToken(ruser.Id, token.Token) + _, _, err = th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should not add restricted user") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") }) @@ -418,7 +418,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - _, _, err := th.App.AddUserToTeamByToken(user.Id, token.Token) + _, _, err := th.App.AddUserToTeamByToken(th.Context, user.Id, token.Token) require.Nil(t, err) res, err := th.App.GetSidebarCategories(user.Id, team.Id) @@ -436,9 +436,9 @@ func TestAddUserToTeamByTeamId(t *testing.T) { t.Run("add user", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) - err := th.App.AddUserToTeamByTeamId(th.BasicTeam.Id, ruser) + err := th.App.AddUserToTeamByTeamId(th.Context, th.BasicTeam.Id, ruser) require.Nil(t, err, "Should add user to the team") }) @@ -448,10 +448,10 @@ func TestAddUserToTeamByTeamId(t *testing.T) { require.Nil(t, err, "Should update the team") user := model.User{Email: strings.ToLower(model.NewId()) + "test@invalid.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) - err = th.App.AddUserToTeamByTeamId(th.BasicTeam.Id, ruser) + err = th.App.AddUserToTeamByTeamId(th.Context, th.BasicTeam.Id, ruser) require.NotNil(t, err, "Should not add restricted user") require.Equal(t, "JoinUserToTeam", err.Where, "Error should be JoinUserToTeam") }) @@ -462,7 +462,7 @@ func TestPermanentDeleteTeam(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - team, err := th.App.CreateTeam(&model.Team{ + team, err := th.App.CreateTeam(th.Context, &model.Team{ DisplayName: "deletion-test", Name: "deletion-test", Email: "foo@foo.com", @@ -724,7 +724,7 @@ func TestJoinUserToTeam(t *testing.T) { Type: model.TEAM_OPEN, } - _, err := th.App.CreateTeam(team) + _, err := th.App.CreateTeam(th.Context, team) require.Nil(t, err, "Should create a new team") maxUsersPerTeam := th.App.Config().TeamSettings.MaxUsersPerTeam @@ -737,8 +737,8 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("new join", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) var alreadyAdded bool _, alreadyAdded, err = th.App.joinUserToTeam(team, ruser) @@ -748,8 +748,8 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("join when you are a member", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) th.App.joinUserToTeam(team, ruser) @@ -761,11 +761,11 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("re-join after leaving", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) - defer th.App.PermanentDeleteUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) + defer th.App.PermanentDeleteUser(th.Context, &user) th.App.joinUserToTeam(team, ruser) - th.App.LeaveTeam(team, ruser, ruser.Id) + th.App.LeaveTeam(th.Context, team, ruser, ruser.Id) var alreadyAdded bool _, alreadyAdded, err = th.App.joinUserToTeam(team, ruser) @@ -775,12 +775,12 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("new join with limit problem", func(t *testing.T) { user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser1, _ := th.App.CreateUser(&user1) + ruser1, _ := th.App.CreateUser(th.Context, &user1) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser2, _ := th.App.CreateUser(&user2) + ruser2, _ := th.App.CreateUser(th.Context, &user2) - defer th.App.PermanentDeleteUser(&user1) - defer th.App.PermanentDeleteUser(&user2) + defer th.App.PermanentDeleteUser(th.Context, &user1) + defer th.App.PermanentDeleteUser(th.Context, &user2) th.App.joinUserToTeam(team, ruser1) _, _, err = th.App.joinUserToTeam(team, ruser2) @@ -789,16 +789,16 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("re-join alfter leaving with limit problem", func(t *testing.T) { user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser1, _ := th.App.CreateUser(&user1) + ruser1, _ := th.App.CreateUser(th.Context, &user1) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser2, _ := th.App.CreateUser(&user2) + ruser2, _ := th.App.CreateUser(th.Context, &user2) - defer th.App.PermanentDeleteUser(&user1) - defer th.App.PermanentDeleteUser(&user2) + defer th.App.PermanentDeleteUser(th.Context, &user1) + defer th.App.PermanentDeleteUser(th.Context, &user2) th.App.joinUserToTeam(team, ruser1) - th.App.LeaveTeam(team, ruser1, ruser1.Id) + th.App.LeaveTeam(th.Context, team, ruser1, ruser1.Id) th.App.joinUserToTeam(team, ruser2) _, _, err = th.App.joinUserToTeam(team, ruser1) @@ -807,8 +807,8 @@ func TestJoinUserToTeam(t *testing.T) { t.Run("new join with correct scheme_admin value from group syncable", func(t *testing.T) { user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser1, _ := th.App.CreateUser(&user1) - defer th.App.PermanentDeleteUser(&user1) + ruser1, _ := th.App.CreateUser(th.Context, &user1) + defer th.App.PermanentDeleteUser(th.Context, &user1) group := th.CreateGroup() @@ -831,8 +831,8 @@ func TestJoinUserToTeam(t *testing.T) { require.False(t, tm1.SchemeAdmin) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser2, _ := th.App.CreateUser(&user2) - defer th.App.PermanentDeleteUser(&user2) + ruser2, _ := th.App.CreateUser(th.Context, &user2) + defer th.App.PermanentDeleteUser(th.Context, &user2) _, err = th.App.UpsertGroupMember(group.Id, user2.Id) require.Nil(t, err) @@ -875,12 +875,12 @@ func TestGetTeamMembers(t *testing.T) { Password: "passwd1", DeleteAt: int64(rand.Intn(2)), } - ruser, err := th.App.CreateUser(&user) + ruser, err := th.App.CreateUser(th.Context, &user) require.Nil(t, err) require.NotNil(t, ruser) - defer th.App.PermanentDeleteUser(&user) + defer th.App.PermanentDeleteUser(th.Context, &user) - _, _, err = th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) // Store the users for comparison later @@ -1039,9 +1039,9 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { t.Run("from guest to user", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, "team_user") @@ -1050,9 +1050,9 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { t.Run("from user to guest", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, "team_guest") @@ -1061,9 +1061,9 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { t.Run("from user to admin", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateUser(&user) + ruser, _ := th.App.CreateUser(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, "team_user team_admin") @@ -1072,9 +1072,9 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { t.Run("from guest to guest plus custom", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.CreateRole(&model.Role{Name: "custom", DisplayName: "custom", Description: "custom"}) @@ -1086,9 +1086,9 @@ func TestUpdateTeamMemberRolesChangingGuest(t *testing.T) { t.Run("a guest cant have user role", func(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := th.App.CreateGuest(&user) + ruser, _ := th.App.CreateGuest(th.Context, &user) - _, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "") + _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) _, err = th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, "team_guest team_user") diff --git a/app/upload.go b/app/upload.go index 39cd004228a..c03a06083a7 100644 --- a/app/upload.go +++ b/app/upload.go @@ -12,6 +12,7 @@ import ( "sync" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -21,7 +22,7 @@ import ( const minFirstPartSize = 5 * 1024 * 1024 // 5MB const IncompleteUploadSuffix = ".tmp" -func (a *App) runPluginsHook(info *model.FileInfo, file io.Reader) *model.AppError { +func (a *App) runPluginsHook(c *request.Context, info *model.FileInfo, file io.Reader) *model.AppError { pluginsEnvironment := a.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil @@ -39,7 +40,7 @@ func (a *App) runPluginsHook(info *model.FileInfo, file io.Reader) *model.AppErr defer close(errChan) var rejErr *model.AppError var once sync.Once - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { once.Do(func() { hookHasRunCh <- struct{}{} @@ -162,7 +163,7 @@ func (a *App) GetUploadSessionsForUser(userID string) ([]*model.UploadSession, * return uss, nil } -func (a *App) UploadData(us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) { +func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError) { // prevent more than one caller to upload data at the same time for a given upload session. // This is to avoid possible inconsistencies. a.Srv().uploadLockMapMut.Lock() @@ -258,7 +259,7 @@ func (a *App) UploadData(us *model.UploadSession, rd io.Reader) (*model.FileInfo } // run plugins upload hook - if err := a.runPluginsHook(info, file); err != nil { + if err := a.runPluginsHook(c, info, file); err != nil { return nil, err } diff --git a/app/upload_test.go b/app/upload_test.go index 479b1c3da9d..74e0c99da19 100644 --- a/app/upload_test.go +++ b/app/upload_test.go @@ -76,7 +76,7 @@ func TestCreateUploadSession(t *testing.T) { t.Run("deleted channel", func(t *testing.T) { ch := th.CreateChannel(th.BasicTeam) - th.App.DeleteChannel(ch, th.BasicUser.Id) + th.App.DeleteChannel(th.Context, ch, th.BasicUser.Id) us.ChannelId = ch.Id u, err := th.App.CreateUploadSession(us) require.NotNil(t, err) @@ -125,7 +125,7 @@ func TestUploadData(t *testing.T) { u := *us u.Path = "" - info, appErr := th.App.UploadData(&u, rd) + info, appErr := th.App.UploadData(th.Context, &u, rd) require.Nil(t, info) require.NotNil(t, appErr) require.NotEqual(t, "app.upload.upload_data.first_part_too_small.app_error", appErr.Id) @@ -141,7 +141,7 @@ func TestUploadData(t *testing.T) { require.False(t, ok) require.Nil(t, appErr) - info, appErr := th.App.UploadData(us, rd) + info, appErr := th.App.UploadData(th.Context, us, rd) require.Nil(t, info) require.NotNil(t, appErr) require.Equal(t, "app.upload.upload_data.first_part_too_small.app_error", appErr.Id) @@ -156,7 +156,7 @@ func TestUploadData(t *testing.T) { R: bytes.NewReader(data), N: 5 * 1024 * 1024, } - info, appErr := th.App.UploadData(us, rd) + info, appErr := th.App.UploadData(th.Context, us, rd) require.Nil(t, info) require.Nil(t, appErr) @@ -164,7 +164,7 @@ func TestUploadData(t *testing.T) { R: bytes.NewReader(data[5*1024*1024:]), N: 3 * 1024 * 1024, } - info, appErr = th.App.UploadData(us, rd) + info, appErr = th.App.UploadData(th.Context, us, rd) require.Nil(t, appErr) require.NotEmpty(t, info) @@ -180,7 +180,7 @@ func TestUploadData(t *testing.T) { require.Nil(t, appErr) require.NotEmpty(t, us) - info, appErr := th.App.UploadData(us, bytes.NewReader(data)) + info, appErr := th.App.UploadData(th.Context, us, bytes.NewReader(data)) require.Nil(t, appErr) require.NotEmpty(t, info) @@ -201,7 +201,7 @@ func TestUploadData(t *testing.T) { R: bytes.NewReader(data), N: 1024 * 1024, } - info, appErr := th.App.UploadData(us, rd) + info, appErr := th.App.UploadData(th.Context, us, rd) require.Nil(t, appErr) require.NotEmpty(t, info) @@ -224,7 +224,7 @@ func TestUploadData(t *testing.T) { require.Nil(t, appErr) require.NotEmpty(t, us) - info, appErr := th.App.UploadData(us, bytes.NewReader(data)) + info, appErr := th.App.UploadData(th.Context, us, bytes.NewReader(data)) require.Nil(t, appErr) require.NotEmpty(t, info) require.NotZero(t, info.Width) @@ -269,7 +269,7 @@ func TestUploadDataConcurrent(t *testing.T) { N: 5 * 1024 * 1024, } u := *us - _, err := th.App.UploadData(&u, rd) + _, err := th.App.UploadData(th.Context, &u, rd) if err != nil && err.Id == "app.upload.upload_data.concurrent.app_error" { atomic.AddInt32(&nErrs, 1) } @@ -293,7 +293,7 @@ func TestUploadDataConcurrent(t *testing.T) { } u := *us u.FileOffset = 5 * 1024 * 1024 - _, err := th.App.UploadData(&u, rd) + _, err := th.App.UploadData(th.Context, &u, rd) if err != nil && err.Id == "app.upload.upload_data.concurrent.app_error" { atomic.AddInt32(&nErrs, 1) } diff --git a/app/user.go b/app/user.go index 1840741bc52..ca9f6585222 100644 --- a/app/user.go +++ b/app/user.go @@ -29,6 +29,7 @@ import ( "github.com/golang/freetype" "github.com/golang/freetype/truetype" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" @@ -50,7 +51,7 @@ const ( ImageProfilePixelDimension = 128 ) -func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) { +func (a *App) CreateUserWithToken(c *request.Context, user *model.User, token *model.Token) (*model.User, *model.AppError) { if err := a.IsUserSignUpAllowed(); err != nil { return nil, err } @@ -88,15 +89,15 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. var ruser *model.User var err *model.AppError if token.Type == TokenTypeTeamInvitation { - ruser, err = a.CreateUser(user) + ruser, err = a.CreateUser(c, user) } else { - ruser, err = a.CreateGuest(user) + ruser, err = a.CreateGuest(c, user) } if err != nil { return nil, err } - if _, err := a.JoinUserToTeam(team, ruser, ""); err != nil { + if _, err := a.JoinUserToTeam(c, team, ruser, ""); err != nil { return nil, err } @@ -104,7 +105,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. if token.Type == TokenTypeGuestInvitation { for _, channel := range channels { - _, err := a.AddChannelMember(ruser.Id, channel, ChannelMemberOpts{}) + _, err := a.AddChannelMember(c, ruser.Id, channel, ChannelMemberOpts{}) if err != nil { mlog.Warn("Failed to add channel member", mlog.Err(err)) } @@ -118,7 +119,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. return ruser, nil } -func (a *App) CreateUserWithInviteId(user *model.User, inviteId, redirect string) (*model.User, *model.AppError) { +func (a *App) CreateUserWithInviteId(c *request.Context, user *model.User, inviteId, redirect string) (*model.User, *model.AppError) { if err := a.IsUserSignUpAllowed(); err != nil { return nil, err } @@ -144,12 +145,12 @@ func (a *App) CreateUserWithInviteId(user *model.User, inviteId, redirect string user.EmailVerified = false - ruser, err := a.CreateUser(user) + ruser, err := a.CreateUser(c, user) if err != nil { return nil, err } - if _, err := a.JoinUserToTeam(team, ruser, ""); err != nil { + if _, err := a.JoinUserToTeam(c, team, ruser, ""); err != nil { return nil, err } @@ -162,8 +163,8 @@ func (a *App) CreateUserWithInviteId(user *model.User, inviteId, redirect string return ruser, nil } -func (a *App) CreateUserAsAdmin(user *model.User, redirect string) (*model.User, *model.AppError) { - ruser, err := a.CreateUser(user) +func (a *App) CreateUserAsAdmin(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) { + ruser, err := a.CreateUser(c, user) if err != nil { return nil, err } @@ -175,7 +176,7 @@ func (a *App) CreateUserAsAdmin(user *model.User, redirect string) (*model.User, return ruser, nil } -func (a *App) CreateUserFromSignup(user *model.User, redirect string) (*model.User, *model.AppError) { +func (a *App) CreateUserFromSignup(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) { if err := a.IsUserSignUpAllowed(); err != nil { return nil, err } @@ -187,7 +188,7 @@ func (a *App) CreateUserFromSignup(user *model.User, redirect string) (*model.Us user.EmailVerified = false - ruser, err := a.CreateUser(user) + ruser, err := a.CreateUser(c, user) if err != nil { return nil, err } @@ -232,17 +233,17 @@ func (a *App) IsFirstUserAccount() bool { // CreateUser creates a user and sets several fields of the returned User struct to // their zero values. -func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { - return a.createUserOrGuest(user, false) +func (a *App) CreateUser(c *request.Context, user *model.User) (*model.User, *model.AppError) { + return a.createUserOrGuest(c, user, false) } // CreateGuest creates a guest and sets several fields of the returned User struct to // their zero values. -func (a *App) CreateGuest(user *model.User) (*model.User, *model.AppError) { - return a.createUserOrGuest(user, true) +func (a *App) CreateGuest(c *request.Context, user *model.User) (*model.User, *model.AppError) { + return a.createUserOrGuest(c, user, true) } -func (a *App) createUserOrGuest(user *model.User, guest bool) (*model.User, *model.AppError) { +func (a *App) createUserOrGuest(c *request.Context, user *model.User, guest bool) (*model.User, *model.AppError) { user.Roles = model.SYSTEM_USER_ROLE_ID if guest { user.Roles = model.SYSTEM_GUEST_ROLE_ID @@ -281,7 +282,7 @@ func (a *App) createUserOrGuest(user *model.User, guest bool) (*model.User, *mod if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { a.Srv().Go(func() { - pluginContext := a.PluginContext() + pluginContext := pluginContext(c) pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { hooks.UserHasBeenCreated(pluginContext, user) return true @@ -339,7 +340,7 @@ func (a *App) createUser(user *model.User) (*model.User, *model.AppError) { return ruser, nil } -func (a *App) CreateOAuthUser(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { +func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) { if !*a.Config().TeamSettings.EnableUserCreation { return nil, model.NewAppError("CreateOAuthUser", "api.user.create_user.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -380,13 +381,13 @@ func (a *App) CreateOAuthUser(service string, userData io.Reader, teamID string, user.EmailVerified = true - ruser, err := a.CreateUser(user) + ruser, err := a.CreateUser(c, user) if err != nil { return nil, err } if teamID != "" { - err = a.AddUserToTeamByTeamId(teamID, user) + err = a.AddUserToTeamByTeamId(c, teamID, user) if err != nil { return nil, err } @@ -695,8 +696,8 @@ func (a *App) GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ( return a.sanitizeProfiles(users, options.IsAdmin), nil } -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) +func (a *App) GetUsersByGroupChannelIds(c *request.Context, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError) { + usersByChannelId, err := a.Srv().Store.User().GetProfileByGroupChannelIdsForUser(c.Session().UserId, channelIDs) if err != nil { return nil, model.NewAppError("GetUsersByGroupChannelIds", "app.user.get_profile_by_group_channel_ids_for_user.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1012,7 +1013,7 @@ func (a *App) UpdatePasswordAsUser(userID, currentPassword, newPassword string) return a.UpdatePasswordSendEmail(user, newPassword, T("api.user.update_password.menu")) } -func (a *App) userDeactivated(userID string) *model.AppError { +func (a *App) userDeactivated(c *request.Context, userID string) *model.AppError { if err := a.RevokeAllSessions(userID); err != nil { return err } @@ -1028,11 +1029,11 @@ func (a *App) userDeactivated(userID string) *model.AppError { // bots the user owns. Only notify once, when the user is the owner, not the // owners bots if !user.IsBot { - a.notifySysadminsBotOwnerDeactivated(userID) + a.notifySysadminsBotOwnerDeactivated(c, userID) } if *a.Config().ServiceSettings.DisableBotsWhenOwnerIsDeactivated { - a.disableUserBots(userID) + a.disableUserBots(c, userID) } return nil @@ -1058,7 +1059,7 @@ func (a *App) invalidateUserChannelMembersCaches(userID string) *model.AppError return nil } -func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) { +func (a *App) UpdateActive(c *request.Context, user *model.User, active bool) (*model.User, *model.AppError) { user.UpdateAt = model.GetMillis() if active { user.DeleteAt = 0 @@ -1082,7 +1083,7 @@ func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.A ruser := userUpdate.New if !active { - if err := a.userDeactivated(ruser.Id); err != nil { + if err := a.userDeactivated(c, ruser.Id); err != nil { return nil, err } } @@ -1095,14 +1096,14 @@ func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.A return ruser, nil } -func (a *App) DeactivateGuests() *model.AppError { +func (a *App) DeactivateGuests(c *request.Context) *model.AppError { userIDs, err := a.Srv().Store.User().DeactivateGuests() if err != nil { return model.NewAppError("DeactivateGuests", "app.user.update_active_for_multiple_users.updating.app_error", nil, err.Error(), http.StatusInternalServerError) } for _, userID := range userIDs { - if err := a.userDeactivated(userID); err != nil { + if err := a.userDeactivated(c, userID); err != nil { return err } } @@ -1314,13 +1315,13 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, return userUpdate.New, nil } -func (a *App) UpdateUserActive(userID string, active bool) *model.AppError { +func (a *App) UpdateUserActive(c *request.Context, userID string, active bool) *model.AppError { user, err := a.GetUser(userID) if err != nil { return err } - if _, err = a.UpdateActive(user, active); err != nil { + if _, err = a.UpdateActive(c, user, active); err != nil { return err } @@ -1603,13 +1604,13 @@ func (a *App) UpdateUserRolesWithUser(user *model.User, newRoles string, sendWeb return ruser, nil } -func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { +func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.AppError { mlog.Warn("Attempting to permanently delete account", mlog.String("user_id", user.Id), mlog.String("user_email", user.Email)) if user.IsInRole(model.SYSTEM_ADMIN_ROLE_ID) { mlog.Warn("You are deleting a user that is a system administrator. You may need to set another account as the system administrator using the command line tools.", mlog.String("user_email", user.Email)) } - if _, err := a.UpdateActive(user, false); err != nil { + if _, err := a.UpdateActive(c, user, false); err != nil { return err } @@ -1716,13 +1717,13 @@ func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { return nil } -func (a *App) PermanentDeleteAllUsers() *model.AppError { +func (a *App) PermanentDeleteAllUsers(c *request.Context) *model.AppError { users, err := a.Srv().Store.User().GetAll() if err != nil { return model.NewAppError("PermanentDeleteAllUsers", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError) } for _, user := range users { - a.PermanentDeleteUser(user) + a.PermanentDeleteUser(c, user) } return nil @@ -2179,7 +2180,7 @@ func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestricti // 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 { +func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError { nErr := a.Srv().Store.User().PromoteGuestToUser(user.Id) a.InvalidateCacheForUser(user.Id) if nErr != nil { @@ -2192,7 +2193,7 @@ func (a *App) PromoteGuestToUser(user *model.User, requestorId string) *model.Ap for _, team := range userTeams { // Soft error if there is an issue joining the default channels - if err := a.JoinDefaultChannels(team.Id, user, false, requestorId); err != nil { + if err := a.JoinDefaultChannels(c, team.Id, user, false, requestorId); err != nil { mlog.Warn("Failed to join default channels", mlog.String("user_id", user.Id), mlog.String("team_id", team.Id), mlog.String("requestor_id", requestorId), mlog.Err(err)) } } diff --git a/app/user_test.go b/app/user_test.go index de3466ef027..97c0f1c7d71 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -17,6 +17,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" oauthgitlab "github.com/mattermost/mattermost-server/v5/model/gitlab" @@ -84,16 +85,16 @@ func TestCreateOAuthUser(t *testing.T) { glUser := oauthgitlab.GitLabUser{Id: 42, Username: "o" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", Name: "Joram Wilander"} json := glUser.ToJson() - user, err := th.App.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id, nil) + user, err := th.App.CreateOAuthUser(th.Context, model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id, nil) require.Nil(t, err) require.Equal(t, glUser.Username, user.Username, "usernames didn't match") - th.App.PermanentDeleteUser(user) + th.App.PermanentDeleteUser(th.Context, user) *th.App.Config().TeamSettings.EnableUserCreation = false - _, err = th.App.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id, nil) + _, err = th.App.CreateOAuthUser(th.Context, model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id, nil) require.NotNil(t, err, "should have failed - user creation disabled") } @@ -160,7 +161,7 @@ func TestUpdateUserToRestrictedDomain(t *testing.T) { defer th.TearDown() user := th.CreateUser() - defer th.App.PermanentDeleteUser(user) + defer th.App.PermanentDeleteUser(th.Context, user) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "foo.com" @@ -175,7 +176,7 @@ func TestUpdateUserToRestrictedDomain(t *testing.T) { t.Run("Restricted Domains must be ignored for guest users", func(t *testing.T) { guest := th.CreateGuest() - defer th.App.PermanentDeleteUser(guest) + defer th.App.PermanentDeleteUser(th.Context, guest) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "foo.com" @@ -189,7 +190,7 @@ func TestUpdateUserToRestrictedDomain(t *testing.T) { t.Run("Guest users should be affected by guest restricted domains", func(t *testing.T) { guest := th.CreateGuest() - defer th.App.PermanentDeleteUser(guest) + defer th.App.PermanentDeleteUser(th.Context, guest) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "foo.com" @@ -220,7 +221,7 @@ func TestUpdateUserActive(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = true }) - err := th.App.UpdateUserActive(user.Id, false) + err := th.App.UpdateUserActive(th.Context, user.Id, false) assert.Nil(t, err) } @@ -228,7 +229,7 @@ func TestUpdateActiveBotsSideEffect(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "username", Description: "a bot", OwnerId: th.BasicUser.Id, @@ -241,7 +242,7 @@ func TestUpdateActiveBotsSideEffect(t *testing.T) { *cfg.ServiceSettings.DisableBotsWhenOwnerIsDeactivated = false }) - th.App.UpdateActive(th.BasicUser, false) + th.App.UpdateActive(th.Context, th.BasicUser, false) retbot1, err := th.App.GetBot(bot.UserId, true) require.Nil(t, err) @@ -250,14 +251,14 @@ func TestUpdateActiveBotsSideEffect(t *testing.T) { require.Nil(t, err) require.Zero(t, user1.DeleteAt) - th.App.UpdateActive(th.BasicUser, true) + th.App.UpdateActive(th.Context, th.BasicUser, true) // Automatic deactivation enabled th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.DisableBotsWhenOwnerIsDeactivated = true }) - th.App.UpdateActive(th.BasicUser, false) + th.App.UpdateActive(th.Context, th.BasicUser, false) retbot2, err := th.App.GetBot(bot.UserId, true) require.Nil(t, err) @@ -266,7 +267,7 @@ func TestUpdateActiveBotsSideEffect(t *testing.T) { require.Nil(t, err) require.NotZero(t, user2.DeleteAt) - th.App.UpdateActive(th.BasicUser, true) + th.App.UpdateActive(th.Context, th.BasicUser, true) } func TestUpdateOAuthUserAttrs(t *testing.T) { @@ -288,8 +289,8 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { var user, user2 *model.User var gitlabUserObj oauthgitlab.GitLabUser - user, gitlabUserObj = createGitlabUser(t, th.App, 1, username, email) - user2, _ = createGitlabUser(t, th.App, 2, username2, email2) + user, gitlabUserObj = createGitlabUser(t, th.App, th.Context, 1, username, email) + user2, _ = createGitlabUser(t, th.App, th.Context, 2, username2, email2) t.Run("UpdateUsername", func(t *testing.T) { t.Run("NoExistingUserWithSameUsername", func(t *testing.T) { @@ -534,14 +535,14 @@ func getGitlabUserPayload(gitlabUser oauthgitlab.GitLabUser, t *testing.T) []byt return payload } -func createGitlabUser(t *testing.T, a *App, id int64, username string, email string) (*model.User, oauthgitlab.GitLabUser) { +func createGitlabUser(t *testing.T, a *App, c *request.Context, id int64, username string, email string) (*model.User, oauthgitlab.GitLabUser) { gitlabUserObj := oauthgitlab.GitLabUser{Id: id, Username: username, Login: "user1", Email: email, Name: "Test User"} gitlabUser := getGitlabUserPayload(gitlabUserObj, t) var user *model.User var err *model.AppError - user, err = a.CreateOAuthUser("gitlab", bytes.NewReader(gitlabUser), "", nil) + user, err = a.CreateOAuthUser(c, "gitlab", bytes.NewReader(gitlabUser), "", nil) require.Nil(t, err, "unable to create the user", err) return user, gitlabUserObj @@ -552,7 +553,7 @@ func TestGetUsersByStatus(t *testing.T) { defer th.TearDown() team := th.CreateTeam() - channel, err := th.App.CreateChannel(&model.Channel{ + channel, err := th.App.CreateChannel(th.Context, &model.Channel{ DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.CHANNEL_OPEN, @@ -564,7 +565,7 @@ func TestGetUsersByStatus(t *testing.T) { createUserWithStatus := func(username string, status string) *model.User { id := model.NewId() - user, err := th.App.CreateUser(&model.User{ + user, err := th.App.CreateUser(th.Context, &model.User{ Email: "success+" + id + "@simulator.amazonses.com", Username: "un_" + username + "_" + id, Nickname: "nn_" + id, @@ -684,13 +685,13 @@ func TestCreateUserWithInviteId(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} t.Run("should create a user", func(t *testing.T) { - u, err := th.App.CreateUserWithInviteId(&user, th.BasicTeam.InviteId, "") + u, err := th.App.CreateUserWithInviteId(th.Context, &user, th.BasicTeam.InviteId, "") require.Nil(t, err) require.Equal(t, u.Id, user.Id) }) t.Run("invalid invite id", func(t *testing.T) { - _, err := th.App.CreateUserWithInviteId(&user, "", "") + _, err := th.App.CreateUserWithInviteId(th.Context, &user, "", "") require.NotNil(t, err) require.Contains(t, err.Id, "app.team.get_by_invite_id") }) @@ -699,7 +700,7 @@ func TestCreateUserWithInviteId(t *testing.T) { th.BasicTeam.AllowedDomains = "mattermost.com" _, nErr := th.App.Srv().Store.Team().Update(th.BasicTeam) require.NoError(t, nErr) - _, err := th.App.CreateUserWithInviteId(&user, th.BasicTeam.InviteId, "") + _, err := th.App.CreateUserWithInviteId(th.Context, &user, th.BasicTeam.InviteId, "") require.NotNil(t, err) require.Equal(t, "api.team.invite_members.invalid_email.app_error", err.Id) }) @@ -712,7 +713,7 @@ func TestCreateUserWithToken(t *testing.T) { user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} t.Run("invalid token", func(t *testing.T) { - _, err := th.App.CreateUserWithToken(&user, &model.Token{Token: "123"}) + _, err := th.App.CreateUserWithToken(th.Context, &user, &model.Token{Token: "123"}) require.NotNil(t, err, "Should fail on unexisting token") }) @@ -723,7 +724,7 @@ func TestCreateUserWithToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, err := th.App.CreateUserWithToken(&user, token) + _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on bad token type") }) @@ -735,7 +736,7 @@ func TestCreateUserWithToken(t *testing.T) { token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1 require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, err := th.App.CreateUserWithToken(&user, token) + _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on expired token") }) @@ -746,7 +747,7 @@ func TestCreateUserWithToken(t *testing.T) { ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) - _, err := th.App.CreateUserWithToken(&user, token) + _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on bad team id") }) @@ -757,7 +758,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}), ) require.NoError(t, th.App.Srv().Store.Token().Save(token)) - newUser, err := th.App.CreateUserWithToken(&user, token) + newUser, err := th.App.CreateUserWithToken(th.Context, &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") @@ -778,7 +779,7 @@ func TestCreateUserWithToken(t *testing.T) { ) require.NoError(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) + newGuest, err := th.App.CreateUserWithToken(th.Context, &guest, token) require.Nil(t, err, "Should add user to the team. err=%v", err) assert.True(t, newGuest.IsGuest()) @@ -819,12 +820,12 @@ func TestCreateUserWithToken(t *testing.T) { Password: "passwd1", AuthService: "", } - newGuest, err := th.App.CreateUserWithToken(&guest, forbiddenDomainToken) + newGuest, err := th.App.CreateUserWithToken(th.Context, &guest, forbiddenDomainToken) require.NotNil(t, err) require.Nil(t, newGuest) assert.Equal(t, "api.user.create_user.accepted_domain.app_error", err.Id) - newGuest, err = th.App.CreateUserWithToken(&guest, grantedDomainToken) + newGuest, err = th.App.CreateUserWithToken(th.Context, &guest, grantedDomainToken) require.Nil(t, err) assert.True(t, newGuest.IsGuest()) require.Equal(t, grantedInvitationEmail, newGuest.Email) @@ -861,7 +862,7 @@ func TestCreateUserWithToken(t *testing.T) { Password: "passwd1", AuthService: "", } - newGuest, err := th.App.CreateUserWithToken(&guest, token) + newGuest, err := th.App.CreateUserWithToken(th.Context, &guest, token) require.Nil(t, err) assert.True(t, newGuest.IsGuest()) assert.Equal(t, invitationEmail, newGuest.Email, "The user email must be the invitation one") @@ -881,11 +882,11 @@ func TestPermanentDeleteUser(t *testing.T) { b := []byte("testimage") - finfo, err := th.App.DoUploadFile(time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "testfile.txt", b) + finfo, err := th.App.DoUploadFile(th.Context, time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "testfile.txt", b) require.Nil(t, err, "Unable to upload file. err=%v", err) - bot, err := th.App.CreateBot(&model.Bot{ + bot, err := th.App.CreateBot(th.Context, &model.Bot{ Username: "botname", Description: "a bot", OwnerId: model.NewId(), @@ -904,14 +905,14 @@ func TestPermanentDeleteUser(t *testing.T) { retUser1, err := th.App.GetUser(bot.UserId) assert.Nil(t, err) - err = th.App.PermanentDeleteUser(retUser1) + err = th.App.PermanentDeleteUser(th.Context, retUser1) assert.Nil(t, err) _, err1 = sqlStore.GetMaster().Select(&bots2, "SELECT * FROM Bots") assert.NoError(t, err1) assert.Equal(t, 0, len(bots2)) - err = th.App.PermanentDeleteUser(th.BasicUser) + err = th.App.PermanentDeleteUser(th.Context, th.BasicUser) require.Nil(t, err, "Unable to delete user. err=%v", err) res, err := th.App.FileExists(finfo.Path) @@ -1086,7 +1087,7 @@ func TestPromoteGuestToUser(t *testing.T) { t.Run("Must fail with regular user", func(t *testing.T) { require.Equal(t, "system_user", th.BasicUser.Roles) - err := th.App.PromoteGuestToUser(th.BasicUser, th.BasicUser.Id) + err := th.App.PromoteGuestToUser(th.Context, th.BasicUser, th.BasicUser.Id) require.Nil(t, err) user, err := th.App.GetUser(th.BasicUser.Id) @@ -1098,7 +1099,7 @@ func TestPromoteGuestToUser(t *testing.T) { guest := th.CreateGuest() require.Equal(t, "system_guest", guest.Roles) - err := th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err := th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) guest, err = th.App.GetUser(guest.Id) assert.Nil(t, err) @@ -1114,7 +1115,7 @@ func TestPromoteGuestToUser(t *testing.T) { require.True(t, teamMember.SchemeGuest) require.False(t, teamMember.SchemeUser) - err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) guest, err = th.App.GetUser(guest.Id) assert.Nil(t, err) @@ -1138,7 +1139,7 @@ func TestPromoteGuestToUser(t *testing.T) { require.True(t, channelMember.SchemeGuest) require.False(t, channelMember.SchemeUser) - err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) guest, err = th.App.GetUser(guest.Id) assert.Nil(t, err) @@ -1170,7 +1171,7 @@ func TestPromoteGuestToUser(t *testing.T) { require.Nil(t, err) require.Len(t, *channelMembers, 1) - err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) guest, err = th.App.GetUser(guest.Id) assert.Nil(t, err) @@ -1208,7 +1209,7 @@ func TestPromoteGuestToUser(t *testing.T) { guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) require.Equal(t, int64(1), guestCount) - err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id) + err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) @@ -1407,7 +1408,7 @@ func TestDeactivateGuests(t *testing.T) { guest2 := th.CreateGuest() user := th.CreateUser() - err := th.App.DeactivateGuests() + err := th.App.DeactivateGuests(th.Context) require.Nil(t, err) guest1, err = th.App.GetUser(guest1.Id) @@ -1463,7 +1464,7 @@ func TestPatchUser(t *testing.T) { defer th.TearDown() testUser := th.CreateUser() - defer th.App.PermanentDeleteUser(testUser) + defer th.App.PermanentDeleteUser(th.Context, testUser) t.Run("Patch with a username already exists", func(t *testing.T) { _, err := th.App.PatchUser(testUser.Id, &model.UserPatch{ diff --git a/app/web_conn.go b/app/web_conn.go index daa8ba08d27..48ac1fc192f 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -104,14 +104,14 @@ type CheckConnResult struct { // PopulateWebConnConfig checks if the connection id already exists in the hub, // and if so, accordingly populates the other fields of the webconn. -func (a *App) PopulateWebConnConfig(cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) { +func (a *App) PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) { if !model.IsValidId(cfg.ConnectionID) { return nil, fmt.Errorf("invalid connection id: %s", cfg.ConnectionID) } // TODO: the method should internally forward the request // to the cluster if it does not have it. - res := a.CheckWebConn(a.Session().UserId, cfg.ConnectionID) + res := a.CheckWebConn(s.UserId, cfg.ConnectionID) if res == nil { // If the connection is not present, then we assume either timeout, // or server restart. In that case, we set a new one. diff --git a/app/webhook.go b/app/webhook.go index 28a60438cf6..6e3300be205 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -12,6 +12,7 @@ import ( "strings" "unicode/utf8" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" "github.com/mattermost/mattermost-server/v5/store" @@ -25,7 +26,7 @@ const ( MaxIntegrationResponseSize = 1024 * 1024 // Posts can be <100KB at most, so this is likely more than enough ) -func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *App) handleWebhookEvents(c *request.Context, post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { if !*a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil } @@ -83,7 +84,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m } a.Srv().Go(func(hook *model.OutgoingWebhook) func() { return func() { - a.TriggerWebhook(payload, hook, post, channel) + a.TriggerWebhook(c, payload, hook, post, channel) } }(hook)) } @@ -91,7 +92,7 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m return nil } -func (a *App) TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { +func (a *App) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { var body io.Reader var contentType string if hook.ContentType == "application/json" { @@ -139,7 +140,7 @@ func (a *App) TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model. if *a.Config().ServiceSettings.EnablePostIconOverride && hook.IconURL != "" && webhookResp.IconURL == "" { webhookResp.IconURL = hook.IconURL } - if _, err := a.CreateWebhookPost(hook.CreatorId, channel, text, webhookResp.Username, webhookResp.IconURL, "", webhookResp.Props, webhookResp.Type, postRootId); err != nil { + if _, err := a.CreateWebhookPost(c, hook.CreatorId, channel, text, webhookResp.Username, webhookResp.IconURL, "", webhookResp.Props, webhookResp.Type, postRootId); err != nil { mlog.Error("Failed to create response post.", mlog.Err(err)) } } @@ -247,7 +248,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. return splits, nil } -func (a *App) CreateWebhookPost(userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { +func (a *App) CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { // parse links into Markdown format linkWithTextRegex := regexp.MustCompile(`<([^\n<\|>]+)\|([^\n>]+)>`) text = linkWithTextRegex.ReplaceAllString(text, "[${2}](${1})") @@ -299,7 +300,7 @@ func (a *App) CreateWebhookPost(userID string, channel *model.Channel, text, ove } for _, split := range splits { - if _, err := a.CreatePostMissingChannel(split, false); err != nil { + if _, err := a.CreatePostMissingChannel(c, split, false); err != nil { return nil, model.NewAppError("CreateWebhookPost", "api.post.create_webhook_post.creating.app_error", nil, "err="+err.Message, http.StatusInternalServerError) } } @@ -642,7 +643,7 @@ func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.Out return webhook, nil } -func (a *App) HandleIncomingWebhook(hookID string, req *model.IncomingWebhookRequest) *model.AppError { +func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *model.IncomingWebhookRequest) *model.AppError { if !*a.Config().ServiceSettings.EnableIncomingWebhooks { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -703,7 +704,7 @@ func (a *App) HandleIncomingWebhook(hookID string, req *model.IncomingWebhookReq if nErr != nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.user.app_error", nil, nErr.Error(), http.StatusBadRequest) } - ch, err := a.GetOrCreateDirectChannel(hook.UserId, result.Id) + ch, err := a.GetOrCreateDirectChannel(c, hook.UserId, result.Id) if err != nil { return err } @@ -781,7 +782,7 @@ func (a *App) HandleIncomingWebhook(hookID string, req *model.IncomingWebhookReq overrideIconURL = req.IconURL } - _, err := a.CreateWebhookPost(hook.UserId, channel, text, overrideUsername, overrideIconURL, req.IconEmoji, req.Props, webhookType, "") + _, err := a.CreateWebhookPost(c, hook.UserId, channel, text, overrideUsername, overrideIconURL, req.IconEmoji, req.Props, webhookType, "") return err } @@ -811,7 +812,7 @@ func (a *App) CreateCommandWebhook(commandID string, args *model.CommandArgs) (* return savedHook, nil } -func (a *App) HandleCommandWebhook(hookID string, response *model.CommandResponse) *model.AppError { +func (a *App) HandleCommandWebhook(c *request.Context, hookID string, response *model.CommandResponse) *model.AppError { if response == nil { return model.NewAppError("HandleCommandWebhook", "app.command_webhook.handle_command_webhook.parse", nil, "", http.StatusBadRequest) } @@ -856,6 +857,6 @@ func (a *App) HandleCommandWebhook(hookID string, response *model.CommandRespons } } - _, err := a.HandleCommandResponse(cmd, args, response, false) + _, err := a.HandleCommandResponse(c, cmd, args, response, false) return err } diff --git a/app/webhook_test.go b/app/webhook_test.go index 241243d499a..4002a59ce73 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -293,7 +293,7 @@ func TestCreateWebhookPost(t *testing.T) { require.Nil(t, err) defer th.App.DeleteIncomingWebhook(hook.Id) - post, err := th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", model.StringInterface{ + post, err := th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", model.StringInterface{ "attachments": []*model.SlackAttachment{ { Text: "text", @@ -307,11 +307,11 @@ func TestCreateWebhookPost(t *testing.T) { assert.Contains(t, post.GetProps(), "attachments", "missing attachments prop") assert.Contains(t, post.GetProps(), "webhook_display_name", "missing webhook_display_name prop") - _, err = th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", nil, model.POST_SYSTEM_GENERIC, "") + _, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", "", nil, model.POST_SYSTEM_GENERIC, "") require.NotNil(t, err, "Should have failed - bad post type") expectedText := "`<>|<>|`" - post, err = th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ + post, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ "attachments": []*model.SlackAttachment{ { Text: "text", @@ -323,7 +323,7 @@ func TestCreateWebhookPost(t *testing.T) { assert.Equal(t, expectedText, post.Message) expectedText = "< | \n|\n>" - post, err = th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ + post, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ "attachments": []*model.SlackAttachment{ { Text: "text", @@ -351,7 +351,7 @@ Date: Thu Mar 1 19:46:48 2018 +0300 test | 3 +++ 1 file changed, 3 insertions(+)` - post, err = th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ + post, err = th.App.CreateWebhookPost(th.Context, hook.UserId, th.BasicChannel, expectedText, "user", "http://iconurl", "", model.StringInterface{ "attachments": []*model.SlackAttachment{ { Text: "text", @@ -684,7 +684,7 @@ func TestTriggerOutGoingWebhookWithUsernameAndIconURL(t *testing.T) { hook, _ := createOutgoingWebhook(channel, ts.URL, th) payload := getPayload(hook, th, channel) - th.App.TriggerWebhook(payload, hook, th.BasicPost, channel) + th.App.TriggerWebhook(th.Context, payload, hook, th.BasicPost, channel) waitUntilWebhookResposeIsCreatedAsPost(channel, th, createdPost) diff --git a/app/websocket_router.go b/app/websocket_router.go index bf0bc1d7e30..cb201165614 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -25,8 +25,6 @@ func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) { } func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { - wr.app.InitServer() - if r.Action == "" { err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) returnWebSocketError(wr.app, conn, r, err) diff --git a/cmd/mattermost/commands/channel.go b/cmd/mattermost/commands/channel.go index 191383d4b67..8c932fa8cbb 100644 --- a/cmd/mattermost/commands/channel.go +++ b/cmd/mattermost/commands/channel.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" ) @@ -211,7 +212,7 @@ func createChannelCmdF(command *cobra.Command, args []string) error { CreatorId: "", } - createdChannel, errCreatedChannel := a.CreateChannel(channel, false) + createdChannel, errCreatedChannel := a.CreateChannel(&request.Context{}, channel, false) if errCreatedChannel != nil { return errCreatedChannel } @@ -265,7 +266,7 @@ func removeUserFromChannel(a *app.App, channel *model.Channel, user *model.User, CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if err := a.RemoveUserFromChannel(user.Id, "", channel); err != nil { + if err := a.RemoveUserFromChannel(&request.Context{}, user.Id, "", channel); err != nil { CommandPrintErrorln("Unable to remove '" + userArg + "' from " + channel.Name + ". Error: " + err.Error()) return } @@ -427,7 +428,7 @@ func moveChannel(a *app.App, team *model.Team, channel *model.Channel, user *mod return err } - if err := a.MoveChannel(team, channel, user); err != nil { + if err := a.MoveChannel(&request.Context{}, team, channel, user); err != nil { return err } @@ -565,7 +566,7 @@ func modifyChannelCmdF(command *cobra.Command, args []string) error { return fmt.Errorf("Unable to find user: '%v'", username) } - updatedChannel, errUpdate := a.UpdateChannelPrivacy(channel, user) + updatedChannel, errUpdate := a.UpdateChannelPrivacy(&request.Context{}, channel, user) if errUpdate != nil { return errors.Wrapf(err, "Failed to update channel ('%s') privacy", args[0]) } diff --git a/cmd/mattermost/commands/import.go b/cmd/mattermost/commands/import.go index 691495fe762..bafe2ad19c0 100644 --- a/cmd/mattermost/commands/import.go +++ b/cmd/mattermost/commands/import.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" ) @@ -76,7 +77,7 @@ func slackImportCmdF(command *cobra.Command, args []string) error { CommandPrettyPrintln("Running Slack Import. This may take a long time for large teams or teams with many messages.") - importErr, log := a.SlackImport(fileReader, fileInfo.Size(), team.Id) + importErr, log := a.SlackImport(&request.Context{}, fileReader, fileInfo.Size(), team.Id) if importErr != nil { return err @@ -149,7 +150,7 @@ func bulkImportCmdF(command *cobra.Command, args []string) error { CommandPrettyPrintln("") - if err, lineNumber := a.BulkImportWithPath(fileReader, !apply, workers, importPath); err != nil { + if err, lineNumber := a.BulkImportWithPath(&request.Context{}, fileReader, !apply, workers, importPath); err != nil { CommandPrintErrorln(err.Error()) if lineNumber != 0 { CommandPrintErrorln(fmt.Sprintf("Error occurred on data file line %v", lineNumber)) diff --git a/cmd/mattermost/commands/init.go b/cmd/mattermost/commands/init.go index ea25d694be3..d304e48d536 100644 --- a/cmd/mattermost/commands/init.go +++ b/cmd/mattermost/commands/init.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -20,7 +21,7 @@ func initDBCommandContextCobra(command *cobra.Command, readOnlyConfigStore bool) panic(err) } - a.InitPlugins(*a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) + a.InitPlugins(&request.Context{}, *a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) a.DoAppMigrations() return a, nil @@ -53,7 +54,6 @@ func initDBCommandContext(configDSN string, readOnlyConfigStore bool) (*app.App, if model.BuildEnterpriseReady == "true" { a.Srv().LoadLicense() } - a.InitServer() return a, nil } diff --git a/cmd/mattermost/commands/jobserver.go b/cmd/mattermost/commands/jobserver.go index 26895c10ae5..92bbc90f111 100644 --- a/cmd/mattermost/commands/jobserver.go +++ b/cmd/mattermost/commands/jobserver.go @@ -41,7 +41,6 @@ func jobserverCmdF(command *cobra.Command, args []string) error { defer a.Srv().Shutdown() a.Srv().LoadLicense() - a.InitServer() // Run jobs mlog.Info("Starting Mattermost job server") diff --git a/cmd/mattermost/commands/sampledata.go b/cmd/mattermost/commands/sampledata.go index 676ba677b7b..f00158e3124 100644 --- a/cmd/mattermost/commands/sampledata.go +++ b/cmd/mattermost/commands/sampledata.go @@ -19,6 +19,7 @@ import ( "github.com/spf13/cobra" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/utils" @@ -373,7 +374,7 @@ func sampleDataCmdF(command *cobra.Command, args []string) error { } var importErr *model.AppError - importErr, lineNumber := a.BulkImport(bulkFile, false, workers) + importErr, lineNumber := a.BulkImport(&request.Context{}, bulkFile, false, workers) if importErr != nil { return fmt.Errorf("%s: %s, %s (line: %d)", importErr.Where, importErr.Message, importErr.DetailedError, lineNumber) } diff --git a/cmd/mattermost/commands/server.go b/cmd/mattermost/commands/server.go index ae87586b36d..abfc4ef7b81 100644 --- a/cmd/mattermost/commands/server.go +++ b/cmd/mattermost/commands/server.go @@ -100,10 +100,12 @@ func runServer(configStore *config.Store, usedPlatform bool, interruptChan chan mlog.Warn("The platform binary has been deprecated, please switch to using the mattermost binary.") } - api := api4.Init(server, server.AppOptions, server.Router) + a := app.New(app.ServerConnector(server)) + api := api4.Init(a, server.Router) + wsapi.Init(server) - web.New(server, server.AppOptions, server.Router) - api4.InitLocal(server, server.AppOptions, server.LocalRouter) + web.New(a, server.Router) + api4.InitLocal(a, server.LocalRouter) serverErr := server.Start() if serverErr != nil { @@ -111,13 +113,6 @@ func runServer(configStore *config.Store, usedPlatform bool, interruptChan chan return serverErr } - // TODO: remove this and handle all required initialization while creating - // the server. In theory, we shouldn't depend on App to have a fully-featured - // server. This initialization is added so that cluster handlers are registered - // and job schedulers are initialized. - fakeApp := app.New(app.ServerConnector(server)) - fakeApp.InitServer() - // If we allow testing then listen for manual testing URL hits if *server.Config().ServiceSettings.EnableTesting { manualtesting.Init(api) diff --git a/cmd/mattermost/commands/server_test.go b/cmd/mattermost/commands/server_test.go index ba039c9ca10..a31dee70f5d 100644 --- a/cmd/mattermost/commands/server_test.go +++ b/cmd/mattermost/commands/server_test.go @@ -58,7 +58,6 @@ func (th *ServerTestHelper) TearDownServerTest() { } func TestRunServerSuccess(t *testing.T) { - t.Skip("MM-34557") th := SetupServerTest(t) defer th.TearDownServerTest() @@ -72,7 +71,6 @@ func TestRunServerSuccess(t *testing.T) { } func TestRunServerSystemdNotification(t *testing.T) { - t.Skip("MM-34557") th := SetupServerTest(t) defer th.TearDownServerTest() @@ -128,7 +126,6 @@ func TestRunServerSystemdNotification(t *testing.T) { } func TestRunServerNoSystemd(t *testing.T) { - t.Skip("MM-34557") th := SetupServerTest(t) defer th.TearDownServerTest() diff --git a/cmd/mattermost/commands/team.go b/cmd/mattermost/commands/team.go index c633198baa5..547f4681d50 100644 --- a/cmd/mattermost/commands/team.go +++ b/cmd/mattermost/commands/team.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" ) @@ -171,7 +172,7 @@ func createTeamCmdF(command *cobra.Command, args []string) error { Type: teamType, } - createdTeam, errCreate := a.CreateTeam(team) + createdTeam, errCreate := a.CreateTeam(&request.Context{}, team) if errCreate != nil { return errors.New("Team creation failed: " + errCreate.Error()) } @@ -208,7 +209,7 @@ func removeUserFromTeam(a *app.App, team *model.Team, user *model.User, userArg CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if err := a.LeaveTeam(team, user, ""); err != nil { + if err := a.LeaveTeam(&request.Context{}, team, user, ""); err != nil { CommandPrintErrorln("Unable to remove '" + userArg + "' from " + team.Name + ". Error: " + err.Error()) return } @@ -243,7 +244,7 @@ func addUserToTeam(a *app.App, team *model.Team, user *model.User, userArg strin CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if _, err := a.JoinUserToTeam(team, user, ""); err != nil { + if _, err := a.JoinUserToTeam(&request.Context{}, team, user, ""); err != nil { CommandPrintErrorln("Unable to add '" + userArg + "' to " + team.Name) return } diff --git a/cmd/mattermost/commands/test.go b/cmd/mattermost/commands/test.go index 5e6fb5943cc..cf48740171a 100644 --- a/cmd/mattermost/commands/test.go +++ b/cmd/mattermost/commands/test.go @@ -58,7 +58,7 @@ func webClientTestsCmdF(command *cobra.Command, args []string) error { return serverErr } - api4.Init(a, a.Srv().AppOptions, a.Srv().Router) + api4.Init(a, a.Srv().Router) wsapi.Init(a.Srv()) a.UpdateConfig(setupClientTests) runWebClientTests() @@ -79,7 +79,7 @@ func serverForWebClientTestsCmdF(command *cobra.Command, args []string) error { return serverErr } - api4.Init(a, a.Srv().AppOptions, a.Srv().Router) + api4.Init(a, a.Srv().Router) wsapi.Init(a.Srv()) a.UpdateConfig(setupClientTests) diff --git a/cmd/mattermost/commands/user.go b/cmd/mattermost/commands/user.go index e45bbbe7a98..73f98e1eec6 100644 --- a/cmd/mattermost/commands/user.go +++ b/cmd/mattermost/commands/user.go @@ -13,6 +13,7 @@ import ( "github.com/spf13/cobra" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" ) @@ -305,7 +306,7 @@ func changeUserActiveStatus(a *app.App, user *model.User, userArg string, activa if user.IsSSOUser() { fmt.Println("You must also deactivate this user in the SSO provider or they will be reactivated on next login or sync.") } - updatedUser, err := a.UpdateActive(user, activate) + updatedUser, err := a.UpdateActive(&request.Context{}, user, activate) if err != nil { return fmt.Errorf("Unable to change activation status of user: %v", userArg) } @@ -371,7 +372,7 @@ func userCreateCmdF(command *cobra.Command, args []string) error { Locale: locale, } - ruser, err := a.CreateUser(user) + ruser, err := a.CreateUser(&request.Context{}, user) if ruser == nil { return errors.New("Unable to create user. Error: " + err.Error()) } @@ -775,7 +776,7 @@ func deleteUserCmdF(command *cobra.Command, args []string) error { return err } } else { - if err := a.PermanentDeleteUser(user); err != nil { + if err := a.PermanentDeleteUser(&request.Context{}, user); err != nil { return err } } @@ -816,7 +817,7 @@ func deleteAllUsersCommandF(command *cobra.Command, args []string) error { } } - if err := a.PermanentDeleteAllUsers(); err != nil { + if err := a.PermanentDeleteAllUsers(&request.Context{}); err != nil { return err } CommandPrettyPrintln("All user accounts successfully deleted.") diff --git a/einterfaces/ldap.go b/einterfaces/ldap.go index 305b0150204..a029a29d23c 100644 --- a/einterfaces/ldap.go +++ b/einterfaces/ldap.go @@ -4,11 +4,12 @@ package einterfaces import ( + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" ) type LdapInterface interface { - DoLogin(id string, password string) (*model.User, *model.AppError) + DoLogin(c *request.Context, id string, password string) (*model.User, *model.AppError) GetUser(id string) (*model.User, *model.AppError) GetUserAttributes(id string, attributes []string) (map[string]string, *model.AppError) CheckPassword(id string, password string) *model.AppError @@ -21,7 +22,7 @@ type LdapInterface interface { MigrateIDAttribute(toAttribute string) error GetGroup(groupUID string) (*model.Group, *model.AppError) GetAllGroupsPage(page int, perPage int, opts model.LdapGroupSearchOpts) ([]*model.Group, int, *model.AppError) - FirstLoginSync(user *model.User, userAuthService, userAuthData, email string) *model.AppError + FirstLoginSync(c *request.Context, user *model.User, userAuthService, userAuthData, email string) *model.AppError UpdateProfilePictureIfNecessary(model.User, model.Session) GetADLdapIdFromSAMLId(authData string) string GetSAMLIdFromADLdapId(authData string) string diff --git a/einterfaces/mocks/AppContextInterface.go b/einterfaces/mocks/AppContextInterface.go new file mode 100644 index 00000000000..25183a2a855 --- /dev/null +++ b/einterfaces/mocks/AppContextInterface.go @@ -0,0 +1,118 @@ +// Code generated by mockery v1.0.0. DO NOT EDIT. + +// Regenerate this file using `make einterfaces-mocks`. + +package mocks + +import ( + model "github.com/mattermost/mattermost-server/v5/model" + mock "github.com/stretchr/testify/mock" +) + +// AppContextInterface is an autogenerated mock type for the AppContextInterface type +type AppContextInterface struct { + mock.Mock +} + +// AcceptLanguage provides a mock function with given fields: +func (_m *AppContextInterface) AcceptLanguage() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// IpAddress provides a mock function with given fields: +func (_m *AppContextInterface) IpAddress() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Path provides a mock function with given fields: +func (_m *AppContextInterface) Path() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// RequestId provides a mock function with given fields: +func (_m *AppContextInterface) RequestId() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// Session provides a mock function with given fields: +func (_m *AppContextInterface) Session() *model.Session { + ret := _m.Called() + + var r0 *model.Session + if rf, ok := ret.Get(0).(func() *model.Session); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*model.Session) + } + } + + return r0 +} + +// T provides a mock function with given fields: translationID, args +func (_m *AppContextInterface) T(translationID string, args ...interface{}) string { + var _ca []interface{} + _ca = append(_ca, translationID) + _ca = append(_ca, args...) + ret := _m.Called(_ca...) + + var r0 string + if rf, ok := ret.Get(0).(func(string, ...interface{}) string); ok { + r0 = rf(translationID, args...) + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} + +// UserAgent provides a mock function with given fields: +func (_m *AppContextInterface) UserAgent() string { + ret := _m.Called() + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { + r0 = rf() + } else { + r0 = ret.Get(0).(string) + } + + return r0 +} diff --git a/einterfaces/mocks/LdapInterface.go b/einterfaces/mocks/LdapInterface.go index 031da77e4fd..fa3be959e94 100644 --- a/einterfaces/mocks/LdapInterface.go +++ b/einterfaces/mocks/LdapInterface.go @@ -5,6 +5,7 @@ package mocks import ( + request "github.com/mattermost/mattermost-server/v5/app/request" model "github.com/mattermost/mattermost-server/v5/model" mock "github.com/stretchr/testify/mock" ) @@ -60,13 +61,13 @@ func (_m *LdapInterface) CheckProviderAttributes(LS *model.LdapSettings, ouser * return r0 } -// DoLogin provides a mock function with given fields: id, password -func (_m *LdapInterface) DoLogin(id string, password string) (*model.User, *model.AppError) { - ret := _m.Called(id, password) +// DoLogin provides a mock function with given fields: c, id, password +func (_m *LdapInterface) DoLogin(c *request.Context, id string, password string) (*model.User, *model.AppError) { + ret := _m.Called(c, id, password) var r0 *model.User - if rf, ok := ret.Get(0).(func(string, string) *model.User); ok { - r0 = rf(id, password) + if rf, ok := ret.Get(0).(func(*request.Context, string, string) *model.User); ok { + r0 = rf(c, id, password) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.User) @@ -74,8 +75,8 @@ func (_m *LdapInterface) DoLogin(id string, password string) (*model.User, *mode } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(string, string) *model.AppError); ok { - r1 = rf(id, password) + if rf, ok := ret.Get(1).(func(*request.Context, string, string) *model.AppError); ok { + r1 = rf(c, id, password) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -85,13 +86,13 @@ func (_m *LdapInterface) DoLogin(id string, password string) (*model.User, *mode return r0, r1 } -// FirstLoginSync provides a mock function with given fields: user, userAuthService, userAuthData, email -func (_m *LdapInterface) FirstLoginSync(user *model.User, userAuthService string, userAuthData string, email string) *model.AppError { - ret := _m.Called(user, userAuthService, userAuthData, email) +// FirstLoginSync provides a mock function with given fields: c, user, userAuthService, userAuthData, email +func (_m *LdapInterface) FirstLoginSync(c *request.Context, user *model.User, userAuthService string, userAuthData string, email string) *model.AppError { + ret := _m.Called(c, user, userAuthService, userAuthData, email) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(*model.User, string, string, string) *model.AppError); ok { - r0 = rf(user, userAuthService, userAuthData, email) + if rf, ok := ret.Get(0).(func(*request.Context, *model.User, string, string, string) *model.AppError); ok { + r0 = rf(c, user, userAuthService, userAuthData, email) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) diff --git a/einterfaces/mocks/SamlInterface.go b/einterfaces/mocks/SamlInterface.go index 2e53c6fa371..418c174f80d 100644 --- a/einterfaces/mocks/SamlInterface.go +++ b/einterfaces/mocks/SamlInterface.go @@ -5,6 +5,7 @@ package mocks import ( + request "github.com/mattermost/mattermost-server/v5/app/request" model "github.com/mattermost/mattermost-server/v5/model" mock "github.com/stretchr/testify/mock" ) @@ -67,13 +68,13 @@ func (_m *SamlInterface) ConfigureSP() error { return r0 } -// DoLogin provides a mock function with given fields: encodedXML, relayState -func (_m *SamlInterface) DoLogin(encodedXML string, relayState map[string]string) (*model.User, *model.AppError) { - ret := _m.Called(encodedXML, relayState) +// DoLogin provides a mock function with given fields: c, encodedXML, relayState +func (_m *SamlInterface) DoLogin(c *request.Context, encodedXML string, relayState map[string]string) (*model.User, *model.AppError) { + ret := _m.Called(c, encodedXML, relayState) var r0 *model.User - if rf, ok := ret.Get(0).(func(string, map[string]string) *model.User); ok { - r0 = rf(encodedXML, relayState) + if rf, ok := ret.Get(0).(func(*request.Context, string, map[string]string) *model.User); ok { + r0 = rf(c, encodedXML, relayState) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.User) @@ -81,8 +82,8 @@ func (_m *SamlInterface) DoLogin(encodedXML string, relayState map[string]string } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(string, map[string]string) *model.AppError); ok { - r1 = rf(encodedXML, relayState) + if rf, ok := ret.Get(1).(func(*request.Context, string, map[string]string) *model.AppError); ok { + r1 = rf(c, encodedXML, relayState) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) diff --git a/einterfaces/saml.go b/einterfaces/saml.go index 4516b987d4c..b9900e0fcf3 100644 --- a/einterfaces/saml.go +++ b/einterfaces/saml.go @@ -4,13 +4,14 @@ package einterfaces import ( + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" ) type SamlInterface interface { ConfigureSP() error BuildRequest(relayState string) (*model.SamlAuthRequest, *model.AppError) - DoLogin(encodedXML string, relayState map[string]string) (*model.User, *model.AppError) + DoLogin(c *request.Context, encodedXML string, relayState map[string]string) (*model.User, *model.AppError) GetMetadata() (string, *model.AppError) CheckProviderAttributes(SS *model.SamlSettings, ouser *model.User, patch *model.UserPatch) string } diff --git a/jobs/active_users/worker.go b/jobs/active_users/worker.go index 72d318d3d1c..f963acff1f6 100644 --- a/jobs/active_users/worker.go +++ b/jobs/active_users/worker.go @@ -27,7 +27,8 @@ type Worker struct { } func init() { - app.RegisterJobsActiveUsersInterface(func(a *app.App) tjobs.ActiveUsersJobInterface { + app.RegisterJobsActiveUsersInterface(func(s *app.Server) tjobs.ActiveUsersJobInterface { + a := app.New(app.ServerConnector(s)) return &ActiveUsersJobInterfaceImpl{a} }) } diff --git a/jobs/expirynotify/expirynotify.go b/jobs/expirynotify/expirynotify.go index 3bd966e29b7..cceaf07a356 100644 --- a/jobs/expirynotify/expirynotify.go +++ b/jobs/expirynotify/expirynotify.go @@ -13,7 +13,8 @@ type ExpiryNotifyJobInterfaceImpl struct { } func init() { - app.RegisterJobsExpiryNotifyJobInterface(func(a *app.App) tjobs.ExpiryNotifyJobInterface { + app.RegisterJobsExpiryNotifyJobInterface(func(s *app.Server) tjobs.ExpiryNotifyJobInterface { + a := app.New(app.ServerConnector(s)) return &ExpiryNotifyJobInterfaceImpl{a} }) } diff --git a/jobs/export_delete/worker.go b/jobs/export_delete/worker.go index 78834ddba62..0f649fa70f0 100644 --- a/jobs/export_delete/worker.go +++ b/jobs/export_delete/worker.go @@ -15,7 +15,8 @@ import ( ) func init() { - app.RegisterJobsExportDeleteInterface(func(a *app.App) tjobs.ExportDeleteInterface { + app.RegisterJobsExportDeleteInterface(func(s *app.Server) tjobs.ExportDeleteInterface { + a := app.New(app.ServerConnector(s)) return &ExportDeleteInterfaceImpl{a} }) } diff --git a/jobs/export_process/worker.go b/jobs/export_process/worker.go index f1f81588178..8732b315930 100644 --- a/jobs/export_process/worker.go +++ b/jobs/export_process/worker.go @@ -15,7 +15,8 @@ import ( ) func init() { - app.RegisterJobsExportProcessInterface(func(a *app.App) tjobs.ExportProcessInterface { + app.RegisterJobsExportProcessInterface(func(s *app.Server) tjobs.ExportProcessInterface { + a := app.New(app.ServerConnector(s)) return &ExportProcessInterfaceImpl{a} }) } diff --git a/jobs/import_delete/worker.go b/jobs/import_delete/worker.go index e50e2255075..d8bc1b8a2b6 100644 --- a/jobs/import_delete/worker.go +++ b/jobs/import_delete/worker.go @@ -17,7 +17,8 @@ import ( ) func init() { - app.RegisterJobsImportDeleteInterface(func(a *app.App) tjobs.ImportDeleteInterface { + app.RegisterJobsImportDeleteInterface(func(s *app.Server) tjobs.ImportDeleteInterface { + a := app.New(app.ServerConnector(s)) return &ImportDeleteInterfaceImpl{a} }) } diff --git a/jobs/import_process/worker.go b/jobs/import_process/worker.go index 942e9366711..b10c040e1d3 100644 --- a/jobs/import_process/worker.go +++ b/jobs/import_process/worker.go @@ -13,6 +13,7 @@ import ( "strconv" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/jobs" tjobs "github.com/mattermost/mattermost-server/v5/jobs/interfaces" "github.com/mattermost/mattermost-server/v5/model" @@ -21,7 +22,8 @@ import ( ) func init() { - app.RegisterJobsImportProcessInterface(func(a *app.App) tjobs.ImportProcessInterface { + app.RegisterJobsImportProcessInterface(func(s *app.Server) tjobs.ImportProcessInterface { + a := app.New(app.ServerConnector(s)) return &ImportProcessInterfaceImpl{a} }) } @@ -37,6 +39,7 @@ type ImportProcessWorker struct { jobsChan chan model.Job jobServer *jobs.JobServer app *app.App + appContext *request.Context } func (i *ImportProcessInterfaceImpl) MakeWorker() model.Worker { @@ -47,6 +50,7 @@ func (i *ImportProcessInterfaceImpl) MakeWorker() model.Worker { jobsChan: make(chan model.Job), jobServer: i.app.Srv().Jobs, app: i.app, + appContext: &request.Context{}, } } @@ -165,7 +169,7 @@ func (w *ImportProcessWorker) doJob(job *model.Job) { } // do the actual import. - appErr, lineNumber := w.app.BulkImportWithPath(jsonFile, false, runtime.NumCPU(), filepath.Join(dir, app.ExportDataDir)) + appErr, lineNumber := w.app.BulkImportWithPath(w.appContext, jsonFile, false, runtime.NumCPU(), filepath.Join(dir, app.ExportDataDir)) if appErr != nil { job.Data["line_number"] = strconv.Itoa(lineNumber) w.setJobError(job, appErr) diff --git a/jobs/product_notices/product_notices.go b/jobs/product_notices/product_notices.go index ba8dd619e7e..41dcee7dde2 100644 --- a/jobs/product_notices/product_notices.go +++ b/jobs/product_notices/product_notices.go @@ -13,7 +13,8 @@ type ProductNoticesJobInterfaceImpl struct { } func init() { - app.RegisterProductNoticesJobInterface(func(a *app.App) tjobs.ProductNoticesJobInterface { + app.RegisterProductNoticesJobInterface(func(s *app.Server) tjobs.ProductNoticesJobInterface { + a := app.New(app.ServerConnector(s)) return &ProductNoticesJobInterfaceImpl{a} }) } diff --git a/jobs/resend_invitation_email/resend_invitation_email.go b/jobs/resend_invitation_email/resend_invitation_email.go index 4257cb5bc09..0d07d97d6ee 100644 --- a/jobs/resend_invitation_email/resend_invitation_email.go +++ b/jobs/resend_invitation_email/resend_invitation_email.go @@ -12,7 +12,8 @@ type ResendInvitationEmailJobInterfaceImpl struct { } func init() { - app.RegisterJobsResendInvitationEmailInterface(func(a *app.App) ejobs.ResendInvitationEmailJobInterface { + app.RegisterJobsResendInvitationEmailInterface(func(s *app.Server) ejobs.ResendInvitationEmailJobInterface { + a := app.New(app.ServerConnector(s)) return &ResendInvitationEmailJobInterfaceImpl{a} }) } diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index 9b5bc5f0098..142caadbcb8 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -94,7 +94,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { } channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: createdTeam.Id} - if _, err := c.App.CreateChannel(channel, false); err != nil { + if _, err := c.App.CreateChannel(c.AppContext, channel, false); err != nil { c.Err = err return } diff --git a/migrations/helper_test.go b/migrations/helper_test.go index 4aad6ae2963..a55656e91e8 100644 --- a/migrations/helper_test.go +++ b/migrations/helper_test.go @@ -7,6 +7,7 @@ import ( "os" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/store/localcachelayer" @@ -15,6 +16,7 @@ import ( type TestHelper struct { App *app.App + Context *request.Context Server *app.Server BasicTeam *model.Team BasicUser *model.User @@ -40,6 +42,7 @@ func setupTestHelper(enterprise bool) *TestHelper { var options []app.Option options = append(options, app.ConfigStore(memoryStore)) options = append(options, app.StoreOverride(mainHelper.Store)) + options = append(options, app.SkipPostInitializiation()) s, err := app.NewServer(options...) if err != nil { @@ -52,8 +55,9 @@ func setupTestHelper(enterprise bool) *TestHelper { } th := &TestHelper{ - App: app.New(app.ServerConnector(s)), - Server: s, + App: app.New(app.ServerConnector(s)), + Context: &request.Context{}, + Server: s, } th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) @@ -76,6 +80,8 @@ func setupTestHelper(enterprise bool) *TestHelper { if enterprise { th.App.Srv().SetLicense(model.NewTestLicense()) + th.App.Srv().Jobs.InitWorkers() + th.App.Srv().Jobs.InitSchedulers() } else { th.App.Srv().SetLicense(nil) } @@ -122,7 +128,7 @@ func (th *TestHelper) CreateTeam() *model.Team { utils.DisableDebugLogForTest() var err *model.AppError - if team, err = th.App.CreateTeam(team); err != nil { + if team, err = th.App.CreateTeam(th.Context, team); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -142,7 +148,7 @@ func (th *TestHelper) CreateUser() *model.User { utils.DisableDebugLogForTest() var err *model.AppError - if user, err = th.App.CreateUser(user); err != nil { + if user, err = th.App.CreateUser(th.Context, user); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -166,7 +172,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType string) *model utils.DisableDebugLogForTest() var err *model.AppError - if channel, err = th.App.CreateChannel(channel, true); err != nil { + if channel, err = th.App.CreateChannel(th.Context, channel, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -177,7 +183,7 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel { utils.DisableDebugLogForTest() var err *model.AppError var channel *model.Channel - if channel, err = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, user.Id); err != nil { + if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -196,7 +202,7 @@ func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post { utils.DisableDebugLogForTest() var err *model.AppError - if post, err = th.App.CreatePost(post, channel, false, true); err != nil { + if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil { panic(err) } utils.EnableDebugLogForTest() @@ -206,7 +212,7 @@ func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post { func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - _, err := th.App.JoinUserToTeam(team, user, "") + _, err := th.App.JoinUserToTeam(th.Context, team, user, "") if err != nil { panic(err) } diff --git a/plugin/scheduler/plugin.go b/plugin/scheduler/plugin.go index 50b08639803..4bd07f3e157 100644 --- a/plugin/scheduler/plugin.go +++ b/plugin/scheduler/plugin.go @@ -13,7 +13,8 @@ type PluginsJobInterfaceImpl struct { } func init() { - app.RegisterJobsPluginsJobInterface(func(a *app.App) tjobs.PluginsJobInterface { + app.RegisterJobsPluginsJobInterface(func(s *app.Server) tjobs.PluginsJobInterface { + a := app.New(app.ServerConnector(s)) return &PluginsJobInterfaceImpl{a} }) } diff --git a/services/remotecluster/recv.go b/services/remotecluster/recv.go index cafa7d206c7..2bebcbee5d6 100644 --- a/services/remotecluster/recv.go +++ b/services/remotecluster/recv.go @@ -6,6 +6,7 @@ package remotecluster import ( "fmt" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) @@ -13,7 +14,7 @@ import ( // ReceiveIncomingMsg is called by the Rest API layer, or websocket layer (future), when a Remote Cluster // message is received. Here we route the message to any topic listeners. // `rc` and `msg` cannot be nil. -func (rcs *Service) ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.RemoteClusterMsg) Response { +func (rcs *Service) ReceiveIncomingMsg(c *request.Context, rc *model.RemoteCluster, msg model.RemoteClusterMsg) Response { rcs.mux.RLock() defer rcs.mux.RUnlock() @@ -31,7 +32,7 @@ func (rcs *Service) ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.Remote listeners := rcs.getTopicListeners(msg.Topic) for _, l := range listeners { - if err := callback(l, msg, &rcSanitized, &response); err != nil { + if err := callback(l, c, msg, &rcSanitized, &response); err != nil { rcs.server.GetLogger().Log(mlog.LvlRemoteClusterServiceError, "Error from remote cluster message listener", mlog.String("msgId", msg.Id), mlog.String("topic", msg.Topic), mlog.String("remote", rc.DisplayName), mlog.Err(err)) @@ -42,12 +43,12 @@ func (rcs *Service) ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.Remote return response } -func callback(listener TopicListener, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) (err error) { +func callback(listener TopicListener, c *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } }() - err = listener(msg, rc, resp) + err = listener(c, msg, rc, resp) return } diff --git a/services/remotecluster/service.go b/services/remotecluster/service.go index e8726bc5981..c0f7c0e5f42 100644 --- a/services/remotecluster/service.go +++ b/services/remotecluster/service.go @@ -10,6 +10,7 @@ import ( "sync" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -65,12 +66,12 @@ type RemoteClusterServiceIFace interface { SendFile(ctx context.Context, us *model.UploadSession, fi *model.FileInfo, rc *model.RemoteCluster, rp ReaderProvider, f SendFileResultFunc) error SendProfileImage(ctx context.Context, userID string, rc *model.RemoteCluster, provider ProfileImageProvider, f SendProfileImageResultFunc) error AcceptInvitation(invite *model.RemoteClusterInvite, name string, displayName string, creatorId string, teamId string, siteURL string) (*model.RemoteCluster, error) - ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.RemoteClusterMsg) Response + ReceiveIncomingMsg(c *request.Context, rc *model.RemoteCluster, msg model.RemoteClusterMsg) Response } // TopicListener is a callback signature used to listen for incoming messages for // a specific topic. -type TopicListener func(msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error +type TopicListener func(c *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error // ConnectionStateListener is used to listen to remote cluster connection state changes. type ConnectionStateListener func(rc *model.RemoteCluster, online bool) diff --git a/services/remotecluster/service_test.go b/services/remotecluster/service_test.go index 2895d6c475e..b0b188aadae 100644 --- a/services/remotecluster/service_test.go +++ b/services/remotecluster/service_test.go @@ -10,21 +10,22 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" ) func TestService_AddTopicListener(t *testing.T) { var count int32 - l1 := func(msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { + l1 := func(_ *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { atomic.AddInt32(&count, 1) return nil } - l2 := func(msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { + l2 := func(_ *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { atomic.AddInt32(&count, 1) return nil } - l3 := func(msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { + l3 := func(_ *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, resp *Response) error { atomic.AddInt32(&count, 1) return nil } @@ -46,26 +47,28 @@ func TestService_AddTopicListener(t *testing.T) { msg1 := model.RemoteClusterMsg{Topic: "test"} msg2 := model.RemoteClusterMsg{Topic: "different"} - service.ReceiveIncomingMsg(rc, msg1) + c := request.EmptyContext() + + service.ReceiveIncomingMsg(c, rc, msg1) assert.Equal(t, int32(2), atomic.LoadInt32(&count)) - service.ReceiveIncomingMsg(rc, msg2) + service.ReceiveIncomingMsg(c, rc, msg2) assert.Equal(t, int32(3), atomic.LoadInt32(&count)) service.RemoveTopicListener(l1id) - service.ReceiveIncomingMsg(rc, msg1) + service.ReceiveIncomingMsg(c, rc, msg1) assert.Equal(t, int32(4), atomic.LoadInt32(&count)) service.RemoveTopicListener(l2id) - service.ReceiveIncomingMsg(rc, msg1) + service.ReceiveIncomingMsg(c, rc, msg1) assert.Equal(t, int32(4), atomic.LoadInt32(&count)) - service.ReceiveIncomingMsg(rc, msg2) + service.ReceiveIncomingMsg(c, rc, msg2) assert.Equal(t, int32(5), atomic.LoadInt32(&count)) service.RemoveTopicListener(l3id) - service.ReceiveIncomingMsg(rc, msg1) - service.ReceiveIncomingMsg(rc, msg2) + service.ReceiveIncomingMsg(c, rc, msg1) + service.ReceiveIncomingMsg(c, rc, msg2) assert.Equal(t, int32(5), atomic.LoadInt32(&count)) listeners = service.getTopicListeners("test") diff --git a/services/sharedchannel/attachment.go b/services/sharedchannel/attachment.go index 4bd2a3085dc..3ee6b5c67a0 100644 --- a/services/sharedchannel/attachment.go +++ b/services/sharedchannel/attachment.go @@ -10,6 +10,7 @@ import ( "fmt" "sync" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -158,7 +159,7 @@ func (scs *Service) sendAttachmentForRemote(fi *model.FileInfo, post *model.Post // onReceiveUploadCreate is called when a message requesting to create an upload session is received. An upload session is // created and the id returned in the response. -func (scs *Service) onReceiveUploadCreate(msg model.RemoteClusterMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { +func (scs *Service) onReceiveUploadCreate(_ *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { var us model.UploadSession if err := json.Unmarshal(msg.Payload, &us); err != nil { diff --git a/services/sharedchannel/channelinvite.go b/services/sharedchannel/channelinvite.go index 01ad2d3243d..88c3c08919f 100644 --- a/services/sharedchannel/channelinvite.go +++ b/services/sharedchannel/channelinvite.go @@ -9,6 +9,7 @@ import ( "fmt" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -110,7 +111,7 @@ func combineErrors(err error, serror string) string { return sb.String() } -func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model.RemoteCluster, _ *remotecluster.Response) error { +func (scs *Service) onReceiveChannelInvite(c *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, _ *remotecluster.Response) error { if len(msg.Payload) == 0 { return nil } @@ -131,7 +132,7 @@ func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model // create channel if it doesn't exist; the channel may already exist, such as if it was shared then unshared at some point. channel, err := scs.server.GetStore().Channel().Get(invite.ChannelId, true) if err != nil { - if channel, err = scs.handleChannelCreation(invite, rc); err != nil { + if channel, err = scs.handleChannelCreation(c, invite, rc); err != nil { return err } } @@ -178,9 +179,9 @@ func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model return nil } -func (scs *Service) handleChannelCreation(invite channelInviteMsg, rc *model.RemoteCluster) (*model.Channel, error) { +func (scs *Service) handleChannelCreation(c *request.Context, invite channelInviteMsg, rc *model.RemoteCluster) (*model.Channel, error) { if invite.Type == model.CHANNEL_DIRECT { - return scs.createDirectChannel(invite) + return scs.createDirectChannel(c, invite) } channelNew := &model.Channel{ @@ -196,7 +197,7 @@ func (scs *Service) handleChannelCreation(invite channelInviteMsg, rc *model.Rem } // check user perms? - channel, appErr := scs.app.CreateChannelWithUser(channelNew, rc.CreatorId) + channel, appErr := scs.app.CreateChannelWithUser(c, channelNew, rc.CreatorId) if appErr != nil { return nil, fmt.Errorf("cannot create channel `%s`: %w", invite.ChannelId, appErr) } @@ -204,12 +205,12 @@ func (scs *Service) handleChannelCreation(invite channelInviteMsg, rc *model.Rem return channel, nil } -func (scs *Service) createDirectChannel(invite channelInviteMsg) (*model.Channel, error) { +func (scs *Service) createDirectChannel(c *request.Context, invite channelInviteMsg) (*model.Channel, error) { if len(invite.DirectParticipantIDs) != 2 { return nil, fmt.Errorf("cannot create direct channel `%s` insufficient participant count `%d`", invite.ChannelId, len(invite.DirectParticipantIDs)) } - channel, err := scs.app.GetOrCreateDirectChannel(invite.DirectParticipantIDs[0], invite.DirectParticipantIDs[1], model.WithID(invite.ChannelId)) + channel, err := scs.app.GetOrCreateDirectChannel(c, invite.DirectParticipantIDs[0], invite.DirectParticipantIDs[1], model.WithID(invite.ChannelId)) if err != nil { return nil, fmt.Errorf("cannot create direct channel `%s`: %w", invite.ChannelId, err) } diff --git a/services/sharedchannel/channelinvite_test.go b/services/sharedchannel/channelinvite_test.go index 38d2bddcdcc..be9d5d3c054 100644 --- a/services/sharedchannel/channelinvite_test.go +++ b/services/sharedchannel/channelinvite_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock" "github.com/mattermost/mattermost-server/v5/shared/mlog" @@ -26,6 +27,8 @@ type mockLogger struct { func (ml *mockLogger) Log(level mlog.LogLevel, s string, flds ...mlog.Field) {} func TestOnReceiveChannelInvite(t *testing.T) { + c := request.EmptyContext() + t.Run("when msg payload is empty, it does nothing", func(t *testing.T) { mockServer := &MockServerIface{} mockLogger := &mockLogger{} @@ -43,7 +46,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { remoteCluster := &model.RemoteCluster{} msg := model.RemoteClusterMsg{} - err := scs.onReceiveChannelInvite(msg, remoteCluster, nil) + err := scs.onReceiveChannelInvite(c, msg, remoteCluster, nil) require.NoError(t, err) mockStore.AssertNotCalled(t, "Channel") }) @@ -104,7 +107,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { mockApp.On("PatchChannelModerationsForChannel", channel, readonlyChannelModerations).Return(nil, nil) defer mockApp.AssertExpectations(t) - err = scs.onReceiveChannelInvite(msg, remoteCluster, nil) + err = scs.onReceiveChannelInvite(c, msg, remoteCluster, nil) require.NoError(t, err) }) @@ -145,7 +148,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { mockApp.On("PatchChannelModerationsForChannel", channel, mock.Anything).Return(nil, appErr) defer mockApp.AssertExpectations(t) - err = scs.onReceiveChannelInvite(msg, remoteCluster, nil) + err = scs.onReceiveChannelInvite(c, msg, remoteCluster, nil) require.Error(t, err) assert.Equal(t, fmt.Sprintf("cannot make channel readonly `%s`: foo: bar, boom", invitation.ChannelId), err.Error()) }) @@ -188,10 +191,10 @@ func TestOnReceiveChannelInvite(t *testing.T) { mockServer = scs.server.(*MockServerIface) mockServer.On("GetStore").Return(mockStore) - mockApp.On("GetOrCreateDirectChannel", invitation.DirectParticipantIDs[0], invitation.DirectParticipantIDs[1], mock.AnythingOfType("model.ChannelOption")).Return(channel, nil) + mockApp.On("GetOrCreateDirectChannel", mock.AnythingOfType("*request.Context"), invitation.DirectParticipantIDs[0], invitation.DirectParticipantIDs[1], mock.AnythingOfType("model.ChannelOption")).Return(channel, nil) defer mockApp.AssertExpectations(t) - err = scs.onReceiveChannelInvite(msg, remoteCluster, nil) + err = scs.onReceiveChannelInvite(c, msg, remoteCluster, nil) require.NoError(t, err) }) } diff --git a/services/sharedchannel/mock_AppIface_test.go b/services/sharedchannel/mock_AppIface_test.go index 1420f6c9a66..6090808c628 100644 --- a/services/sharedchannel/mock_AppIface_test.go +++ b/services/sharedchannel/mock_AppIface_test.go @@ -9,6 +9,8 @@ import ( mock "github.com/stretchr/testify/mock" model "github.com/mattermost/mattermost-server/v5/model" + + request "github.com/mattermost/mattermost-server/v5/app/request" ) // MockAppIface is an autogenerated mock type for the AppIface type @@ -41,13 +43,13 @@ func (_m *MockAppIface) AddUserToChannel(user *model.User, channel *model.Channe return r0, r1 } -// AddUserToTeamByTeamId provides a mock function with given fields: teamId, user -func (_m *MockAppIface) AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError { - ret := _m.Called(teamId, user) +// AddUserToTeamByTeamId provides a mock function with given fields: c, teamId, user +func (_m *MockAppIface) AddUserToTeamByTeamId(c *request.Context, teamId string, user *model.User) *model.AppError { + ret := _m.Called(c, teamId, user) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(string, *model.User) *model.AppError); ok { - r0 = rf(teamId, user) + if rf, ok := ret.Get(0).(func(*request.Context, string, *model.User) *model.AppError); ok { + r0 = rf(c, teamId, user) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -57,13 +59,13 @@ func (_m *MockAppIface) AddUserToTeamByTeamId(teamId string, user *model.User) * return r0 } -// CreateChannelWithUser provides a mock function with given fields: channel, userId -func (_m *MockAppIface) CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channel, *model.AppError) { - ret := _m.Called(channel, userId) +// CreateChannelWithUser provides a mock function with given fields: c, channel, userId +func (_m *MockAppIface) CreateChannelWithUser(c *request.Context, channel *model.Channel, userId string) (*model.Channel, *model.AppError) { + ret := _m.Called(c, channel, userId) var r0 *model.Channel - if rf, ok := ret.Get(0).(func(*model.Channel, string) *model.Channel); ok { - r0 = rf(channel, userId) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Channel, string) *model.Channel); ok { + r0 = rf(c, channel, userId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Channel) @@ -71,8 +73,8 @@ func (_m *MockAppIface) CreateChannelWithUser(channel *model.Channel, userId str } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.Channel, string) *model.AppError); ok { - r1 = rf(channel, userId) + if rf, ok := ret.Get(1).(func(*request.Context, *model.Channel, string) *model.AppError); ok { + r1 = rf(c, channel, userId) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -82,13 +84,13 @@ func (_m *MockAppIface) CreateChannelWithUser(channel *model.Channel, userId str return r0, r1 } -// CreatePost provides a mock function with given fields: post, channel, triggerWebhooks, setOnline -func (_m *MockAppIface) CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (*model.Post, *model.AppError) { - ret := _m.Called(post, channel, triggerWebhooks, setOnline) +// CreatePost provides a mock function with given fields: c, post, channel, triggerWebhooks, setOnline +func (_m *MockAppIface) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (*model.Post, *model.AppError) { + ret := _m.Called(c, post, channel, triggerWebhooks, setOnline) var r0 *model.Post - if rf, ok := ret.Get(0).(func(*model.Post, *model.Channel, bool, bool) *model.Post); ok { - r0 = rf(post, channel, triggerWebhooks, setOnline) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Post, *model.Channel, bool, bool) *model.Post); ok { + r0 = rf(c, post, channel, triggerWebhooks, setOnline) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Post) @@ -96,8 +98,8 @@ func (_m *MockAppIface) CreatePost(post *model.Post, channel *model.Channel, tri } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.Post, *model.Channel, bool, bool) *model.AppError); ok { - r1 = rf(post, channel, triggerWebhooks, setOnline) + if rf, ok := ret.Get(1).(func(*request.Context, *model.Post, *model.Channel, bool, bool) *model.AppError); ok { + r1 = rf(c, post, channel, triggerWebhooks, setOnline) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -157,13 +159,13 @@ func (_m *MockAppIface) DeletePost(postID string, deleteByID string) (*model.Pos return r0, r1 } -// DeleteReactionForPost provides a mock function with given fields: reaction -func (_m *MockAppIface) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { - ret := _m.Called(reaction) +// DeleteReactionForPost provides a mock function with given fields: c, reaction +func (_m *MockAppIface) DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError { + ret := _m.Called(c, reaction) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(*model.Reaction) *model.AppError); ok { - r0 = rf(reaction) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Reaction) *model.AppError); ok { + r0 = rf(c, reaction) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -198,20 +200,20 @@ func (_m *MockAppIface) FileReader(path string) (filestore.ReadCloseSeeker, *mod return r0, r1 } -// GetOrCreateDirectChannel provides a mock function with given fields: userId, otherUserId, channelOptions -func (_m *MockAppIface) GetOrCreateDirectChannel(userId string, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +// GetOrCreateDirectChannel provides a mock function with given fields: c, userId, otherUserId, channelOptions +func (_m *MockAppIface) GetOrCreateDirectChannel(c *request.Context, userId string, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { _va := make([]interface{}, len(channelOptions)) for _i := range channelOptions { _va[_i] = channelOptions[_i] } var _ca []interface{} - _ca = append(_ca, userId, otherUserId) + _ca = append(_ca, c, userId, otherUserId) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *model.Channel - if rf, ok := ret.Get(0).(func(string, string, ...model.ChannelOption) *model.Channel); ok { - r0 = rf(userId, otherUserId, channelOptions...) + if rf, ok := ret.Get(0).(func(*request.Context, string, string, ...model.ChannelOption) *model.Channel); ok { + r0 = rf(c, userId, otherUserId, channelOptions...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Channel) @@ -219,8 +221,8 @@ func (_m *MockAppIface) GetOrCreateDirectChannel(userId string, otherUserId stri } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(string, string, ...model.ChannelOption) *model.AppError); ok { - r1 = rf(userId, otherUserId, channelOptions...) + if rf, ok := ret.Get(1).(func(*request.Context, string, string, ...model.ChannelOption) *model.AppError); ok { + r1 = rf(c, userId, otherUserId, channelOptions...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -329,13 +331,13 @@ func (_m *MockAppIface) PermanentDeleteChannel(channel *model.Channel) *model.Ap return r0 } -// SaveReactionForPost provides a mock function with given fields: reaction -func (_m *MockAppIface) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { - ret := _m.Called(reaction) +// SaveReactionForPost provides a mock function with given fields: c, reaction +func (_m *MockAppIface) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) { + ret := _m.Called(c, reaction) var r0 *model.Reaction - if rf, ok := ret.Get(0).(func(*model.Reaction) *model.Reaction); ok { - r0 = rf(reaction) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Reaction) *model.Reaction); ok { + r0 = rf(c, reaction) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Reaction) @@ -343,8 +345,8 @@ func (_m *MockAppIface) SaveReactionForPost(reaction *model.Reaction) (*model.Re } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.Reaction) *model.AppError); ok { - r1 = rf(reaction) + if rf, ok := ret.Get(1).(func(*request.Context, *model.Reaction) *model.AppError); ok { + r1 = rf(c, reaction) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -370,13 +372,13 @@ func (_m *MockAppIface) SendEphemeralPost(userId string, post *model.Post) *mode return r0 } -// UpdatePost provides a mock function with given fields: post, safeUpdate -func (_m *MockAppIface) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { - ret := _m.Called(post, safeUpdate) +// UpdatePost provides a mock function with given fields: c, post, safeUpdate +func (_m *MockAppIface) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { + ret := _m.Called(c, post, safeUpdate) var r0 *model.Post - if rf, ok := ret.Get(0).(func(*model.Post, bool) *model.Post); ok { - r0 = rf(post, safeUpdate) + if rf, ok := ret.Get(0).(func(*request.Context, *model.Post, bool) *model.Post); ok { + r0 = rf(c, post, safeUpdate) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Post) @@ -384,8 +386,8 @@ func (_m *MockAppIface) UpdatePost(post *model.Post, safeUpdate bool) (*model.Po } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.Post, bool) *model.AppError); ok { - r1 = rf(post, safeUpdate) + if rf, ok := ret.Get(1).(func(*request.Context, *model.Post, bool) *model.AppError); ok { + r1 = rf(c, post, safeUpdate) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) diff --git a/services/sharedchannel/service.go b/services/sharedchannel/service.go index 276581aa31a..4206f3d3c4b 100644 --- a/services/sharedchannel/service.go +++ b/services/sharedchannel/service.go @@ -10,6 +10,7 @@ import ( "sync" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" "github.com/mattermost/mattermost-server/v5/shared/filestore" @@ -43,16 +44,16 @@ type ServerIface interface { type AppIface interface { SendEphemeralPost(userId string, post *model.Post) *model.Post - CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channel, *model.AppError) - GetOrCreateDirectChannel(userId, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) + CreateChannelWithUser(c *request.Context, channel *model.Channel, userId string) (*model.Channel, *model.AppError) + GetOrCreateDirectChannel(c *request.Context, userId, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) - AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError + AddUserToTeamByTeamId(c *request.Context, teamId string, user *model.User) *model.AppError PermanentDeleteChannel(channel *model.Channel) *model.AppError - CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) - UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) + CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) + UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) DeletePost(postID, deleteByID string) (*model.Post, *model.AppError) - SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) - DeleteReactionForPost(reaction *model.Reaction) *model.AppError + SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) + DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) diff --git a/services/sharedchannel/sync_recv.go b/services/sharedchannel/sync_recv.go index 452e97253ce..10a1ee82276 100644 --- a/services/sharedchannel/sync_recv.go +++ b/services/sharedchannel/sync_recv.go @@ -11,12 +11,13 @@ import ( "strconv" "strings" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" "github.com/mattermost/mattermost-server/v5/shared/mlog" ) -func (scs *Service) onReceiveSyncMessage(msg model.RemoteClusterMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { +func (scs *Service) onReceiveSyncMessage(c *request.Context, msg model.RemoteClusterMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { if msg.Topic != TopicSync { return fmt.Errorf("wrong topic, expected `%s`, got `%s`", TopicSync, msg.Topic) } @@ -43,10 +44,10 @@ func (scs *Service) onReceiveSyncMessage(msg model.RemoteClusterMsg, rc *model.R mlog.Int("sync_msg_count", len(syncMessages)), ) - return scs.processSyncMessages(syncMessages, rc, response) + return scs.processSyncMessages(c, syncMessages, rc, response) } -func (scs *Service) processSyncMessages(syncMessages []syncMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { +func (scs *Service) processSyncMessages(c *request.Context, syncMessages []syncMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { var channel *model.Channel var team *model.Team @@ -73,7 +74,7 @@ func (scs *Service) processSyncMessages(syncMessages []syncMsg, rc *model.Remote // add/update users before posts for _, user := range sm.Users { - if userSaved, err := scs.upsertSyncUser(user, channel, rc); err != nil { + if userSaved, err := scs.upsertSyncUser(c, user, channel, rc); err != nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceError, "Error upserting sync user", mlog.String("post_id", sm.PostId), mlog.String("channel_id", sm.ChannelId), @@ -120,7 +121,7 @@ func (scs *Service) processSyncMessages(syncMessages []syncMsg, rc *model.Remote } // add/update post - rpost, err := scs.upsertSyncPost(sm.Post, channel, rc) + rpost, err := scs.upsertSyncPost(c, sm.Post, channel, rc) if err != nil { postErrors = append(postErrors, sm.Post.Id) scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceError, "Error upserting sync post", @@ -135,7 +136,7 @@ func (scs *Service) processSyncMessages(syncMessages []syncMsg, rc *model.Remote // add/remove reactions for _, reaction := range sm.Reactions { - if _, err := scs.upsertSyncReaction(reaction, rc); err != nil { + if _, err := scs.upsertSyncReaction(c, reaction, rc); err != nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceError, "Error upserting sync reaction", mlog.String("user_id", reaction.UserId), mlog.String("post_id", reaction.PostId), @@ -169,7 +170,7 @@ func (scs *Service) processSyncMessages(syncMessages []syncMsg, rc *model.Remote return nil } -func (scs *Service) upsertSyncUser(user *model.User, channel *model.Channel, rc *model.RemoteCluster) (*model.User, error) { +func (scs *Service) upsertSyncUser(c *request.Context, user *model.User, channel *model.Channel, rc *model.RemoteCluster) (*model.User, error) { var err error if user.RemoteId == nil || *user.RemoteId == "" { user.RemoteId = model.NewString(rc.RemoteId) @@ -212,7 +213,7 @@ func (scs *Service) upsertSyncUser(user *model.User, channel *model.Channel, rc // Instead of undoing what succeeded on any failure we simply do all steps each // time. AddUserToChannel & AddUserToTeamByTeamId do not error if user was already // added and exit quickly. - if err := scs.app.AddUserToTeamByTeamId(channel.TeamId, userSaved); err != nil { + if err := scs.app.AddUserToTeamByTeamId(c, channel.TeamId, userSaved); err != nil { return nil, fmt.Errorf("error adding sync user to Team: %w", err) } @@ -329,7 +330,7 @@ func (scs *Service) updateSyncUser(patch *model.UserPatch, user *model.User, cha return nil, fmt.Errorf("error updating sync user %s: %w", user.Id, err) } -func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc *model.RemoteCluster) (*model.Post, error) { +func (scs *Service) upsertSyncPost(c *request.Context, post *model.Post, channel *model.Channel, rc *model.RemoteCluster) (*model.Post, error) { var appErr *model.AppError post.RemoteId = model.NewString(rc.RemoteId) @@ -343,7 +344,7 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc if rpost == nil { // post doesn't exist; create new one - rpost, appErr = scs.app.CreatePost(post, channel, true, true) + rpost, appErr = scs.app.CreatePost(c, post, channel, true, true) scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceDebug, "Created sync post", mlog.String("post_id", post.Id), mlog.String("channel_id", post.ChannelId), @@ -357,7 +358,7 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc ) } else if post.EditAt > rpost.EditAt || post.Message != rpost.Message { // update post - rpost, appErr = scs.app.UpdatePost(post, false) + rpost, appErr = scs.app.UpdatePost(c, post, false) scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceDebug, "Updated sync post", mlog.String("post_id", post.Id), mlog.String("channel_id", post.ChannelId), @@ -377,16 +378,16 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc return rpost, rerr } -func (scs *Service) upsertSyncReaction(reaction *model.Reaction, rc *model.RemoteCluster) (*model.Reaction, error) { +func (scs *Service) upsertSyncReaction(c *request.Context, reaction *model.Reaction, rc *model.RemoteCluster) (*model.Reaction, error) { savedReaction := reaction var appErr *model.AppError reaction.RemoteId = model.NewString(rc.RemoteId) if reaction.DeleteAt == 0 { - savedReaction, appErr = scs.app.SaveReactionForPost(reaction) + savedReaction, appErr = scs.app.SaveReactionForPost(c, reaction) } else { - appErr = scs.app.DeleteReactionForPost(reaction) + appErr = scs.app.DeleteReactionForPost(c, reaction) } var err error diff --git a/services/sharedchannel/sync_send.go b/services/sharedchannel/sync_send.go index c4c7b7e6210..39c1c4305e1 100644 --- a/services/sharedchannel/sync_send.go +++ b/services/sharedchannel/sync_send.go @@ -10,6 +10,7 @@ import ( "sync" "time" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/remotecluster" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -140,6 +141,7 @@ func stopTimer(timer *time.Timer) { // doSync checks the task queue for any tasks to be processed and processes all that are ready. // If any delayed tasks remain in queue then the duration until the next scheduled task is returned. func (scs *Service) doSync() time.Duration { + c := request.EmptyContext() // TODO: check this var task syncTask var ok bool var shortestWait time.Duration @@ -149,7 +151,7 @@ func (scs *Service) doSync() time.Duration { if !ok { break } - if err := scs.processTask(task); err != nil { + if err := scs.processTask(c, task); err != nil { // put task back into map so it will update again if task.incRetry() { scs.addTask(task) @@ -200,7 +202,7 @@ func (scs *Service) removeOldestTask() (syncTask, bool, time.Duration) { } // processTask updates one or more remote clusters with any new channel content. -func (scs *Service) processTask(task syncTask) error { +func (scs *Service) processTask(c *request.Context, task syncTask) error { var err error var remotes []*model.RemoteCluster diff --git a/web/context.go b/web/context.go index 35070db0a56..bd4d812f80c 100644 --- a/web/context.go +++ b/web/context.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/audit" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -19,6 +20,7 @@ import ( type Context struct { App app.AppIface + AppContext *request.Context Logger *mlog.Logger Params *Params Err *model.AppError @@ -51,13 +53,13 @@ func (c *Context) LogAuditRecWithLevel(rec *audit.Record, level mlog.LogLevel) { // MakeAuditRecord creates a audit record pre-populated with data from this context. func (c *Context) MakeAuditRecord(event string, initialStatus string) *audit.Record { rec := &audit.Record{ - APIPath: c.App.Path(), + APIPath: c.AppContext.Path(), Event: event, Status: initialStatus, - UserID: c.App.Session().UserId, - SessionID: c.App.Session().Id, - Client: c.App.UserAgent(), - IPAddress: c.App.IpAddress(), + UserID: c.AppContext.Session().UserId, + SessionID: c.AppContext.Session().Id, + Client: c.AppContext.UserAgent(), + IPAddress: c.AppContext.IpAddress(), Meta: audit.Meta{audit.KeyClusterID: c.App.GetClusterId()}, } rec.AddMetaTypeConverter(model.AuditModelTypeConv) @@ -66,7 +68,7 @@ func (c *Context) MakeAuditRecord(event string, initialStatus string) *audit.Rec } 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} + audit := &model.Audit{UserId: c.AppContext.Session().UserId, IpAddress: c.AppContext.IpAddress(), Action: c.AppContext.Path(), ExtraInfo: extraInfo, SessionId: c.AppContext.Session().Id} if err := c.App.Srv().Store.Audit().Save(audit); err != nil { appErr := model.NewAppError("LogAudit", "app.audit.save.saving.app_error", nil, err.Error(), http.StatusInternalServerError) c.LogErrorByCode(appErr) @@ -75,11 +77,11 @@ func (c *Context) LogAudit(extraInfo string) { func (c *Context) LogAuditWithUserId(userId, extraInfo string) { - if c.App.Session().UserId != "" { - extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.App.Session().UserId) + if c.AppContext.Session().UserId != "" { + extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.AppContext.Session().UserId) } - audit := &model.Audit{UserId: userId, IpAddress: c.App.IpAddress(), Action: c.App.Path(), ExtraInfo: extraInfo, SessionId: c.App.Session().Id} + audit := &model.Audit{UserId: userId, IpAddress: c.AppContext.IpAddress(), Action: c.AppContext.Path(), ExtraInfo: extraInfo, SessionId: c.AppContext.Session().Id} if err := c.App.Srv().Store.Audit().Save(audit); err != nil { appErr := model.NewAppError("LogAuditWithUserId", "app.audit.save.saving.app_error", nil, err.Error(), http.StatusInternalServerError) c.LogErrorByCode(appErr) @@ -106,33 +108,33 @@ func (c *Context) LogErrorByCode(err *model.AppError) { } func (c *Context) IsSystemAdmin() bool { - return c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) + return c.App.SessionHasPermissionTo(*c.AppContext.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.AppContext.Session().Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN && + c.AppContext.Session().Props[model.SESSION_PROP_IS_BOT] != model.SESSION_PROP_IS_BOT_VALUE { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized) return } - if c.App.Session().UserId == "" { + if c.AppContext.Session().UserId == "" { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserRequired", http.StatusUnauthorized) return } } func (c *Context) CloudKeyRequired() { - if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.App.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_CLOUD_KEY { + if license := c.App.Srv().License(); license == nil || !*license.Features.Cloud || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_CLOUD_KEY { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized) return } } func (c *Context) RemoteClusterTokenRequired() { - if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.App.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_REMOTECLUSTER_TOKEN { + if license := c.App.Srv().License(); license == nil || !*license.Features.RemoteClusterService || c.AppContext.Session().Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_REMOTECLUSTER_TOKEN { c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "TokenRequired", http.StatusUnauthorized) return } @@ -145,11 +147,11 @@ func (c *Context) MfaRequired() { } // OAuth integrations are excepted - if c.App.Session().IsOAuth { + if c.AppContext.Session().IsOAuth { return } - user, err := c.App.GetUser(c.App.Session().UserId) + user, err := c.App.GetUser(c.AppContext.Session().UserId) if err != nil { c.Err = model.NewAppError("MfaRequired", "api.context.get_user.app_error", nil, err.Error(), http.StatusUnauthorized) return @@ -167,7 +169,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.AppContext.Path() == path.Join(subpath, "/api/v4/users/me") { return } @@ -185,8 +187,8 @@ func (c *Context) MfaRequired() { // ExtendSessionExpiryIfNeeded will update Session.ExpiresAt based on session lengths in config. // Session cookies will be resent to the client with updated max age. func (c *Context) ExtendSessionExpiryIfNeeded(w http.ResponseWriter, r *http.Request) { - if ok := c.App.ExtendSessionExpiryIfNeeded(c.App.Session()); ok { - c.App.AttachSessionCookies(w, r) + if ok := c.App.ExtendSessionExpiryIfNeeded(c.AppContext.Session()); ok { + c.App.AttachSessionCookies(c.AppContext, w, r) } } @@ -281,7 +283,7 @@ func NewJSONEncodingError() *model.AppError { } func (c *Context) SetPermissionError(permissions ...*model.Permission) { - c.Err = c.App.MakePermissionError(permissions) + c.Err = c.App.MakePermissionError(c.AppContext.Session(), permissions) } func (c *Context) SetSiteURLHeader(url string) { @@ -298,7 +300,7 @@ func (c *Context) RequireUserId() *Context { } if c.Params.UserId == model.ME { - c.Params.UserId = c.App.Session().UserId + c.Params.UserId = c.AppContext.Session().UserId } if !model.IsValidId(c.Params.UserId) { diff --git a/web/context_test.go b/web/context_test.go index 74239819c70..2d81f6abd10 100644 --- a/web/context_test.go +++ b/web/context_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock" "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" @@ -41,7 +42,8 @@ func TestCloudKeyRequired(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense("cloud")) c := &Context{ - App: th.App, + App: th.App, + AppContext: &request.Context{}, } c.CloudKeyRequired() @@ -69,7 +71,7 @@ func TestMfaRequired(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense("mfa")) - th.App.SetSession(&model.Session{Id: "abc", UserId: "userid"}) + th.Context.SetSession(&model.Session{Id: "abc", UserId: "userid"}) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.AnnouncementSettings.UserNoticesEnabled = false @@ -79,7 +81,8 @@ func TestMfaRequired(t *testing.T) { }) c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } c.MfaRequired() diff --git a/web/handlers.go b/web/handlers.go index 0489f6e601b..b0ed91d2381 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -21,6 +21,7 @@ import ( "github.com/mattermost/mattermost-server/v5/app" app_opentracing "github.com/mattermost/mattermost-server/v5/app/opentracing" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/tracing" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -40,37 +41,37 @@ func GetHandlerName(h func(*Context, http.ResponseWriter, *http.Request)) string func (w *Web) NewHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { return &Handler{ - GetGlobalAppOptions: w.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: GetHandlerName(h), - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: w.app, + HandleFunc: h, + HandlerName: GetHandlerName(h), + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } } func (w *Web) NewStaticHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { // Determine the CSP SHA directive needed for subpath support, if any. This value is fixed // on server start and intentionally requires a restart to take effect. - subpath, _ := utils.GetSubpathFromConfig(w.ConfigService.Config()) + subpath, _ := utils.GetSubpathFromConfig(w.app.Config()) return &Handler{ - GetGlobalAppOptions: w.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: GetHandlerName(h), - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: true, + App: w.app, + HandleFunc: h, + HandlerName: GetHandlerName(h), + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: true, cspShaDirective: utils.GetSubpathScriptHash(subpath), } } type Handler struct { - GetGlobalAppOptions app.AppOptionCreator + App app.AppIface HandleFunc func(*Context, http.ResponseWriter, *http.Request) HandlerName string RequireSession bool @@ -104,19 +105,18 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { mlog.Debug("Received HTTP request", responseLogFields...) }() - c := &Context{} - c.App = app.New( - h.GetGlobalAppOptions()..., - ) - c.App.InitServer() + c := &Context{ + AppContext: &request.Context{}, + App: h.App, + } t, _ := i18n.GetTranslationsAndLocaleFromRequest(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.AppContext.SetT(t) + c.AppContext.SetRequestId(requestID) + c.AppContext.SetIpAddress(utils.GetIPAddress(r, c.App.Config().ServiceSettings.TrustedProxyIPHeader)) + c.AppContext.SetUserAgent(r.UserAgent()) + c.AppContext.SetAcceptLanguage(r.Header.Get("Accept-Language")) + c.AppContext.SetPath(r.URL.Path) c.Params = ParamsFromRequest(r) c.Logger = c.App.Log() @@ -125,10 +125,10 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { carrier := opentracing.HTTPHeadersCarrier(r.Header) _ = opentracing.GlobalTracer().Inject(span.Context(), opentracing.HTTPHeaders, carrier) ext.HTTPMethod.Set(span, r.Method) - ext.HTTPUrl.Set(span, c.App.Path()) - ext.PeerAddress.Set(span, c.App.IpAddress()) - span.SetTag("request_id", c.App.RequestId()) - span.SetTag("user_agent", c.App.UserAgent()) + ext.HTTPUrl.Set(span, c.AppContext.Path()) + ext.PeerAddress.Set(span, c.AppContext.IpAddress()) + span.SetTag("request_id", c.AppContext.RequestId()) + span.SetTag("user_agent", c.AppContext.UserAgent()) defer func() { if c.Err != nil { @@ -138,7 +138,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } span.Finish() }() - c.App.SetContext(ctx) + c.AppContext.SetContext(ctx) tmpSrv := *c.App.Srv() tmpSrv.Store = opentracinglayer.New(c.App.Srv().Store, ctx) @@ -158,7 +158,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.AppContext.RequestId()) w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil)) if *c.App.Config().ServiceSettings.TLSStrictTransport { @@ -219,11 +219,11 @@ 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.SetSession(session) + c.AppContext.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.AppContext.Session().UserId, w) { return } @@ -235,7 +235,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Logger.Warn("Invalid CWS token", mlog.Err(err)) c.Err = err } else { - c.App.SetSession(session) + c.AppContext.SetSession(session) } } else if token != "" && c.App.Srv().License() != nil && *c.App.Srv().License().Features.RemoteClusterService && tokenLocation == app.TokenLocationRemoteClusterHeader { // Get the remote cluster @@ -249,16 +249,16 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.Logger.Warn("Invalid remote cluster token", mlog.Err(err)) c.Err = err } else { - c.App.SetSession(session) + c.AppContext.SetSession(session) } } } c.Logger = 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("path", c.AppContext.Path()), + mlog.String("request_id", c.AppContext.RequestId()), + mlog.String("ip_addr", c.AppContext.IpAddress()), + mlog.String("user_id", c.AppContext.Session().UserId), mlog.String("method", r.Method), ) @@ -287,7 +287,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // shape IP:PORT (it will be "@" in Linux, for example) isLocalOrigin := !strings.Contains(r.RemoteAddr, ":") if *c.App.Config().ServiceSettings.EnableLocalMode && isLocalOrigin { - c.App.SetSession(&model.Session{Local: true}) + c.AppContext.SetSession(&model.Session{Local: true}) } else if !isLocalOrigin { c.Err = model.NewAppError("", "api.context.local_origin_required.app_error", nil, "LocalOriginRequired", http.StatusUnauthorized) } @@ -299,8 +299,8 @@ 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.Translate(c.AppContext.T) + c.Err.RequestId = c.AppContext.RequestId() c.LogErrorByCode(c.Err) c.Err.Where = r.URL.Path @@ -382,7 +382,7 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke } if !csrfCheckPassed { - c.App.SetSession(&model.Session{}) + c.AppContext.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) } } @@ -394,16 +394,16 @@ func (h *Handler) checkCSRFToken(c *Context, r *http.Request, token string, toke // granted. func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ - GetGlobalAppOptions: w.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: GetHandlerName(h), - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: w.app, + HandleFunc: h, + HandlerName: GetHandlerName(h), + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *w.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *w.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -414,16 +414,16 @@ func (w *Web) ApiHandler(h func(*Context, http.ResponseWriter, *http.Request)) h // websocket. func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ - GetGlobalAppOptions: w.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: GetHandlerName(h), - RequireSession: false, - TrustRequester: true, - RequireMfa: false, - IsStatic: false, - IsLocal: false, + App: w.app, + HandleFunc: h, + HandlerName: GetHandlerName(h), + RequireSession: false, + TrustRequester: true, + RequireMfa: false, + IsStatic: false, + IsLocal: false, } - if *w.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *w.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler @@ -433,16 +433,16 @@ func (w *Web) ApiHandlerTrustRequester(h func(*Context, http.ResponseWriter, *ht // be granted. func (w *Web) ApiSessionRequired(h func(*Context, http.ResponseWriter, *http.Request)) http.Handler { handler := &Handler{ - GetGlobalAppOptions: w.GetGlobalAppOptions, - HandleFunc: h, - HandlerName: GetHandlerName(h), - RequireSession: true, - TrustRequester: false, - RequireMfa: true, - IsStatic: false, - IsLocal: false, + App: w.app, + HandleFunc: h, + HandlerName: GetHandlerName(h), + RequireSession: true, + TrustRequester: false, + RequireMfa: true, + IsStatic: false, + IsLocal: false, } - if *w.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *w.app.Config().ServiceSettings.WebserverMode == "gzip" { return gziphandler.GzipHandler(handler) } return handler diff --git a/web/handlers_test.go b/web/handlers_test.go index 1584d26b974..53b86b79db7 100644 --- a/web/handlers_test.go +++ b/web/handlers_test.go @@ -25,7 +25,7 @@ func TestHandlerServeHTTPErrors(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := web.NewHandler(handlerForHTTPErrors) var flagtests = []struct { @@ -84,7 +84,7 @@ func TestHandlerServeHTTPSecureTransport(t *testing.T) { *config.ServiceSettings.TLSStrictTransportMaxAge = 6000 }) - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := web.NewHandler(handlerForHTTPSecureTransport) request := httptest.NewRequest("GET", "/api/v4/test", nil) @@ -136,15 +136,15 @@ func TestHandlerServeCSRFToken(t *testing.T) { t.Errorf("Expected nil, got %s", err) } - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSRFToken, - RequireSession: true, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, + App: web.app, + HandleFunc: handlerForCSRFToken, + RequireSession: true, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, } cookie := &http.Cookie{ @@ -219,12 +219,12 @@ func TestHandlerServeCSRFToken(t *testing.T) { // Handler with RequireSession set to false handlerNoSession := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSRFToken, - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, + App: th.App, + HandleFunc: handlerForCSRFToken, + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, } // CSRF Token Used - Success Expected @@ -263,15 +263,15 @@ func TestHandlerServeCSPHeader(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSPHeader, - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, + App: web.app, + HandleFunc: handlerForCSPHeader, + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, } request := httptest.NewRequest("POST", "/api/v4/test", nil) @@ -285,15 +285,15 @@ func TestHandlerServeCSPHeader(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSPHeader, - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: true, + App: web.app, + HandleFunc: handlerForCSPHeader, + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: true, } request := httptest.NewRequest("POST", "/", nil) @@ -325,15 +325,15 @@ func TestHandlerServeCSPHeader(t *testing.T) { *cfg.ServiceSettings.SiteURL = *cfg.ServiceSettings.SiteURL + "/subpath" }) - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSPHeader, - RequireSession: false, - TrustRequester: false, - RequireMfa: false, - IsStatic: true, + App: web.app, + HandleFunc: handlerForCSPHeader, + RequireSession: false, + TrustRequester: false, + RequireMfa: false, + IsStatic: true, } request := httptest.NewRequest("POST", "/", nil) @@ -380,15 +380,15 @@ func TestHandlerServeInvalidToken(t *testing.T) { *cfg.ServiceSettings.SiteURL = tc.SiteURL }) - web := New(th.Server, th.Server.AppOptions, th.Server.Router) + web := New(th.App, th.Server.Router) handler := Handler{ - GetGlobalAppOptions: web.GetGlobalAppOptions, - HandleFunc: handlerForCSRFToken, - RequireSession: true, - TrustRequester: false, - RequireMfa: false, - IsStatic: false, + App: web.app, + HandleFunc: handlerForCSRFToken, + RequireSession: true, + TrustRequester: false, + RequireMfa: false, + IsStatic: false, } cookie := &http.Cookie{ @@ -422,7 +422,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_CSRF_TOKEN, token) @@ -452,8 +453,9 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, - Logger: th.App.Log(), + App: th.App, + Logger: th.App.Log(), + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) @@ -501,8 +503,9 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, - Logger: th.App.Log(), + App: th.App, + Logger: th.App.Log(), + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_REQUESTED_WITH, model.HEADER_REQUESTED_WITH_XML) @@ -532,7 +535,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) session := &model.Session{ @@ -561,7 +565,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodGet, "", nil) session := &model.Session{ @@ -590,7 +595,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationHeader c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) session := &model.Session{ @@ -619,7 +625,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_CSRF_TOKEN, token) @@ -644,7 +651,8 @@ func TestCheckCSRFToken(t *testing.T) { tokenLocation := app.TokenLocationCookie c := &Context{ - App: th.App, + App: th.App, + AppContext: th.Context, } r, _ := http.NewRequest(http.MethodPost, "", nil) r.Header.Set(model.HEADER_CSRF_TOKEN, token) diff --git a/web/oauth.go b/web/oauth.go index c15407b9705..de7763cda9a 100644 --- a/web/oauth.go +++ b/web/oauth.go @@ -54,7 +54,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Session().IsOAuth { + if c.AppContext.Session().IsOAuth { c.SetPermissionError(model.PERMISSION_EDIT_OTHER_USERS) c.Err.DetailedError += ", attempted access by oauth app" return @@ -64,7 +64,7 @@ func authorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.App.Session().UserId, authRequest) + redirectUrl, err := c.App.AllowOAuthAppAccessToUser(c.AppContext.Session().UserId, authRequest) if err != nil { c.Err = err @@ -89,7 +89,7 @@ func deauthorizeOAuthApp(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deauthorizeOAuthApp", audit.Fail) defer c.LogAuditRec(auditRec) - err := c.App.DeauthorizeOAuthAppForUser(c.App.Session().UserId, clientId) + err := c.App.DeauthorizeOAuthAppForUser(c.AppContext.Session().UserId, clientId) if err != nil { c.Err = err return @@ -134,7 +134,7 @@ func authorizeOAuthPage(c *Context, w http.ResponseWriter, r *http.Request) { } // here we should check if the user is logged in - if c.App.Session().UserId == "" { + if c.AppContext.Session().UserId == "" { 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 { @@ -155,14 +155,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.AppContext.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.AppContext.Session().UserId, authRequest) if err != nil { utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey()) @@ -295,15 +295,15 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { } if err != nil { - err.Translate(c.App.T) + err.Translate(c.AppContext.T) c.LogErrorByCode(err) renderError(err) return } - user, err := c.App.CompleteOAuth(service, body, teamId, props, tokenUser) + user, err := c.App.CompleteOAuth(c.AppContext, service, body, teamId, props, tokenUser) if err != nil { - err.Translate(c.App.T) + err.Translate(c.AppContext.T) c.LogErrorByCode(err) renderError(err) return @@ -314,9 +314,9 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { } else if action == model.OAUTH_ACTION_SSO_TO_EMAIL { redirectURL = app.GetProtocol(r) + "://" + r.Host + "/claim?email=" + url.QueryEscape(props["email"]) } else { - err = c.App.DoLogin(w, r, user, "", isMobile, false, false) + err = c.App.DoLogin(c.AppContext, w, r, user, "", isMobile, false, false) if err != nil { - err.Translate(c.App.T) + err.Translate(c.AppContext.T) mlog.Error(err.Error()) renderError(err) return @@ -324,19 +324,19 @@ func completeOAuth(c *Context, w http.ResponseWriter, r *http.Request) { // Old mobile version if isMobile && !hasRedirectURL { - c.App.AttachSessionCookies(w, r) + c.App.AttachSessionCookies(c.AppContext, w, r) return } else // New mobile version if isMobile && hasRedirectURL { redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{ - model.SESSION_COOKIE_TOKEN: c.App.Session().Token, - model.SESSION_COOKIE_CSRF: c.App.Session().GetCSRF(), + model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token, + model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(), }) utils.RenderMobileAuthComplete(w, redirectURL) return } else { // For web - c.App.AttachSessionCookies(w, r) + c.App.AttachSessionCookies(c.AppContext, w, r) // If no redirect url is passed, get the default one if !hasRedirectURL { diff --git a/web/oauth_test.go b/web/oauth_test.go index e42517f371f..672c7901a08 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -18,6 +18,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/shared/i18n" @@ -530,14 +531,15 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() c := &Context{ - App: th.App, + App: th.App, + AppContext: &request.Context{}, Params: &Params{ Service: "gitlab", }, } translationFunc := i18n.GetUserTranslations("en") - c.App.SetT(translationFunc) + c.AppContext.SetT(translationFunc) buffer := &bytes.Buffer{} c.Logger = mlog.NewTestingLogger(t, buffer) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true }) diff --git a/web/saml.go b/web/saml.go index d9e9a14eeec..4e5e5839ddc 100644 --- a/web/saml.go +++ b/web/saml.go @@ -112,7 +112,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { handleError := func(err *model.AppError) { if isMobile && hasRedirectURL { - err.Translate(c.App.T) + err.Translate(c.AppContext.T) utils.RenderMobileError(c.App.Config(), w, err, redirectURL) } else { c.Err = err @@ -120,7 +120,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { } } - user, err := samlInterface.DoLogin(encodedXML, relayProps) + user, err := samlInterface.DoLogin(c.AppContext, encodedXML, relayProps) if err != nil { c.LogAudit("fail") mlog.Error(err.Error()) @@ -137,7 +137,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { switch action { case model.OAUTH_ACTION_SIGNUP: if teamId := relayProps["team_id"]; teamId != "" { - if err = c.App.AddUserToTeamByTeamId(teamId, user); err != nil { + if err = c.App.AddUserToTeamByTeamId(c.AppContext, teamId, user); err != nil { c.LogErrorByCode(err) break } @@ -162,7 +162,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("obtained_user_id", user.Id) c.LogAuditWithUserId(user.Id, "obtained user") - err = c.App.DoLogin(w, r, user, "", isMobile, false, true) + err = c.App.DoLogin(c.AppContext, w, r, user, "", isMobile, false, true) if err != nil { mlog.Error(err.Error()) handleError(err) @@ -172,14 +172,14 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.Success() c.LogAuditWithUserId(user.Id, "success") - c.App.AttachSessionCookies(w, r) + c.App.AttachSessionCookies(c.AppContext, w, r) if hasRedirectURL { if isMobile { // Mobile clients with redirect url support redirectURL = utils.AppendQueryParamsToURL(redirectURL, map[string]string{ - model.SESSION_COOKIE_TOKEN: c.App.Session().Token, - model.SESSION_COOKIE_CSRF: c.App.Session().GetCSRF(), + model.SESSION_COOKIE_TOKEN: c.AppContext.Session().Token, + model.SESSION_COOKIE_CSRF: c.AppContext.Session().GetCSRF(), }) utils.RenderMobileAuthComplete(w, redirectURL) } else { diff --git a/web/static.go b/web/static.go index d2bfd6eb098..4d8b8d31dfc 100644 --- a/web/static.go +++ b/web/static.go @@ -21,20 +21,20 @@ import ( var robotsTxt = []byte("User-agent: *\nDisallow: /\n") func (w *Web) InitStatic() { - if *w.ConfigService.Config().ServiceSettings.WebserverMode != "disabled" { - if err := utils.UpdateAssetsSubpathFromConfig(w.ConfigService.Config()); err != nil { + if *w.app.Config().ServiceSettings.WebserverMode != "disabled" { + if err := utils.UpdateAssetsSubpathFromConfig(w.app.Config()); err != nil { mlog.Error("Failed to update assets subpath from config", mlog.Err(err)) } staticDir, _ := fileutils.FindDir(model.CLIENT_DIR) mlog.Debug("Using client directory", mlog.String("clientDir", staticDir)) - subpath, _ := utils.GetSubpathFromConfig(w.ConfigService.Config()) + subpath, _ := utils.GetSubpathFromConfig(w.app.Config()) staticHandler := staticFilesHandler(http.StripPrefix(path.Join(subpath, "static"), http.FileServer(http.Dir(staticDir)))) - pluginHandler := staticFilesHandler(http.StripPrefix(path.Join(subpath, "static", "plugins"), http.FileServer(http.Dir(*w.ConfigService.Config().PluginSettings.ClientDirectory)))) + pluginHandler := staticFilesHandler(http.StripPrefix(path.Join(subpath, "static", "plugins"), http.FileServer(http.Dir(*w.app.Config().PluginSettings.ClientDirectory)))) - if *w.ConfigService.Config().ServiceSettings.WebserverMode == "gzip" { + if *w.app.Config().ServiceSettings.WebserverMode == "gzip" { staticHandler = gziphandler.GzipHandler(staticHandler) pluginHandler = gziphandler.GzipHandler(pluginHandler) } @@ -58,7 +58,10 @@ func (w *Web) InitStatic() { func root(c *Context, w http.ResponseWriter, r *http.Request) { if !CheckClientCompatibility(r.UserAgent()) { - renderUnsupportedBrowser(c.App, w, r) + w.Header().Set("Cache-Control", "no-store") + data := renderUnsupportedBrowser(c.AppContext, r) + + c.App.Srv().TemplatesContainer().Render(w, "unsupported_browser", data) return } diff --git a/web/unsupported_browser.go b/web/unsupported_browser.go index 5463f17d26a..9943e49c694 100644 --- a/web/unsupported_browser.go +++ b/web/unsupported_browser.go @@ -8,7 +8,7 @@ import ( "github.com/avct/uasurfer" - "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/shared/templates" ) @@ -44,13 +44,12 @@ type SystemBrowser struct { MakeDefaultString string } -func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") +func renderUnsupportedBrowser(ctx *request.Context, r *http.Request) templates.Data { data := templates.Data{ Props: map[string]interface{}{ - "DownloadAppOrUpgradeBrowserString": app.T("web.error.unsupported_browser.download_app_or_upgrade_browser"), - "LearnMoreString": app.T("web.error.unsupported_browser.learn_more"), + "DownloadAppOrUpgradeBrowserString": ctx.T("web.error.unsupported_browser.download_app_or_upgrade_browser"), + "LearnMoreString": ctx.T("web.error.unsupported_browser.learn_more"), }, } @@ -63,98 +62,99 @@ func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.R // Basic heading translations if isSafari { - data.Props["NoLongerSupportString"] = app.T("web.error.unsupported_browser.no_longer_support_version") + data.Props["NoLongerSupportString"] = ctx.T("web.error.unsupported_browser.no_longer_support_version") } else { - data.Props["NoLongerSupportString"] = app.T("web.error.unsupported_browser.no_longer_support") + data.Props["NoLongerSupportString"] = ctx.T("web.error.unsupported_browser.no_longer_support") } // Mattermost app version if isWindows { - data.Props["App"] = renderMattermostAppWindows(app) + data.Props["App"] = renderMattermostAppWindows(ctx) } else if isMacOSX { - data.Props["App"] = renderMattermostAppMac(app) + data.Props["App"] = renderMattermostAppMac(ctx) } // Browsers to download // Show a link to Safari if you're using safari and it's outdated // Can't show on Mac all the time because there's no way to open it via URI - browsers := []Browser{renderBrowserChrome(app), renderBrowserFirefox(app)} + browsers := []Browser{renderBrowserChrome(ctx), renderBrowserFirefox(ctx)} if isSafari { - browsers = append(browsers, renderBrowserSafari(app)) + browsers = append(browsers, renderBrowserSafari(ctx)) } data.Props["Browsers"] = browsers // If on Windows 10, show link to Edge if isWindows10 { - data.Props["SystemBrowser"] = renderSystemBrowserEdge(app, r) + data.Props["SystemBrowser"] = renderSystemBrowserEdge(ctx, r) } - app.Srv().TemplatesContainer().Render(w, "unsupported_browser", data) + return data + } -func renderMattermostAppMac(app app.AppIface) MattermostApp { +func renderMattermostAppMac(ctx *request.Context) MattermostApp { return MattermostApp{ "/static/images/browser-icons/mac.png", - app.T("web.error.unsupported_browser.download_the_app"), - app.T("web.error.unsupported_browser.min_os_version.mac"), - app.T("web.error.unsupported_browser.download"), + ctx.T("web.error.unsupported_browser.download_the_app"), + ctx.T("web.error.unsupported_browser.min_os_version.mac"), + ctx.T("web.error.unsupported_browser.download"), "https://mattermost.com/download/#mattermostApps", - app.T("web.error.unsupported_browser.install_guide.mac"), + ctx.T("web.error.unsupported_browser.install_guide.mac"), "https://docs.mattermost.com/install/desktop.html#mac-os-x-10-9", } } -func renderMattermostAppWindows(app app.AppIface) MattermostApp { +func renderMattermostAppWindows(ctx *request.Context) MattermostApp { return MattermostApp{ "/static/images/browser-icons/windows.svg", - app.T("web.error.unsupported_browser.download_the_app"), - app.T("web.error.unsupported_browser.min_os_version.windows"), - app.T("web.error.unsupported_browser.download"), + ctx.T("web.error.unsupported_browser.download_the_app"), + ctx.T("web.error.unsupported_browser.min_os_version.windows"), + ctx.T("web.error.unsupported_browser.download"), "https://mattermost.com/download/#mattermostApps", - app.T("web.error.unsupported_browser.install_guide.windows"), + ctx.T("web.error.unsupported_browser.install_guide.windows"), "https://docs.mattermost.com/install/desktop.html#windows-10-windows-8-1-windows-7", } } -func renderBrowserChrome(app app.AppIface) Browser { +func renderBrowserChrome(ctx *request.Context) Browser { return Browser{ "/static/images/browser-icons/chrome.svg", - app.T("web.error.unsupported_browser.browser_title.chrome"), - app.T("web.error.unsupported_browser.min_browser_version.chrome"), + ctx.T("web.error.unsupported_browser.browser_title.chrome"), + ctx.T("web.error.unsupported_browser.min_browser_version.chrome"), "http://www.google.com/chrome", - app.T("web.error.unsupported_browser.browser_get_latest.chrome"), + ctx.T("web.error.unsupported_browser.browser_get_latest.chrome"), } } -func renderBrowserFirefox(app app.AppIface) Browser { +func renderBrowserFirefox(ctx *request.Context) Browser { return Browser{ "/static/images/browser-icons/firefox.svg", - app.T("web.error.unsupported_browser.browser_title.firefox"), - app.T("web.error.unsupported_browser.min_browser_version.firefox"), + ctx.T("web.error.unsupported_browser.browser_title.firefox"), + ctx.T("web.error.unsupported_browser.min_browser_version.firefox"), "https://www.mozilla.org/firefox/new/", - app.T("web.error.unsupported_browser.browser_get_latest.firefox"), + ctx.T("web.error.unsupported_browser.browser_get_latest.firefox"), } } -func renderBrowserSafari(app app.AppIface) Browser { +func renderBrowserSafari(ctx *request.Context) Browser { return Browser{ "/static/images/browser-icons/safari.svg", - app.T("web.error.unsupported_browser.browser_title.safari"), - app.T("web.error.unsupported_browser.min_browser_version.safari"), + ctx.T("web.error.unsupported_browser.browser_title.safari"), + ctx.T("web.error.unsupported_browser.min_browser_version.safari"), "macappstore://showUpdatesPage", - app.T("web.error.unsupported_browser.browser_get_latest.safari"), + ctx.T("web.error.unsupported_browser.browser_get_latest.safari"), } } -func renderSystemBrowserEdge(app app.AppIface, r *http.Request) SystemBrowser { +func renderSystemBrowserEdge(ctx *request.Context, r *http.Request) SystemBrowser { return SystemBrowser{ "/static/images/browser-icons/edge.svg", - app.T("web.error.unsupported_browser.browser_title.edge"), - app.T("web.error.unsupported_browser.min_browser_version.edge"), - app.T("web.error.unsupported_browser.open_system_browser.edge"), + ctx.T("web.error.unsupported_browser.browser_title.edge"), + ctx.T("web.error.unsupported_browser.min_browser_version.edge"), + ctx.T("web.error.unsupported_browser.open_system_browser.edge"), "microsoft-edge:http://" + r.Host + r.RequestURI, //TODO: Can we get HTTP or HTTPS? If someone's server doesn't have a redirect this won't work "ms-settings:defaultapps", - app.T("web.error.unsupported_browser.system_browser_or"), - app.T("web.error.unsupported_browser.system_browser_make_default"), + ctx.T("web.error.unsupported_browser.system_browser_or"), + ctx.T("web.error.unsupported_browser.system_browser_make_default"), } } diff --git a/web/web.go b/web/web.go index 8e1048b71d7..e59cf06bbca 100644 --- a/web/web.go +++ b/web/web.go @@ -13,24 +13,21 @@ import ( "github.com/mattermost/mattermost-server/v5/app" "github.com/mattermost/mattermost-server/v5/model" - "github.com/mattermost/mattermost-server/v5/services/configservice" "github.com/mattermost/mattermost-server/v5/shared/mlog" "github.com/mattermost/mattermost-server/v5/utils" ) type Web struct { - GetGlobalAppOptions app.AppOptionCreator - ConfigService configservice.ConfigService - MainRouter *mux.Router + app app.AppIface + MainRouter *mux.Router } -func New(config configservice.ConfigService, globalOptions app.AppOptionCreator, root *mux.Router) *Web { +func New(a app.AppIface, root *mux.Router) *Web { mlog.Debug("Initializing web routes") web := &Web{ - GetGlobalAppOptions: globalOptions, - ConfigService: config, - MainRouter: root, + app: a, + MainRouter: root, } web.InitOAuth() @@ -60,24 +57,24 @@ func CheckClientCompatibility(agentString string) bool { return true } -func Handle404(config configservice.ConfigService, w http.ResponseWriter, r *http.Request) { +func Handle404(a app.AppIface, w http.ResponseWriter, r *http.Request) { err := model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound) - ipAddress := utils.GetIPAddress(r, config.Config().ServiceSettings.TrustedProxyIPHeader) + ipAddress := utils.GetIPAddress(r, a.Config().ServiceSettings.TrustedProxyIPHeader) mlog.Debug("not found handler triggered", mlog.String("path", r.URL.Path), mlog.Int("code", 404), mlog.String("ip", ipAddress)) - if IsApiCall(config, r) { + if IsApiCall(a, r) { w.WriteHeader(err.StatusCode) err.DetailedError = "There doesn't appear to be an api call for the url='" + r.URL.Path + "'. Typo? are you missing a team_id or user_id as part of the url?" w.Write([]byte(err.ToJson())) - } else if *config.Config().ServiceSettings.WebserverMode == "disabled" { + } else if *a.Config().ServiceSettings.WebserverMode == "disabled" { http.NotFound(w, r) } else { - utils.RenderWebAppError(config.Config(), w, r, err, config.AsymmetricSigningKey()) + utils.RenderWebAppError(a.Config(), w, r, err, a.AsymmetricSigningKey()) } } -func IsApiCall(config configservice.ConfigService, r *http.Request) bool { - subpath, _ := utils.GetSubpathFromConfig(config.Config()) +func IsApiCall(a app.AppIface, r *http.Request) bool { + subpath, _ := utils.GetSubpathFromConfig(a.Config()) return strings.HasPrefix(r.URL.Path, path.Join(subpath, "api")+"/") } @@ -88,8 +85,8 @@ func IsWebhookCall(a app.AppIface, r *http.Request) bool { return strings.HasPrefix(r.URL.Path, path.Join(subpath, "hooks")+"/") } -func IsOAuthApiCall(config configservice.ConfigService, r *http.Request) bool { - subpath, _ := utils.GetSubpathFromConfig(config.Config()) +func IsOAuthApiCall(a app.AppIface, r *http.Request) bool { + subpath, _ := utils.GetSubpathFromConfig(a.Config()) if r.Method == "POST" && r.URL.Path == path.Join(subpath, "oauth", "authorize") { return true diff --git a/web/web_test.go b/web/web_test.go index 5a73ede8849..dfc13ced1c5 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -17,6 +17,7 @@ import ( "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v5/app" + "github.com/mattermost/mattermost-server/v5/app/request" "github.com/mattermost/mattermost-server/v5/config" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/plugin" @@ -30,9 +31,10 @@ var ApiClient *model.Client4 var URL string type TestHelper struct { - App app.AppIface - Server *app.Server - Web *Web + App app.AppIface + Context *request.Context + Server *app.Server + Web *Web BasicUser *model.User BasicChannel *model.Channel @@ -108,10 +110,10 @@ func setupTestHelper(includeCacheLayer bool) *TestHelper { *cfg.PasswordSettings.Number = false }) + ctx := &request.Context{} a := app.New(app.ServerConnector(s)) - a.InitServer() - web := New(s, s.AppOptions, s.Router) + web := New(a, s.Router) URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port) ApiClient = model.NewAPIv4Client(URL) @@ -123,6 +125,7 @@ func setupTestHelper(includeCacheLayer bool) *TestHelper { th := &TestHelper{ App: a, + Context: ctx, Server: s, Web: web, IncludeCacheLayer: includeCacheLayer, @@ -135,21 +138,25 @@ func (th *TestHelper) InitPlugins() *TestHelper { pluginDir := filepath.Join(th.tempWorkspace, "plugins") webappDir := filepath.Join(th.tempWorkspace, "webapp") - th.App.InitPlugins(pluginDir, webappDir) + th.App.InitPlugins(th.Context, pluginDir, webappDir) return th } +func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API { + return th.App.NewPluginAPI(th.Context, manifest) +} + func (th *TestHelper) InitBasic() *TestHelper { - th.SystemAdminUser, _ = th.App.CreateUser(&model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_ADMIN_ROLE_ID}) + th.SystemAdminUser, _ = th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_ADMIN_ROLE_ID}) - user, _ := th.App.CreateUser(&model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_USER_ROLE_ID}) + user, _ := th.App.CreateUser(th.Context, &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1", EmailVerified: true, Roles: model.SYSTEM_USER_ROLE_ID}) - team, _ := th.App.CreateTeam(&model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TEAM_OPEN}) + team, _ := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: user.Email, Type: model.TEAM_OPEN}) - th.App.JoinUserToTeam(team, user, "") + th.App.JoinUserToTeam(th.Context, team, user, "") - channel, _ := th.App.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id, CreatorId: user.Id}, true) + channel, _ := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id, CreatorId: user.Id}, true) th.BasicUser = user th.BasicChannel = channel @@ -263,7 +270,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(), nil) + env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), nil) require.NoError(t, err) pluginID := "com.mattermost.sample" diff --git a/web/webhook.go b/web/webhook.go index 068cf423c27..75d41e16e70 100644 --- a/web/webhook.go +++ b/web/webhook.go @@ -49,7 +49,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.AppContext.RequestId()), mlog.String("payload", incomingWebhookPayload.ToJson())) } } }() @@ -85,7 +85,7 @@ func incomingWebhook(c *Context, w http.ResponseWriter, r *http.Request) { } } - err = c.App.HandleIncomingWebhook(id, incomingWebhookPayload) + err = c.App.HandleIncomingWebhook(c.AppContext, id, incomingWebhookPayload) if err != nil { c.Err = err return @@ -105,7 +105,7 @@ func commandWebhook(c *Context, w http.ResponseWriter, r *http.Request) { return } - appErr := c.App.HandleCommandWebhook(id, response) + appErr := c.App.HandleCommandWebhook(c.AppContext, id, response) if appErr != nil { c.Err = appErr return diff --git a/web/webhook_test.go b/web/webhook_test.go index a773d82da0d..1018ca2f46b 100644 --- a/web/webhook_test.go +++ b/web/webhook_test.go @@ -232,7 +232,7 @@ func TestIncomingWebhook(t *testing.T) { }) t.Run("ChannelLockedWebhook", func(t *testing.T) { - channel, err := th.App.CreateChannel(&model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.CHANNEL_OPEN, CreatorId: th.BasicUser.Id}, true) + channel, err := th.App.CreateChannel(th.Context, &model.Channel{TeamId: th.BasicTeam.Id, Name: model.NewId(), DisplayName: model.NewId(), Type: model.CHANNEL_OPEN, CreatorId: th.BasicUser.Id}, true) require.Nil(t, err) hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id, ChannelLocked: true})