Skip to content

Commit 6d27703

Browse files
authored
[API] List, Check, Add & delete endpoints for repository teams (#13630)
* List, Check, Add & delete endpoints for repository teams * return units on single team responce too * Add Tests
1 parent a918863 commit 6d27703

File tree

4 files changed

+483
-0
lines changed

4 files changed

+483
-0
lines changed

integrations/api_repo_teams_test.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Copyright 2021 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package integrations
6+
7+
import (
8+
"fmt"
9+
"net/http"
10+
"testing"
11+
12+
"code.gitea.io/gitea/models"
13+
api "code.gitea.io/gitea/modules/structs"
14+
15+
"github.com/stretchr/testify/assert"
16+
)
17+
18+
func TestAPIRepoTeams(t *testing.T) {
19+
defer prepareTestEnv(t)()
20+
21+
// publicOrgRepo = user3/repo21
22+
publicOrgRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository)
23+
// user4
24+
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
25+
session := loginUser(t, user.Name)
26+
token := getTokenForLoggedInUser(t, session)
27+
28+
// ListTeams
29+
url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token)
30+
req := NewRequest(t, "GET", url)
31+
res := session.MakeRequest(t, req, http.StatusOK)
32+
var teams []*api.Team
33+
DecodeJSON(t, res, &teams)
34+
if assert.Len(t, teams, 2) {
35+
assert.EqualValues(t, "Owners", teams[0].Name)
36+
assert.EqualValues(t, false, teams[0].CanCreateOrgRepo)
37+
assert.EqualValues(t, []string{"repo.code", "repo.issues", "repo.pulls", "repo.releases", "repo.wiki", "repo.ext_wiki", "repo.ext_issues"}, teams[0].Units)
38+
assert.EqualValues(t, "owner", teams[0].Permission)
39+
40+
assert.EqualValues(t, "test_team", teams[1].Name)
41+
assert.EqualValues(t, false, teams[1].CanCreateOrgRepo)
42+
assert.EqualValues(t, []string{"repo.issues"}, teams[1].Units)
43+
assert.EqualValues(t, "write", teams[1].Permission)
44+
}
45+
46+
// IsTeam
47+
url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "Test_Team", token)
48+
req = NewRequest(t, "GET", url)
49+
res = session.MakeRequest(t, req, http.StatusOK)
50+
var team *api.Team
51+
DecodeJSON(t, res, &team)
52+
assert.EqualValues(t, teams[1], team)
53+
54+
url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "NonExistingTeam", token)
55+
req = NewRequest(t, "GET", url)
56+
res = session.MakeRequest(t, req, http.StatusNotFound)
57+
58+
// AddTeam with user4
59+
url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token)
60+
req = NewRequest(t, "PUT", url)
61+
res = session.MakeRequest(t, req, http.StatusForbidden)
62+
63+
// AddTeam with user2
64+
user = models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
65+
session = loginUser(t, user.Name)
66+
token = getTokenForLoggedInUser(t, session)
67+
url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token)
68+
req = NewRequest(t, "PUT", url)
69+
res = session.MakeRequest(t, req, http.StatusNoContent)
70+
res = session.MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request
71+
72+
// DeleteTeam
73+
url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token)
74+
req = NewRequest(t, "DELETE", url)
75+
res = session.MakeRequest(t, req, http.StatusNoContent)
76+
res = session.MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request
77+
}

routers/api/v1/api.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,12 @@ func Routes() *web.Route {
727727
Put(reqAdmin(), bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
728728
Delete(reqAdmin(), repo.DeleteCollaborator)
729729
}, reqToken())
730+
m.Group("/teams", func() {
731+
m.Get("", reqAnyRepoReader(), repo.ListTeams)
732+
m.Combo("/{team}").Get(reqAnyRepoReader(), repo.IsTeam).
733+
Put(reqAdmin(), repo.AddTeam).
734+
Delete(reqAdmin(), repo.DeleteTeam)
735+
}, reqToken())
730736
m.Get("/raw/*", context.RepoRefForAPI, reqRepoReader(models.UnitTypeCode), repo.GetRawFile)
731737
m.Get("/archive/*", reqRepoReader(models.UnitTypeCode), repo.GetArchive)
732738
m.Combo("/forks").Get(repo.ListForks).

routers/api/v1/repo/teams.go

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
// Copyright 2020 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package repo
6+
7+
import (
8+
"fmt"
9+
"net/http"
10+
11+
"code.gitea.io/gitea/models"
12+
"code.gitea.io/gitea/modules/context"
13+
"code.gitea.io/gitea/modules/convert"
14+
api "code.gitea.io/gitea/modules/structs"
15+
)
16+
17+
// ListTeams list a repository's teams
18+
func ListTeams(ctx *context.APIContext) {
19+
// swagger:operation GET /repos/{owner}/{repo}/teams repository repoListTeams
20+
// ---
21+
// summary: List a repository's teams
22+
// produces:
23+
// - application/json
24+
// parameters:
25+
// - name: owner
26+
// in: path
27+
// description: owner of the repo
28+
// type: string
29+
// required: true
30+
// - name: repo
31+
// in: path
32+
// description: name of the repo
33+
// type: string
34+
// required: true
35+
// responses:
36+
// "200":
37+
// "$ref": "#/responses/TeamList"
38+
39+
if !ctx.Repo.Owner.IsOrganization() {
40+
ctx.Error(http.StatusMethodNotAllowed, "noOrg", "repo is not owned by an organization")
41+
return
42+
}
43+
44+
teams, err := ctx.Repo.Repository.GetRepoTeams()
45+
if err != nil {
46+
ctx.InternalServerError(err)
47+
return
48+
}
49+
50+
apiTeams := make([]*api.Team, len(teams))
51+
for i := range teams {
52+
if err := teams[i].GetUnits(); err != nil {
53+
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
54+
return
55+
}
56+
57+
apiTeams[i] = convert.ToTeam(teams[i])
58+
}
59+
60+
ctx.JSON(http.StatusOK, apiTeams)
61+
}
62+
63+
// IsTeam check if a team is assigned to a repository
64+
func IsTeam(ctx *context.APIContext) {
65+
// swagger:operation GET /repos/{owner}/{repo}/teams/{team} repository repoCheckTeam
66+
// ---
67+
// summary: Check if a team is assigned to a repository
68+
// produces:
69+
// - application/json
70+
// parameters:
71+
// - name: owner
72+
// in: path
73+
// description: owner of the repo
74+
// type: string
75+
// required: true
76+
// - name: repo
77+
// in: path
78+
// description: name of the repo
79+
// type: string
80+
// required: true
81+
// - name: team
82+
// in: path
83+
// description: team name
84+
// type: string
85+
// required: true
86+
// responses:
87+
// "200":
88+
// "$ref": "#/responses/Team"
89+
// "404":
90+
// "$ref": "#/responses/notFound"
91+
// "405":
92+
// "$ref": "#/responses/error"
93+
94+
if !ctx.Repo.Owner.IsOrganization() {
95+
ctx.Error(http.StatusMethodNotAllowed, "noOrg", "repo is not owned by an organization")
96+
return
97+
}
98+
99+
team := getTeamByParam(ctx)
100+
if team == nil {
101+
return
102+
}
103+
104+
if team.HasRepository(ctx.Repo.Repository.ID) {
105+
if err := team.GetUnits(); err != nil {
106+
ctx.Error(http.StatusInternalServerError, "GetUnits", err)
107+
return
108+
}
109+
apiTeam := convert.ToTeam(team)
110+
ctx.JSON(http.StatusOK, apiTeam)
111+
return
112+
}
113+
114+
ctx.NotFound()
115+
}
116+
117+
// AddTeam add a team to a repository
118+
func AddTeam(ctx *context.APIContext) {
119+
// swagger:operation PUT /repos/{owner}/{repo}/teams/{team} repository repoAddTeam
120+
// ---
121+
// summary: Add a team to a repository
122+
// produces:
123+
// - application/json
124+
// parameters:
125+
// - name: owner
126+
// in: path
127+
// description: owner of the repo
128+
// type: string
129+
// required: true
130+
// - name: repo
131+
// in: path
132+
// description: name of the repo
133+
// type: string
134+
// required: true
135+
// - name: team
136+
// in: path
137+
// description: team name
138+
// type: string
139+
// required: true
140+
// responses:
141+
// "204":
142+
// "$ref": "#/responses/empty"
143+
// "422":
144+
// "$ref": "#/responses/validationError"
145+
// "405":
146+
// "$ref": "#/responses/error"
147+
148+
changeRepoTeam(ctx, true)
149+
}
150+
151+
// DeleteTeam delete a team from a repository
152+
func DeleteTeam(ctx *context.APIContext) {
153+
// swagger:operation DELETE /repos/{owner}/{repo}/teams/{team} repository repoDeleteTeam
154+
// ---
155+
// summary: Delete a team from a repository
156+
// produces:
157+
// - application/json
158+
// parameters:
159+
// - name: owner
160+
// in: path
161+
// description: owner of the repo
162+
// type: string
163+
// required: true
164+
// - name: repo
165+
// in: path
166+
// description: name of the repo
167+
// type: string
168+
// required: true
169+
// - name: team
170+
// in: path
171+
// description: team name
172+
// type: string
173+
// required: true
174+
// responses:
175+
// "204":
176+
// "$ref": "#/responses/empty"
177+
// "422":
178+
// "$ref": "#/responses/validationError"
179+
// "405":
180+
// "$ref": "#/responses/error"
181+
182+
changeRepoTeam(ctx, false)
183+
}
184+
185+
func changeRepoTeam(ctx *context.APIContext, add bool) {
186+
if !ctx.Repo.Owner.IsOrganization() {
187+
ctx.Error(http.StatusMethodNotAllowed, "noOrg", "repo is not owned by an organization")
188+
}
189+
if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
190+
ctx.Error(http.StatusForbidden, "noAdmin", "user is nor repo admin nor owner")
191+
return
192+
}
193+
194+
team := getTeamByParam(ctx)
195+
if team == nil {
196+
return
197+
}
198+
199+
repoHasTeam := team.HasRepository(ctx.Repo.Repository.ID)
200+
var err error
201+
if add {
202+
if repoHasTeam {
203+
ctx.Error(http.StatusUnprocessableEntity, "alreadyAdded", fmt.Errorf("team '%s' is already added to repo", team.Name))
204+
return
205+
}
206+
err = team.AddRepository(ctx.Repo.Repository)
207+
} else {
208+
if !repoHasTeam {
209+
ctx.Error(http.StatusUnprocessableEntity, "notAdded", fmt.Errorf("team '%s' was not added to repo", team.Name))
210+
return
211+
}
212+
err = team.RemoveRepository(ctx.Repo.Repository.ID)
213+
}
214+
if err != nil {
215+
ctx.InternalServerError(err)
216+
return
217+
}
218+
219+
ctx.Status(http.StatusNoContent)
220+
}
221+
222+
func getTeamByParam(ctx *context.APIContext) *models.Team {
223+
team, err := models.GetTeam(ctx.Repo.Owner.ID, ctx.Params(":team"))
224+
if err != nil {
225+
if models.IsErrTeamNotExist(err) {
226+
ctx.Error(http.StatusNotFound, "TeamNotExit", err)
227+
return nil
228+
}
229+
ctx.InternalServerError(err)
230+
return nil
231+
}
232+
return team
233+
}

0 commit comments

Comments
 (0)