MM-15452 - Add ability to override LHS icon for bot accounts (#11423)

* MM-15452 - Add ability to override LHS icon for bot accounts

* MM-15452 - Added translations

* MM-15452 - Updated GetIconImage test to check returned image

* MM-15452 - Added Delete handler for /icon endpoint, invalidating user cache on set/delete

* MM-15452 - Moved /icon routes under bot/, addressed other pr feedback

* MM-15452 - More conflict resolutoin

* MM-15452 Restoring api4/user.go

* MM-15452 - Using require as opposed to t for test assertions

* MM-15452 - Updated as per PR feedback
Этот коммит содержится в:
Ali Farooq
2019-07-06 02:56:21 -04:00
коммит произвёл Jesús Espino
родитель 0d05fe32af
Коммит 2ecca12bed
7 изменённых файлов: 537 добавлений и 18 удалений

Просмотреть файл

@@ -4,7 +4,11 @@
package api4
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"github.com/mattermost/mattermost-server/model"
)
@@ -17,6 +21,10 @@ func (api *API) InitBot() {
api.BaseRoutes.Bot.Handle("/disable", api.ApiSessionRequired(disableBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("/enable", api.ApiSessionRequired(enableBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("/assign/{user_id:[A-Za-z0-9]+}", api.ApiSessionRequired(assignBot)).Methods("POST")
api.BaseRoutes.Bot.Handle("/icon", api.ApiSessionRequiredTrustRequester(getBotIconImage)).Methods("GET")
api.BaseRoutes.Bot.Handle("/icon", api.ApiSessionRequired(setBotIconImage)).Methods("POST")
api.BaseRoutes.Bot.Handle("/icon", api.ApiSessionRequired(deleteBotIconImage)).Methods("DELETE")
}
func createBot(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -217,3 +225,127 @@ func assignBot(c *Context, w http.ResponseWriter, r *http.Request) {
w.Write(bot.ToJson())
}
func getBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
canSee, err := c.App.UserCanSeeOtherUser(c.App.Session.UserId, botUserId)
if err != nil {
c.Err = err
return
}
if !canSee {
c.SetPermissionError(model.PERMISSION_VIEW_MEMBERS)
return
}
user, err := c.App.GetUser(botUserId)
if err != nil {
c.Err = err
return
}
if !user.IsBot {
c.Err = model.MakeBotNotFoundError(botUserId)
return
}
etag := strconv.FormatInt(user.LastPictureUpdate, 10)
if c.HandleEtag(etag, "Get Icon Image", w, r) {
return
}
img, readFailed, err := c.App.GetBotIconImage(user.Id)
if err != nil {
c.Err = err
return
}
if readFailed {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, public", 5*60)) // 5 mins
} else {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v, public", 24*60*60)) // 24 hrs
w.Header().Set(model.HEADER_ETAG_SERVER, etag)
}
w.Header().Set("Content-Type", "image/svg+xml")
w.Write(img)
}
func setBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) {
defer io.Copy(ioutil.Discard, r.Body)
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil {
c.Err = err
return
}
if _, err := c.App.GetBot(botUserId, true); err != nil {
c.Err = model.MakeBotNotFoundError(botUserId)
return
}
if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize {
c.Err = model.NewAppError("setBotIconImage", "api.bot.set_bot_icon_image.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge)
return
}
if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil {
c.Err = model.NewAppError("setBotIconImage", "api.bot.set_bot_icon_image.parse.app_error", nil, err.Error(), http.StatusInternalServerError)
return
}
m := r.MultipartForm
imageArray, ok := m.File["image"]
if !ok {
c.Err = model.NewAppError("setBotIconImage", "api.bot.set_bot_icon_image.no_file.app_error", nil, "", http.StatusBadRequest)
return
}
if len(imageArray) <= 0 {
c.Err = model.NewAppError("setBotIconImage", "api.bot.set_bot_icon_image.array.app_error", nil, "", http.StatusBadRequest)
return
}
imageData := imageArray[0]
if err := c.App.SetBotIconImage(botUserId, imageData); err != nil {
c.Err = err
return
}
c.LogAudit("")
ReturnStatusOK(w)
}
func deleteBotIconImage(c *Context, w http.ResponseWriter, r *http.Request) {
defer io.Copy(ioutil.Discard, r.Body)
c.RequireBotUserId()
if c.Err != nil {
return
}
botUserId := c.Params.BotUserId
if err := c.App.SessionHasPermissionToManageBot(c.App.Session, botUserId); err != nil {
c.Err = err
return
}
if err := c.App.DeleteBotIconImage(botUserId); err != nil {
c.Err = err
return
}
c.LogAudit("")
ReturnStatusOK(w)
}

Просмотреть файл

@@ -4,11 +4,17 @@
package api4
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils/fileutils"
"github.com/mattermost/mattermost-server/utils/testutils"
"github.com/stretchr/testify/require"
)
@@ -1090,6 +1096,196 @@ func TestAssignBot(t *testing.T) {
})
}
func TestSetBotIconImage(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
user := th.BasicUser
defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableBotAccountCreation = true
})
bot := &model.Bot{
Username: GenerateTestUsername(),
Description: "bot",
}
bot, resp := th.Client.CreateBot(bot)
CheckCreatedStatus(t, resp)
defer th.App.PermanentDeleteBot(bot.UserId)
badData, err := testutils.ReadTestFile("test.png")
require.Nil(t, err)
goodData, err := testutils.ReadTestFile("test.svg")
require.Nil(t, err)
// SetBotIconImage only allowed for bots
_, resp = th.SystemAdminClient.SetBotIconImage(user.Id, goodData)
CheckNotFoundStatus(t, resp)
// png/jpg is not allowed
ok, resp := th.Client.SetBotIconImage(bot.UserId, badData)
require.False(t, ok, "Should return false, set icon image only allows svg")
CheckBadRequestStatus(t, resp)
ok, resp = th.Client.SetBotIconImage(model.NewId(), badData)
require.False(t, ok, "Should return false, set icon image not allowed")
CheckNotFoundStatus(t, resp)
_, resp = th.Client.SetBotIconImage(bot.UserId, goodData)
CheckNoError(t, resp)
// status code returns either forbidden or unauthorized
// note: forbidden is set as default at Client4.SetBotIconImage when request is terminated early by server
th.Client.Logout()
_, resp = th.Client.SetBotIconImage(bot.UserId, badData)
if resp.StatusCode == http.StatusForbidden {
CheckForbiddenStatus(t, resp)
} else if resp.StatusCode == http.StatusUnauthorized {
CheckUnauthorizedStatus(t, resp)
} else {
require.Fail(t, "Should have failed either forbidden or unauthorized")
}
_, resp = th.SystemAdminClient.SetBotIconImage(bot.UserId, goodData)
CheckNoError(t, resp)
info := &model.FileInfo{Path: "/bots/" + bot.UserId + "/icon.svg"}
err = th.cleanupTestFile(info)
require.Nil(t, err)
}
func TestGetBotIconImage(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableBotAccountCreation = true
})
bot := &model.Bot{
Username: GenerateTestUsername(),
Description: "bot",
}
bot, resp := th.Client.CreateBot(bot)
CheckCreatedStatus(t, resp)
defer th.App.PermanentDeleteBot(bot.UserId)
// Get icon image for user with no icon
data, resp := th.Client.GetBotIconImage(bot.UserId)
CheckNotFoundStatus(t, resp)
require.Equal(t, 0, len(data))
// Set an icon image
path, _ := fileutils.FindDir("tests")
svgFile, fileErr := os.Open(filepath.Join(path, "test.svg"))
require.NoError(t, fileErr)
defer svgFile.Close()
expectedData, err := ioutil.ReadAll(svgFile)
require.NoError(t, err)
svgFile.Seek(0, 0)
fpath := fmt.Sprintf("/bots/%v/icon.svg", bot.UserId)
_, err = th.App.WriteFile(svgFile, fpath)
require.Nil(t, err)
data, resp = th.Client.GetBotIconImage(bot.UserId)
CheckNoError(t, resp)
require.Equal(t, expectedData, data)
_, resp = th.Client.GetBotIconImage("junk")
CheckBadRequestStatus(t, resp)
_, resp = th.Client.GetBotIconImage(model.NewId())
CheckNotFoundStatus(t, resp)
th.Client.Logout()
_, resp = th.Client.GetBotIconImage(bot.UserId)
CheckUnauthorizedStatus(t, resp)
_, resp = th.SystemAdminClient.GetBotIconImage(bot.UserId)
CheckNoError(t, resp)
info := &model.FileInfo{Path: "/bots/" + bot.UserId + "/icon.svg"}
err = th.cleanupTestFile(info)
require.Nil(t, err)
}
func TestDeleteBotIconImage(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
defer th.RestoreDefaultRolePermissions(th.SaveDefaultRolePermissions())
th.AddPermissionToRole(model.PERMISSION_CREATE_BOT.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_MANAGE_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_READ_BOTS.Id, model.SYSTEM_USER_ROLE_ID)
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableBotAccountCreation = true
})
bot := &model.Bot{
Username: GenerateTestUsername(),
Description: "bot",
}
bot, resp := th.Client.CreateBot(bot)
CheckCreatedStatus(t, resp)
defer th.App.PermanentDeleteBot(bot.UserId)
// Get icon image for user with no icon
data, resp := th.Client.GetBotIconImage(bot.UserId)
CheckNotFoundStatus(t, resp)
require.Equal(t, 0, len(data))
// Set an icon image
svgData, err := testutils.ReadTestFile("test.svg")
require.Nil(t, err)
_, resp = th.Client.SetBotIconImage(bot.UserId, svgData)
CheckNoError(t, resp)
fpath := fmt.Sprintf("/bots/%v/icon.svg", bot.UserId)
exists, err := th.App.FileExists(fpath)
require.Nil(t, err)
require.True(t, exists, "icon.svg needs to exist for the user")
data, resp = th.Client.GetBotIconImage(bot.UserId)
CheckNoError(t, resp)
require.Equal(t, svgData, data)
success, resp := th.Client.DeleteBotIconImage("junk")
CheckBadRequestStatus(t, resp)
require.False(t, success)
success, resp = th.Client.DeleteBotIconImage(model.NewId())
CheckNotFoundStatus(t, resp)
require.False(t, success)
success, resp = th.Client.DeleteBotIconImage(bot.UserId)
CheckNoError(t, resp)
require.True(t, success)
th.Client.Logout()
success, resp = th.Client.DeleteBotIconImage(bot.UserId)
CheckUnauthorizedStatus(t, resp)
require.False(t, success)
exists, err = th.App.FileExists(fpath)
require.Nil(t, err)
require.False(t, exists, "icon.svg should not for the user")
}
func sToP(s string) *string {
return &s
}