Migrate to stateless app.App (#17542)

* add request context

* move initialialization to server

* use app interface instead of global app functions

* remove app context from webconn

* cleanup

* remove duplicated services

* move context to separate package

* remove finalize init method and move content to NewServer function

* restart workers and schedulers after adding license for tests

* reflect review comments

Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
This commit is contained in:
Ibrahim Serdar Acikgoz 2021-05-11 13:00:44 +03:00 committed by GitHub
parent c09369f14a
commit 5ea06e51d0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
235 changed files with 4048 additions and 3819 deletions

View file

@ -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

View file

@ -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)
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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

View file

@ -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
}

View file

@ -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,

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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
}

View file

@ -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

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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()

View file

@ -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)

View file

@ -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
}

View file

@ -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

View file

@ -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

View file

@ -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) {

View file

@ -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

View file

@ -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

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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) ||

View file

@ -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
}

View file

@ -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
}

View file

@ -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)

View file

@ -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
}

View file

@ -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
}

View file

@ -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)

View file

@ -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 {

View file

@ -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
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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()

View file

@ -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

View file

@ -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
}

View file

@ -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

View file

@ -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) {

View file

@ -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
}

View file

@ -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

View file

@ -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()

View file

@ -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)

View file

@ -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)
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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})

View file

@ -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)

View file

@ -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

View file

@ -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)
}

View file

@ -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()
}

View file

@ -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

View file

@ -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

View file

@ -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})
}
}

View file

@ -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
}

View file

@ -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)

View file

@ -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
}

View file

@ -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,

View file

@ -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
}
}

View file

@ -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)
}

View file

@ -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",

View file

@ -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)))
}

View file

@ -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
}

View file

@ -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))

View file

@ -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,

View file

@ -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
}

View file

@ -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

View file

@ -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))
}
})

View file

@ -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 {

View file

@ -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)
}

View file

@ -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)

View file

@ -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),

View file

@ -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)

View file

@ -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)
}

View file

@ -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)

View file

@ -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
}
}

View file

@ -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)

View file

@ -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()

View file

@ -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
}

View file

@ -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)

View file

@ -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
}

View file

@ -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,

View file

@ -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)
})

View file

@ -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()
}

View file

@ -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{

View file

@ -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{}

View file

@ -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)
}
}

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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
}
}

View file

@ -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))
}
}
}

View file

@ -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 {

View file

@ -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{

View file

@ -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 {

Some files were not shown because too many files have changed in this diff Show more