* create ChannelBookmarks table

* ChannelBookmark model

* channel bookamrks Store layer

* add GetBookmarksForAllChannelByIdSince

* add channel bookmarks to test store

* Add channel bookmarks to app layer

* remove index for createAt in channel bookmarks migrations

* remove createAt from select channel bookmark query and enable store delete bookmark test

* update reponse of UpdateBookmark

* rename db migration files

* channel bookmarks store update sort order

* channel bookmarks app layer update sort order

* fix lint & tests

* Fix lint and introduce util functions to insert / remove from slice

* remove model etag

* i18n

* defer remove file info after test run

* Fix tests passing the request context

* fix migrations

* fix TestRetry

* Add bookmark permissions (#25560)

* Adds channel bookmarks permissions

* Fix linter

* Remove unnecessary empty lines

* Remove scss change as it's not necessary anymore

* Fix mock store

* Fix mock store and add role entry

* Fix test

* Adds cypress test and update permissions migration to update admin roles

* Adds channel bookmarks roles to default admin roles

* Adds bookmark permissions to default role permissions constant in webapp

* Update mmctl test

* Update permission test after normalising the roles

* fix store tests

* fix app layer tests

* Add new bookmark endpoint (#25624)

* Adds channel bookmarks api scaffold and create endpoint

* Applies review comments to the API docs

* Adds websocket test to create channel bookmark

---------

Co-authored-by: Mattermost Build <build@mattermost.com>

* MM-54426 exclude Channel Bookmarks files from data retention (#25656)

* Augment channel APIs to include bookmarks (#25567)

* update files docs for server 9.4

* Adds update channel bookmark endpoint (#25653)

* Adds update channel bookmark sort order endpoint (#25686)

* Adds update channel bookmark endpoint

* Updates edit app method to return the right deleted bookmark and adds tests

* Adds the update channel bookmark sort order endpoint

* Fix repeated test after merge

* Assign right permissions to each test

* Update store and app layer to return specific errors and add tests

* Adds delete channel bookmark endpoint (#25693)

* Updates edit app method to return the right deleted bookmark and adds tests

* Fix repeated test after merge

* Updates edit app method to return the right deleted bookmark and adds tests

* Adds delete channel bookmark endpoint

* Adds list channel bookmarks endpoint (#25700)

* Add channel moderation to bookmarks (#25716)

* fix migrations index

* fix getChannelsForTeamForUser

* fix getChannelsForTeamForUser

* fix bad merge client4

* fix file api with bookmark permission

* add ChannelBookmarks feature flag

* add missing translations

* Set DB column for type as enum

* use custom type for bookmark query using sqlx

* use transaction when saving bookmark

* return NewErrNotFound instead of Sql.ErrNoRows

* use squirrel for IN query

* add a limit of 1K for records in GetBookmarksForAllChannelByIdSince

* UpdateSortOrder with one single query instead of multiple updates

* fix shadow declaration

* fix channel bookmarks permission string definition in admin console

* fix another shadow declaration

* Fix model conversion

* add SplitSliceInChunks

* remove include bookmarks in channels api

* Cap amount of bookmarks per channel

* add etag back to get channels

* feedback review

* update file info when replacing a bookmark file

* return 501 not implemented when the license is not available

* add detail message when getting channel member on bookmark api

* start audit before permission check on create bookmark api

* use require.Eventuallyf for testing WS events

* remove unnecessary log in app layer

* use require instead of assert to avoid panics

* enforce limit when querying bookmarks since

* prevent to create/update bookmark if file is already attached

* fix lint

* delete file when a bookmark is deleted

* Dot allow to set a fileId and a url at the same time to a bookmark

* fix query to delete a file that belongs to a bookmark

* do not patch the bookmark type

* Server side FeatureFlag check (#26145)

* use ff in server, set ff to false

* turn on FF for unit tests

* defer unset FF for unit tests

* turn ff on for testing

* only allow attaching files that were uploaded for bookmark

* Set feature flag off as default

* fix lint

* update email templates as PR failed

* revert templates

* force the assignment of ID when creating a bookmark

* Fix unit tests

---------

Co-authored-by: Miguel de la Cruz <miguel@mcrx.me>
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: Caleb Roseland <caleb@calebroseland.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Этот коммит содержится в:
Elias Nahum
2024-03-12 22:36:05 +08:00
коммит произвёл GitHub
родитель 2480a6c646
Коммит 7e9cd04a8b
66 изменённых файлов: 6578 добавлений и 57 удалений

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

@@ -49,6 +49,8 @@ type Routes struct {
ChannelMembersForUser *mux.Router // 'api/v4/users/{user_id:[A-Za-z0-9]+}/teams/{team_id:[A-Za-z0-9]+}/channels/members'
ChannelModerations *mux.Router // 'api/v4/channels/{channel_id:[A-Za-z0-9]+}/moderations'
ChannelCategories *mux.Router // 'api/v4/users/{user_id:[A-Za-z0-9]+}/teams/{team_id:[A-Za-z0-9]+}/channels/categories'
ChannelBookmarks *mux.Router // 'api/v4/channels/{channel_id:[A-Za-z0-9]+}/bookmarks'
ChannelBookmark *mux.Router // 'api/v4/channels/{channel_id:[A-Za-z0-9]+}/bookmarks/{bookmark_id:[A-Za-z0-9]+}'
Posts *mux.Router // 'api/v4/posts'
Post *mux.Router // 'api/v4/posts/{post_id:[A-Za-z0-9]+}'
@@ -193,6 +195,8 @@ func Init(srv *app.Server) (*API, error) {
api.BaseRoutes.ChannelMembersForUser = api.BaseRoutes.User.PathPrefix("/teams/{team_id:[A-Za-z0-9]+}/channels/members").Subrouter()
api.BaseRoutes.ChannelModerations = api.BaseRoutes.Channel.PathPrefix("/moderations").Subrouter()
api.BaseRoutes.ChannelCategories = api.BaseRoutes.User.PathPrefix("/teams/{team_id:[A-Za-z0-9]+}/channels/categories").Subrouter()
api.BaseRoutes.ChannelBookmarks = api.BaseRoutes.Channel.PathPrefix("/bookmarks").Subrouter()
api.BaseRoutes.ChannelBookmark = api.BaseRoutes.ChannelBookmarks.PathPrefix("/{bookmark_id:[A-Za-z0-9]+}").Subrouter()
api.BaseRoutes.Posts = api.BaseRoutes.APIRoot.PathPrefix("/posts").Subrouter()
api.BaseRoutes.Post = api.BaseRoutes.Posts.PathPrefix("/{post_id:[A-Za-z0-9]+}").Subrouter()
@@ -323,6 +327,7 @@ func Init(srv *app.Server) (*API, error) {
api.InitHostedCustomer()
api.InitDrafts()
api.InitIPFiltering()
api.InitChannelBookmarks()
api.InitReports()
api.InitLimits()
api.InitOutgoingOAuthConnection()

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

@@ -623,6 +623,41 @@ func (th *TestHelper) CreateUserWithAuth(authService string) *model.User {
return user
}
// CreateGuestAndClient creates a guest user, adds them to the basic
// team, basic channel and basic private channel, and generates an API
// client ready to use
func (th *TestHelper) CreateGuestAndClient() (*model.User, *model.Client4) {
id := model.NewId()
// create a guest user and add it to the basic team and public/private channels
guest, cgErr := th.App.CreateGuest(th.Context, &model.User{
Email: "test_guest" + id + "@sample.com",
Username: "guest_" + id,
Nickname: "guest_" + id,
Password: "Password1",
EmailVerified: true,
})
if cgErr != nil {
panic(cgErr)
}
_, _, tErr := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, th.SystemAdminUser.Id)
if tErr != nil {
panic(tErr)
}
th.AddUserToChannel(guest, th.BasicChannel)
th.AddUserToChannel(guest, th.BasicPrivateChannel)
// create a client and login the guest
guestClient := th.CreateClient()
_, _, lErr := guestClient.Login(context.Background(), guest.Username, "Password1")
if lErr != nil {
panic(lErr)
}
return guest, guestClient
}
func (th *TestHelper) SetupLdapConfig() {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableMultifactorAuthentication = true
@@ -809,6 +844,23 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel {
return channel
}
func (th *TestHelper) PatchChannelModerationsForMembers(channelId, name string, val bool) {
patch := []*model.ChannelModerationPatch{{
Name: &name,
Roles: &model.ChannelModeratedRolesPatch{Members: model.NewBool(val)},
}}
channel, err := th.App.GetChannel(th.Context, channelId)
if err != nil {
panic(err)
}
_, err = th.App.PatchChannelModerationsForChannel(th.Context, channel, patch)
if err != nil {
panic(err)
}
}
func (th *TestHelper) LoginBasic() {
th.LoginBasicWithClient(th.Client)
}

408
server/channels/api4/channel_bookmark.go Обычный файл
Просмотреть файл

@@ -0,0 +1,408 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package api4
import (
"encoding/json"
"net/http"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/v8/channels/audit"
)
func (api *API) InitChannelBookmarks() {
if api.srv.Config().FeatureFlags.ChannelBookmarks {
api.BaseRoutes.ChannelBookmarks.Handle("", api.APISessionRequired(createChannelBookmark)).Methods("POST")
api.BaseRoutes.ChannelBookmark.Handle("", api.APISessionRequired(updateChannelBookmark)).Methods("PATCH")
api.BaseRoutes.ChannelBookmark.Handle("/sort_order", api.APISessionRequired(updateChannelBookmarkSortOrder)).Methods("POST")
api.BaseRoutes.ChannelBookmark.Handle("", api.APISessionRequired(deleteChannelBookmark)).Methods("DELETE")
api.BaseRoutes.ChannelBookmarks.Handle("", api.APISessionRequired(listChannelBookmarksForChannel)).Methods("GET")
}
}
func createChannelBookmark(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.Channels().License() == nil {
c.Err = model.NewAppError("createChannelBookmark", "api.channel.bookmark.channel_bookmark.license.error", nil, "", http.StatusNotImplemented)
return
}
connectionID := r.Header.Get(model.ConnectionId)
c.RequireChannelId()
if c.Err != nil {
return
}
channel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId)
if appErr != nil {
c.Err = appErr
return
}
var channelBookmark *model.ChannelBookmark
err := json.NewDecoder(r.Body).Decode(&channelBookmark)
if err != nil || channelBookmark == nil {
c.SetInvalidParamWithErr("channelBookmark", err)
return
}
channelBookmark.ChannelId = c.Params.ChannelId
auditRec := c.MakeAuditRecord("createChannelBookmark", audit.Fail)
defer c.LogAuditRec(auditRec)
audit.AddEventParameterAuditable(auditRec, "channelBookmark", channelBookmark)
switch channel.Type {
case model.ChannelTypeOpen:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionAddBookmarkPublicChannel) {
c.SetPermissionError(model.PermissionAddBookmarkPublicChannel)
return
}
case model.ChannelTypePrivate:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionAddBookmarkPrivateChannel) {
c.SetPermissionError(model.PermissionAddBookmarkPrivateChannel)
return
}
case model.ChannelTypeGroup, model.ChannelTypeDirect:
// Any member of DM/GMs but guests can manage channel bookmarks
if _, errGet := c.App.GetChannelMember(c.AppContext, channel.Id, c.AppContext.Session().UserId); errGet != nil {
c.Err = model.NewAppError("createChannelBookmark", "api.channel.bookmark.create_channel_bookmark.direct_or_group_channels.forbidden.app_error", nil, errGet.Message, http.StatusForbidden)
return
}
user, gAppErr := c.App.GetUser(c.AppContext.Session().UserId)
if gAppErr != nil {
c.Err = gAppErr
return
}
if user.IsGuest() {
c.Err = model.NewAppError("createChannelBookmark", "api.channel.bookmark.create_channel_bookmark.direct_or_group_channels_by_guests.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
default:
c.Err = model.NewAppError("createChannelBookmark", "api.channel.bookmark.create_channel_bookmark.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
newChannelBookmark, appErr := c.App.CreateChannelBookmark(c.AppContext, channelBookmark, connectionID)
if appErr != nil {
c.Err = appErr
return
}
auditRec.Success()
auditRec.AddEventResultState(newChannelBookmark)
auditRec.AddEventObjectType("channelBookmarkWithFileInfo")
c.LogAudit("display_name=" + newChannelBookmark.DisplayName)
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(newChannelBookmark); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func updateChannelBookmark(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.Channels().License() == nil {
c.Err = model.NewAppError("updateChannelBookmark", "api.channel.bookmark.channel_bookmark.license.error", nil, "", http.StatusNotImplemented)
return
}
connectionID := r.Header.Get(model.ConnectionId)
c.RequireChannelId()
if c.Err != nil {
return
}
var patch *model.ChannelBookmarkPatch
if err := json.NewDecoder(r.Body).Decode(&patch); err != nil || patch == nil {
c.SetInvalidParamWithErr("channelBookmarkPatch", err)
return
}
originalChannelBookmark, appErr := c.App.GetBookmark(c.Params.ChannelBookmarkId, false)
if appErr != nil {
c.Err = appErr
return
}
patchedBookmark := originalChannelBookmark.Clone()
auditRec := c.MakeAuditRecord("updateChannelBookmark", audit.Fail)
defer c.LogAuditRec(auditRec)
audit.AddEventParameterAuditable(auditRec, "channelBookmark", patch)
// The channel bookmark should belong to the same channel specified in the URL
if patchedBookmark.ChannelId != c.Params.ChannelId {
c.SetInvalidParam("channel_id")
return
}
auditRec.AddEventPriorState(originalChannelBookmark)
channel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId)
if appErr != nil {
c.Err = appErr
return
}
switch channel.Type {
case model.ChannelTypeOpen:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionEditBookmarkPublicChannel) {
c.SetPermissionError(model.PermissionEditBookmarkPublicChannel)
return
}
case model.ChannelTypePrivate:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionEditBookmarkPrivateChannel) {
c.SetPermissionError(model.PermissionEditBookmarkPrivateChannel)
return
}
case model.ChannelTypeGroup, model.ChannelTypeDirect:
// Any member of DM/GMs but guests can manage channel bookmarks
if _, errGet := c.App.GetChannelMember(c.AppContext, channel.Id, c.AppContext.Session().UserId); errGet != nil {
c.Err = model.NewAppError("updateChannelBookmark", "api.channel.bookmark.update_channel_bookmark.direct_or_group_channels.forbidden.app_error", nil, errGet.Message, http.StatusForbidden)
return
}
user, gAppErr := c.App.GetUser(c.AppContext.Session().UserId)
if gAppErr != nil {
c.Err = gAppErr
return
}
if user.IsGuest() {
c.Err = model.NewAppError("updateChannelBookmark", "api.channel.bookmark.update_channel_bookmark.direct_or_group_channels_by_guests.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
default:
c.Err = model.NewAppError("updateChannelBookmark", "api.channel.bookmark.update_channel_bookmark.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
patchedBookmark.Patch(patch)
updateChannelBookmarkResponse, appErr := c.App.UpdateChannelBookmark(c.AppContext, patchedBookmark, connectionID)
if appErr != nil {
c.Err = appErr
return
}
auditRec.Success()
auditRec.AddEventResultState(updateChannelBookmarkResponse)
auditRec.AddEventObjectType("updateChannelBookmarkResponse")
c.LogAudit("")
if err := json.NewEncoder(w).Encode(updateChannelBookmarkResponse); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func updateChannelBookmarkSortOrder(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.Channels().License() == nil {
c.Err = model.NewAppError("updateChannelBookmarkSortOrder", "api.channel.bookmark.channel_bookmark.license.error", nil, "", http.StatusNotImplemented)
return
}
connectionID := r.Header.Get(model.ConnectionId)
c.RequireChannelId()
if c.Err != nil {
return
}
var newSortOrder int64
if err := json.NewDecoder(r.Body).Decode(&newSortOrder); err != nil {
c.SetInvalidParamWithErr("channelBookmarkSortOrder", err)
return
}
if newSortOrder < 0 {
c.SetInvalidParam("channelBookmarkSortOrder")
return
}
auditRec := c.MakeAuditRecord("updateChannelBookmarkSortOrder", audit.Fail)
defer c.LogAuditRec(auditRec)
audit.AddEventParameter(auditRec, "id", c.Params.ChannelBookmarkId)
channel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId)
if appErr != nil {
c.Err = appErr
return
}
switch channel.Type {
case model.ChannelTypeOpen:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionOrderBookmarkPublicChannel) {
c.SetPermissionError(model.PermissionOrderBookmarkPublicChannel)
return
}
case model.ChannelTypePrivate:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionOrderBookmarkPrivateChannel) {
c.SetPermissionError(model.PermissionOrderBookmarkPrivateChannel)
return
}
case model.ChannelTypeGroup, model.ChannelTypeDirect:
// Any member of DM/GMs but guests can manage channel bookmarks
if _, errGet := c.App.GetChannelMember(c.AppContext, channel.Id, c.AppContext.Session().UserId); errGet != nil {
c.Err = model.NewAppError("updateChannelBookmarkSortOrder", "api.channel.bookmark.update_channel_bookmark_sort_order.direct_or_group_channels.forbidden.app_error", nil, errGet.Message, http.StatusForbidden)
return
}
user, gAppErr := c.App.GetUser(c.AppContext.Session().UserId)
if gAppErr != nil {
c.Err = gAppErr
return
}
if user.IsGuest() {
c.Err = model.NewAppError("updateChannelBookmarkSortOrder", "api.channel.bookmark.update_channel_bookmark_sort_order.direct_or_group_channels_by_guests.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
default:
c.Err = model.NewAppError("updateChannelBookmarkSortOrder", "api.channel.bookmark.update_channel_bookmark_sort_order.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
bookmarks, appErr := c.App.UpdateChannelBookmarkSortOrder(c.Params.ChannelBookmarkId, c.Params.ChannelId, newSortOrder, connectionID)
if appErr != nil {
c.Err = appErr
return
}
for _, b := range bookmarks {
if b.Id == c.Params.ChannelBookmarkId {
auditRec.AddEventResultState(b)
auditRec.AddEventObjectType("channelBookmarkWithFileInfo")
break
}
}
auditRec.Success()
c.LogAudit("")
if err := json.NewEncoder(w).Encode(bookmarks); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func deleteChannelBookmark(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.Channels().License() == nil {
c.Err = model.NewAppError("deleteChannelBookmark", "api.channel.bookmark.channel_bookmark.license.error", nil, "", http.StatusNotImplemented)
return
}
connectionID := r.Header.Get(model.ConnectionId)
c.RequireChannelId()
if c.Err != nil {
return
}
auditRec := c.MakeAuditRecord("deleteChannelBookmark", audit.Fail)
defer c.LogAuditRec(auditRec)
audit.AddEventParameter(auditRec, "id", c.Params.ChannelBookmarkId)
channel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId)
if appErr != nil {
c.Err = appErr
return
}
switch channel.Type {
case model.ChannelTypeOpen:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionDeleteBookmarkPublicChannel) {
c.SetPermissionError(model.PermissionDeleteBookmarkPublicChannel)
return
}
case model.ChannelTypePrivate:
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionDeleteBookmarkPrivateChannel) {
c.SetPermissionError(model.PermissionDeleteBookmarkPrivateChannel)
return
}
case model.ChannelTypeGroup, model.ChannelTypeDirect:
// Any member of DM/GMs but guests can manage channel bookmarks
if _, errGet := c.App.GetChannelMember(c.AppContext, channel.Id, c.AppContext.Session().UserId); errGet != nil {
c.Err = model.NewAppError("deleteChannelBookmark", "api.channel.bookmark.delete_channel_bookmark.direct_or_group_channels.forbidden.app_error", nil, errGet.Message, http.StatusForbidden)
return
}
user, gAppErr := c.App.GetUser(c.AppContext.Session().UserId)
if gAppErr != nil {
c.Err = gAppErr
return
}
if user.IsGuest() {
c.Err = model.NewAppError("deleteChannelBookmark", "api.channel.bookmark.delete_channel_bookmark.direct_or_group_channels_by_guests.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
default:
c.Err = model.NewAppError("deleteChannelBookmark", "api.channel.bookmark.delete_channel_bookmark.forbidden.app_error", nil, "", http.StatusForbidden)
return
}
oldBookmark, obErr := c.App.GetBookmark(c.Params.ChannelBookmarkId, false)
if obErr != nil {
c.Err = obErr
return
}
// The channel bookmark should belong to the same channel specified in the URL
if oldBookmark.ChannelId != c.Params.ChannelId {
c.SetInvalidParam("channel_id")
return
}
auditRec.AddEventPriorState(oldBookmark)
bookmark, appErr := c.App.DeleteChannelBookmark(c.Params.ChannelBookmarkId, connectionID)
if appErr != nil {
c.Err = appErr
return
}
auditRec.Success()
auditRec.AddEventResultState(bookmark)
c.LogAudit("bookmark=" + bookmark.DisplayName)
if err := json.NewEncoder(w).Encode(bookmark); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}
func listChannelBookmarksForChannel(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.Channels().License() == nil {
c.Err = model.NewAppError("listChannelBookmarksForChannel", "api.channel.bookmark.channel_bookmark.license.error", nil, "", http.StatusNotImplemented)
return
}
c.RequireChannelId()
if c.Err != nil {
return
}
if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannelContent) {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
bookmarks, appErr := c.App.GetChannelBookmarks(c.Params.ChannelId, c.Params.BookmarksSince)
if appErr != nil {
c.Err = appErr
return
}
if err := json.NewEncoder(w).Encode(bookmarks); err != nil {
c.Logger.Warn("Error while writing response", mlog.Err(err))
}
}

1551
server/channels/api4/channel_bookmark_test.go Обычный файл

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@@ -4230,9 +4230,9 @@ func TestGetChannelModerations(t *testing.T) {
t.Run("Returns default moderations with default roles", func(t *testing.T) {
moderations, _, err := th.SystemAdminClient.GetChannelModerations(context.Background(), channel.Id, "")
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, true)
@@ -4320,7 +4320,7 @@ func TestGetChannelModerations(t *testing.T) {
require.Nil(t, appErr)
th.RemovePermissionFromRole(model.PermissionManagePublicChannelMembers.Id, scheme.DefaultChannelUserRole)
defer th.AddPermissionToRole(model.PermissionCreatePost.Id, scheme.DefaultChannelUserRole)
defer th.AddPermissionToRole(model.PermissionManagePublicChannelMembers.Id, scheme.DefaultChannelUserRole)
// public channel does not have the permission
moderations, _, err := th.SystemAdminClient.GetChannelModerations(context.Background(), channel.Id, "")
@@ -4341,6 +4341,48 @@ func TestGetChannelModerations(t *testing.T) {
}
})
t.Run("Returns the correct value for manage_bookmarks depending on whether the channel is public or private", func(t *testing.T) {
scheme := th.SetupTeamScheme()
team.SchemeId = &scheme.Id
_, appErr := th.App.UpdateTeamScheme(team)
require.Nil(t, appErr)
bookmarkPublicPermissions := []string{
model.PermissionAddBookmarkPublicChannel.Id,
model.PermissionEditBookmarkPublicChannel.Id,
model.PermissionDeleteBookmarkPublicChannel.Id,
model.PermissionOrderBookmarkPublicChannel.Id,
}
for _, p := range bookmarkPublicPermissions {
th.RemovePermissionFromRole(p, scheme.DefaultChannelUserRole)
}
defer func() {
for _, p := range bookmarkPublicPermissions {
th.AddPermissionToRole(p, scheme.DefaultChannelUserRole)
}
}()
// public channel does not have the permissions
moderations, _, err := th.SystemAdminClient.GetChannelModerations(context.Background(), channel.Id, "")
require.NoError(t, err)
for _, moderation := range moderations {
if moderation.Name == "manage_bookmarks" {
require.Equal(t, moderation.Roles.Members.Value, false)
}
}
// private channel does have the permissions
moderations, _, err = th.SystemAdminClient.GetChannelModerations(context.Background(), th.BasicPrivateChannel.Id, "")
require.NoError(t, err)
for _, moderation := range moderations {
if moderation.Name == "manage_bookmarks" {
require.Equal(t, moderation.Roles.Members.Value, true)
}
}
})
t.Run("Does not return an error if the team scheme has a blank DefaultChannelGuestRole field", func(t *testing.T) {
scheme := th.SetupTeamScheme()
scheme.DefaultChannelGuestRole = ""
@@ -4405,9 +4447,9 @@ func TestPatchChannelModerations(t *testing.T) {
t.Run("Returns default moderations with empty patch", func(t *testing.T) {
moderations, _, err := th.SystemAdminClient.PatchChannelModerations(context.Background(), channel.Id, emptyPatch)
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, true)
@@ -4431,9 +4473,9 @@ func TestPatchChannelModerations(t *testing.T) {
moderations, _, err := th.SystemAdminClient.PatchChannelModerations(context.Background(), channel.Id, patch)
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, true)
@@ -4468,9 +4510,9 @@ func TestPatchChannelModerations(t *testing.T) {
moderations, _, err := th.SystemAdminClient.PatchChannelModerations(context.Background(), channel.Id, patch)
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, true)
@@ -4523,9 +4565,9 @@ func TestPatchChannelModerations(t *testing.T) {
moderations, _, err := th.SystemAdminClient.PatchChannelModerations(context.Background(), channel.Id, emptyPatch)
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, false)
@@ -4545,9 +4587,9 @@ func TestPatchChannelModerations(t *testing.T) {
moderations, _, err = th.SystemAdminClient.PatchChannelModerations(context.Background(), channel.Id, patch)
require.NoError(t, err)
require.Equal(t, len(moderations), 4)
require.Equal(t, len(moderations), 5)
for _, moderation := range moderations {
if moderation.Name == "manage_members" {
if moderation.Name == "manage_members" || moderation.Name == "manage_bookmarks" {
require.Empty(t, moderation.Roles.Guests)
} else {
require.Equal(t, moderation.Roles.Guests.Value, false)

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

@@ -150,9 +150,15 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F
clientId := r.Form.Get("client_id")
audit.AddEventParameter(auditRec, "client_id", clientId)
creatorId := c.AppContext.Session().UserId
if isBookmark, err := strconv.ParseBool(r.URL.Query().Get(model.BookmarkFileOwner)); err == nil && isBookmark {
creatorId = model.BookmarkFileOwner
audit.AddEventParameter(auditRec, model.BookmarkFileOwner, true)
}
info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, c.Params.Filename, r.Body,
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.AppContext.Session().UserId),
app.UploadFileSetUserId(creatorId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(r.ContentLength),
app.UploadFileSetClientId(clientId))
@@ -267,6 +273,11 @@ NextPart:
continue NextPart
}
isBookmark := false
if val, queryErr := strconv.ParseBool(r.URL.Query().Get(model.BookmarkFileOwner)); queryErr == nil {
isBookmark = val
}
// A file part.
if c.Params.ChannelId == "" && asStream == nil {
@@ -279,7 +290,7 @@ NextPart:
return nil
}
return uploadFileMultipartLegacy(c, mr, timestamp)
return uploadFileMultipartLegacy(c, mr, timestamp, isBookmark)
}
c.RequireChannelId()
@@ -312,9 +323,15 @@ NextPart:
audit.AddEventParameter(auditRec, "channel_id", c.Params.ChannelId)
audit.AddEventParameter(auditRec, "client_id", clientId)
creatorId := c.AppContext.Session().UserId
if isBookmark {
creatorId = model.BookmarkFileOwner
audit.AddEventParameter(auditRec, model.BookmarkFileOwner, true)
}
info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, filename, part,
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.AppContext.Session().UserId),
app.UploadFileSetUserId(creatorId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(-1),
app.UploadFileSetClientId(clientId))
@@ -353,7 +370,7 @@ NextPart:
// borrowing from http.ParseMultipartForm. If successful it returns a
// *model.FileUploadResponse filled in with the individual model.FileInfo's.
func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader,
timestamp time.Time) *model.FileUploadResponse {
timestamp time.Time, isBookmark bool) *model.FileUploadResponse {
// Parse the entire form.
form, err := mr.ReadForm(*c.App.Config().FileSettings.MaxFileSize)
if err != nil {
@@ -414,9 +431,15 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader,
audit.AddEventParameter(auditRec, "channel_id", channelId)
audit.AddEventParameter(auditRec, "client_id", clientId)
creatorId := c.AppContext.Session().UserId
if isBookmark {
creatorId = model.BookmarkFileOwner
audit.AddEventParameter(auditRec, model.BookmarkFileOwner, true)
}
info, appErr := c.App.UploadFileX(c.AppContext, c.Params.ChannelId, fileHeader.Filename, f,
app.UploadFileSetTeamId(FileTeamId),
app.UploadFileSetUserId(c.AppContext.Session().UserId),
app.UploadFileSetUserId(creatorId),
app.UploadFileSetTimestamp(timestamp),
app.UploadFileSetContentLength(-1),
app.UploadFileSetClientId(clientId))
@@ -461,8 +484,12 @@ func getFile(c *Context, w http.ResponseWriter, r *http.Request) {
audit.AddEventParameterAuditable(auditRec, "file", info)
perm := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), info.ChannelId, model.PermissionReadChannelContent)
if info.CreatorId != c.AppContext.Session().UserId && !perm {
if info.CreatorId == model.BookmarkFileOwner {
if !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else if info.CreatorId != c.AppContext.Session().UserId && !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
@@ -495,7 +522,12 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) {
}
perm := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), info.ChannelId, model.PermissionReadChannelContent)
if info.CreatorId != c.AppContext.Session().UserId && !perm {
if info.CreatorId == model.BookmarkFileOwner {
if !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else if info.CreatorId != c.AppContext.Session().UserId && !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
@@ -539,12 +571,17 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) {
audit.AddEventParameterAuditable(auditRec, "file", info)
perm := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), info.ChannelId, model.PermissionReadChannelContent)
if info.CreatorId != c.AppContext.Session().UserId && !perm {
if info.CreatorId == model.BookmarkFileOwner {
if !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else if info.CreatorId != c.AppContext.Session().UserId && !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
if info.PostId == "" {
if info.PostId == "" && info.CreatorId != model.BookmarkFileOwner {
c.Err = model.NewAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id, http.StatusBadRequest)
return
}
@@ -573,7 +610,12 @@ func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) {
}
perm := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), info.ChannelId, model.PermissionReadChannelContent)
if info.CreatorId != c.AppContext.Session().UserId && !perm {
if info.CreatorId == model.BookmarkFileOwner {
if !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else if info.CreatorId != c.AppContext.Session().UserId && !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
@@ -608,8 +650,12 @@ func getFileInfo(c *Context, w http.ResponseWriter, r *http.Request) {
}
perm := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), info.ChannelId, model.PermissionReadChannelContent)
if info.CreatorId != c.AppContext.Session().UserId && !perm {
if info.CreatorId == model.BookmarkFileOwner {
if !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}
} else if info.CreatorId != c.AppContext.Session().UserId && !perm {
c.SetPermissionError(model.PermissionReadChannelContent)
return
}

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

@@ -96,6 +96,7 @@ func testUploadFilesPost(
blobs [][]byte,
clientIds []string,
useChunked bool,
isBookmark bool,
) (*model.FileUploadResponse, *model.Response, error) {
// Do not check len(clientIds), leave it entirely to the user to
// provide. The server will error out if it does not match the number
@@ -120,6 +121,10 @@ func testUploadFilesPost(
postURL += fmt.Sprintf("&client_id=%v", url.QueryEscape(clientIds[i]))
}
if isBookmark {
postURL += "&bookmark=true"
}
fur, resp, err := testDoUploadFileRequest(t, c, postURL, blob, ct, cl)
if err != nil {
return nil, resp, err
@@ -145,6 +150,7 @@ func testUploadFilesMultipart(
names []string,
blobs [][]byte,
clientIds []string,
isBookmark bool,
) (
*model.FileUploadResponse,
*model.Response,
@@ -185,7 +191,11 @@ func testUploadFilesMultipart(
}
require.NoError(t, mw.Close())
fur, resp, err := testDoUploadFileRequest(t, c, "", mwBody.Bytes(), mw.FormDataContentType(), -1)
url := ""
if isBookmark {
url += "?bookmark=true"
}
fur, resp, err := testDoUploadFileRequest(t, c, url, mwBody.Bytes(), mw.FormDataContentType(), -1)
if err != nil {
return nil, resp, err
}
@@ -230,6 +240,7 @@ func TestUploadFiles(t *testing.T) {
expectedImageMiniPreview []bool
setupConfig func(a *app.App) func(a *app.App)
checkResponse func(t testing.TB, resp *model.Response)
uploadAsBookmark bool
}{
// Upload a bunch of files, mixed images and non-images
{
@@ -578,6 +589,20 @@ func TestUploadFiles(t *testing.T) {
}
},
},
{
title: "Bookmark images",
names: []string{"orientation_test_5.jpeg"},
expectedImageThumbnailNames: []string{"orientation_test_5_expected_thumb.jpeg"},
expectedImagePreviewNames: []string{"orientation_test_5_expected_preview.jpeg"},
channelId: channel.Id,
expectImage: true,
expectedCreatorId: model.BookmarkFileOwner,
expectedImageWidths: []int{2860},
expectedImageHeights: []int{1578},
expectedImageHasPreview: []bool{true},
expectedImageMiniPreview: []bool{true},
uploadAsBookmark: true,
},
}
for _, useMultipart := range []bool{true, false} {
@@ -627,9 +652,9 @@ func TestUploadFiles(t *testing.T) {
var resp *model.Response
var err error
if useMultipart {
fileResp, resp, err = testUploadFilesMultipart(t, client, channelId, tc.names, blobs, tc.clientIds)
fileResp, resp, err = testUploadFilesMultipart(t, client, channelId, tc.names, blobs, tc.clientIds, tc.uploadAsBookmark)
} else {
fileResp, resp, err = testUploadFilesPost(t, client, channelId, tc.names, blobs, tc.clientIds, tc.useChunkedInSimplePost)
fileResp, resp, err = testUploadFilesPost(t, client, channelId, tc.names, blobs, tc.clientIds, tc.useChunkedInSimplePost, tc.uploadAsBookmark)
}
if tc.checkResponse != nil {
@@ -672,6 +697,9 @@ func TestUploadFiles(t *testing.T) {
ext := filepath.Ext(fname)
name := fname[:len(fname)-len(ext)]
expectedDir := fmt.Sprintf("%v/teams/%v/channels/%v/users/%s/%s", date, FileTeamId, channel.Id, ri.CreatorId, ri.Id)
if tc.uploadAsBookmark {
expectedDir = fmt.Sprintf("%v/teams/%v/channels/%v/%s", model.BookmarkFileOwner, FileTeamId, channel.Id, ri.Id)
}
expectedPath := fmt.Sprintf("%s/%s", expectedDir, fname)
assert.Equal(t, dbInfo.Path, expectedPath,
fmt.Sprintf("File %v saved to:%q, expected:%q", dbInfo.Name, dbInfo.Path, expectedPath))
@@ -774,7 +802,7 @@ func TestGetFile(t *testing.T) {
CheckUnauthorizedStatus(t, resp)
_, _, err = th.SystemAdminClient.GetFile(context.Background(), fileId)
require.Error(t, err)
require.NoError(t, err)
CheckUnauthorizedStatus(t, resp)
}
@@ -889,7 +917,7 @@ func TestGetFileThumbnail(t *testing.T) {
client.Logout(context.Background())
_, _, err = th.SystemAdminClient.GetFileThumbnail(context.Background(), fileId)
require.Error(t, err)
require.NoError(t, err)
CheckForbiddenStatus(t, resp)
}
@@ -1002,7 +1030,7 @@ func TestGetFilePreview(t *testing.T) {
client.Logout(context.Background())
_, _, err = th.SystemAdminClient.GetFilePreview(context.Background(), fileId)
require.Error(t, err)
require.NoError(t, err)
CheckForbiddenStatus(t, resp)
}
@@ -1027,7 +1055,6 @@ func TestGetFileInfo(t *testing.T) {
info, _, err := client.GetFileInfo(context.Background(), fileId)
require.NoError(t, err)
require.NoError(t, err)
require.Equal(t, fileId, info.Id, "got incorrect file")
require.Equal(t, user.Id, info.CreatorId, "file should be assigned to user")
require.Equal(t, "", info.PostId, "file shouldn't have a post")
@@ -1057,7 +1084,7 @@ func TestGetFileInfo(t *testing.T) {
client.Logout(context.Background())
_, _, err = th.SystemAdminClient.GetFileInfo(context.Background(), fileId)
require.Error(t, err)
require.NoError(t, err)
CheckForbiddenStatus(t, resp)
}