Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to search only for linkable boards #3553

Merged
merged 3 commits into from
Aug 5, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('components/boardSelector', () => {
})

it('renders with no results', async () => {
mockedOctoClient.search.mockResolvedValueOnce([])
mockedOctoClient.searchLinkableBoards.mockResolvedValueOnce([])

const store = mockStateStore([], state)
const {container} = render(wrapIntl(
Expand All @@ -74,7 +74,7 @@ describe('components/boardSelector', () => {
})

it('renders with some results', async () => {
mockedOctoClient.search.mockResolvedValueOnce([createBoard(), createBoard(), createBoard()])
mockedOctoClient.searchLinkableBoards.mockResolvedValueOnce([createBoard(), createBoard(), createBoard()])

const store = mockStateStore([], state)
const {container} = render(wrapIntl(
Expand Down
2 changes: 1 addition & 1 deletion mattermost-plugin/webapp/src/components/boardSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const BoardSelector = () => {
if (query.trim().length === 0 || !teamId) {
return
}
const items = await octoClient.search(teamId, query)
const items = await octoClient.searchLinkableBoards(teamId, query)

setResults(items)
setIsSearching(false)
Expand Down
90 changes: 90 additions & 0 deletions server/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func (a *API) RegisterRoutes(r *mux.Router) {
apiv2.HandleFunc("/teams/{teamID}/channels/{channelID}", a.sessionRequired(a.handleGetChannel)).Methods("GET")
apiv2.HandleFunc("/teams/{teamID}/boards", a.sessionRequired(a.handleGetBoards)).Methods("GET")
apiv2.HandleFunc("/teams/{teamID}/boards/search", a.sessionRequired(a.handleSearchBoards)).Methods("GET")
apiv2.HandleFunc("/teams/{teamID}/boards/search/linkable", a.sessionRequired(a.handleSearchLinkableBoards)).Methods("GET")
apiv2.HandleFunc("/teams/{teamID}/templates", a.sessionRequired(a.handleGetTemplates)).Methods("GET")
apiv2.HandleFunc("/boards", a.sessionRequired(a.handleCreateBoard)).Methods("POST")
apiv2.HandleFunc("/boards/search", a.sessionRequired(a.handleSearchAllBoards)).Methods("GET")
Expand Down Expand Up @@ -3514,6 +3515,95 @@ func (a *API) handleSearchBoards(w http.ResponseWriter, r *http.Request) {
auditRec.Success()
}

func (a *API) handleSearchLinkableBoards(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /teams/{teamID}/boards/search/linkable searchLinkableBoards
//
// Returns the boards that match with a search term in the team and the
// user has permission to manage members
//
// ---
// produces:
// - application/json
// parameters:
// - name: teamID
// in: path
// description: Team ID
// required: true
// type: string
// - name: q
// in: query
// description: The search term. Must have at least one character
// required: true
// type: string
// security:
// - BearerAuth: []
// responses:
// '200':
// description: success
// schema:
// type: array
// items:
// "$ref": "#/definitions/Board"
// default:
// description: internal error
// schema:
// "$ref": "#/definitions/ErrorResponse"

if !a.MattermostAuth {
a.errorResponse(w, r.URL.Path, http.StatusNotImplemented, "not permitted in standalone mode", nil)
return
}

teamID := mux.Vars(r)["teamID"]
term := r.URL.Query().Get("q")
userID := getUserID(r)

if !a.permissions.HasPermissionToTeam(userID, teamID, model.PermissionViewTeam) {
a.errorResponse(w, r.URL.Path, http.StatusForbidden, "", PermissionError{"access denied to team"})
return
}

if len(term) == 0 {
jsonStringResponse(w, http.StatusOK, "[]")
return
}

auditRec := a.makeAuditRecord(r, "searchLinkableBoards", audit.Fail)
defer a.audit.LogRecord(audit.LevelRead, auditRec)
auditRec.AddMeta("teamID", teamID)

// retrieve boards list
boards, err := a.app.SearchBoardsForUserInTeam(teamID, term, userID)
if err != nil {
a.errorResponse(w, r.URL.Path, http.StatusInternalServerError, "", err)
return
}

linkableBoards := []*model.Board{}
for _, board := range boards {
if a.permissions.HasPermissionToBoard(userID, board.ID, model.PermissionManageBoardRoles) {
linkableBoards = append(linkableBoards, board)
}
}

a.logger.Debug("SearchLinkableBoards",
mlog.String("teamID", teamID),
mlog.Int("boardsCount", len(linkableBoards)),
)

data, err := json.Marshal(linkableBoards)
if err != nil {
a.errorResponse(w, r.URL.Path, http.StatusInternalServerError, "", err)
return
}

// response
jsonBytesResponse(w, http.StatusOK, data)

auditRec.AddMeta("boardsCount", len(linkableBoards))
auditRec.Success()
}

func (a *API) handleSearchAllBoards(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /boards/search searchBoards
//
Expand Down
37 changes: 37 additions & 0 deletions server/integrationtests/permissions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,43 @@ func TestPermissionsSearchTeamBoards(t *testing.T) {
})
}

func TestPermissionsSearchTeamLinkableBoards(t *testing.T) {
t.Run("plugin", func(t *testing.T) {
th := SetupTestHelperPluginMode(t)
defer th.TearDown()
clients := setupClients(th)
testData := setupData(t, th)
ttCases := []TestCase{
// Search boards
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userAnon, http.StatusUnauthorized, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userNoTeamMember, http.StatusForbidden, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userTeamMember, http.StatusOK, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userViewer, http.StatusOK, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userCommenter, http.StatusOK, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userEditor, http.StatusOK, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userAdmin, http.StatusOK, 2},
}
runTestCases(t, ttCases, testData, clients)
})
t.Run("local", func(t *testing.T) {
th := SetupTestHelperLocalMode(t)
defer th.TearDown()
clients := setupLocalClients(th)
testData := setupData(t, th)
ttCases := []TestCase{
// Search boards
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userAnon, http.StatusUnauthorized, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userNoTeamMember, http.StatusNotImplemented, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userTeamMember, http.StatusNotImplemented, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userViewer, http.StatusNotImplemented, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userCommenter, http.StatusNotImplemented, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userEditor, http.StatusNotImplemented, 0},
{"/teams/test-team/boards/search/linkable?q=b", methodGet, "", userAdmin, http.StatusNotImplemented, 0},
}
runTestCases(t, ttCases, testData, clients)
})
}

func TestPermissionsGetTeamTemplates(t *testing.T) {
extraSetup := func(t *testing.T, th *TestHelper) {
err := th.Server.App().InitTemplates()
Expand Down
14 changes: 14 additions & 0 deletions webapp/src/octoClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,20 @@ class OctoClient {
return (await this.getJson(response, [])) as Array<Board>
}

async searchLinkableBoards(teamID: string, query: string): Promise<Array<Board>> {
const url = `${this.teamPath(teamID)}/boards/search/linkable?q=${encodeURIComponent(query)}`
const response = await fetch(this.getBaseURL() + url, {
method: 'GET',
headers: this.headers(),
})

if (response.status !== 200) {
return []
}

return (await this.getJson(response, [])) as Array<Board>
}

async searchAll(query: string): Promise<Array<Board>> {
const url = `/api/v2/boards/search?q=${encodeURIComponent(query)}`
const response = await fetch(this.getBaseURL() + url, {
Expand Down