Skip to content

Commit d0a681f

Browse files
romdum6543
andauthored
[API] Add endpount to get user org permissions (#17232)
* Add endpoint * Add swagger response + generate swagger * Stop execution if user / org is not found * Add tests Co-authored-by: 6543 <[email protected]>
1 parent 7b87231 commit d0a681f

File tree

7 files changed

+325
-1
lines changed

7 files changed

+325
-1
lines changed
+149
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
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+
api "code.gitea.io/gitea/modules/structs"
13+
"github.com/stretchr/testify/assert"
14+
)
15+
16+
type apiUserOrgPermTestCase struct {
17+
LoginUser string
18+
User string
19+
Organization string
20+
ExpectedOrganizationPermissions api.OrganizationPermissions
21+
}
22+
23+
func TestTokenNeeded(t *testing.T) {
24+
defer prepareTestEnv(t)()
25+
26+
session := emptyTestSession(t)
27+
req := NewRequest(t, "GET", "/api/v1/users/user1/orgs/user6/permissions")
28+
session.MakeRequest(t, req, http.StatusUnauthorized)
29+
}
30+
31+
func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) {
32+
defer prepareTestEnv(t)()
33+
34+
session := loginUser(t, auoptc.LoginUser)
35+
token := getTokenForLoggedInUser(t, session)
36+
37+
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token))
38+
resp := session.MakeRequest(t, req, http.StatusOK)
39+
40+
var apiOP api.OrganizationPermissions
41+
DecodeJSON(t, resp, &apiOP)
42+
assert.Equal(t, auoptc.ExpectedOrganizationPermissions.IsOwner, apiOP.IsOwner)
43+
assert.Equal(t, auoptc.ExpectedOrganizationPermissions.IsAdmin, apiOP.IsAdmin)
44+
assert.Equal(t, auoptc.ExpectedOrganizationPermissions.CanWrite, apiOP.CanWrite)
45+
assert.Equal(t, auoptc.ExpectedOrganizationPermissions.CanRead, apiOP.CanRead)
46+
assert.Equal(t, auoptc.ExpectedOrganizationPermissions.CanCreateRepository, apiOP.CanCreateRepository)
47+
}
48+
49+
func TestWithOwnerUser(t *testing.T) {
50+
sampleTest(t, apiUserOrgPermTestCase{
51+
LoginUser: "user2",
52+
User: "user2",
53+
Organization: "user3",
54+
ExpectedOrganizationPermissions: api.OrganizationPermissions{
55+
IsOwner: true,
56+
IsAdmin: true,
57+
CanWrite: true,
58+
CanRead: true,
59+
CanCreateRepository: true,
60+
},
61+
})
62+
}
63+
64+
func TestCanWriteUser(t *testing.T) {
65+
sampleTest(t, apiUserOrgPermTestCase{
66+
LoginUser: "user4",
67+
User: "user4",
68+
Organization: "user3",
69+
ExpectedOrganizationPermissions: api.OrganizationPermissions{
70+
IsOwner: false,
71+
IsAdmin: false,
72+
CanWrite: true,
73+
CanRead: true,
74+
CanCreateRepository: false,
75+
},
76+
})
77+
}
78+
79+
func TestAdminUser(t *testing.T) {
80+
sampleTest(t, apiUserOrgPermTestCase{
81+
LoginUser: "user1",
82+
User: "user28",
83+
Organization: "user3",
84+
ExpectedOrganizationPermissions: api.OrganizationPermissions{
85+
IsOwner: false,
86+
IsAdmin: true,
87+
CanWrite: true,
88+
CanRead: true,
89+
CanCreateRepository: true,
90+
},
91+
})
92+
}
93+
94+
func TestAdminCanNotCreateRepo(t *testing.T) {
95+
sampleTest(t, apiUserOrgPermTestCase{
96+
LoginUser: "user1",
97+
User: "user28",
98+
Organization: "user6",
99+
ExpectedOrganizationPermissions: api.OrganizationPermissions{
100+
IsOwner: false,
101+
IsAdmin: true,
102+
CanWrite: true,
103+
CanRead: true,
104+
CanCreateRepository: false,
105+
},
106+
})
107+
}
108+
109+
func TestCanReadUser(t *testing.T) {
110+
sampleTest(t, apiUserOrgPermTestCase{
111+
LoginUser: "user1",
112+
User: "user24",
113+
Organization: "org25",
114+
ExpectedOrganizationPermissions: api.OrganizationPermissions{
115+
IsOwner: false,
116+
IsAdmin: false,
117+
CanWrite: false,
118+
CanRead: true,
119+
CanCreateRepository: false,
120+
},
121+
})
122+
}
123+
124+
func TestUnknowUser(t *testing.T) {
125+
defer prepareTestEnv(t)()
126+
127+
session := loginUser(t, "user1")
128+
token := getTokenForLoggedInUser(t, session)
129+
130+
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token))
131+
resp := session.MakeRequest(t, req, http.StatusNotFound)
132+
133+
var apiError api.APIError
134+
DecodeJSON(t, resp, &apiError)
135+
assert.Equal(t, "GetUserByName", apiError.Message)
136+
}
137+
138+
func TestUnknowOrganization(t *testing.T) {
139+
defer prepareTestEnv(t)()
140+
141+
session := loginUser(t, "user1")
142+
token := getTokenForLoggedInUser(t, session)
143+
144+
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token))
145+
resp := session.MakeRequest(t, req, http.StatusNotFound)
146+
var apiError api.APIError
147+
DecodeJSON(t, resp, &apiError)
148+
assert.Equal(t, "GetUserByName", apiError.Message)
149+
}

models/org.go

+13
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,19 @@ func CanCreateOrgRepo(orgID, uid int64) (bool, error) {
392392
Exist(new(Team))
393393
}
394394

395+
// GetOrgUserMaxAuthorizeLevel returns highest authorize level of user in an organization
396+
func (org *User) GetOrgUserMaxAuthorizeLevel(uid int64) (AccessMode, error) {
397+
var authorize AccessMode
398+
_, err := db.GetEngine(db.DefaultContext).
399+
Select("max(team.authorize)").
400+
Table("team").
401+
Join("INNER", "team_user", "team_user.team_id = team.id").
402+
Where("team_user.uid = ?", uid).
403+
And("team_user.org_id = ?", org.ID).
404+
Get(&authorize)
405+
return authorize, err
406+
}
407+
395408
// GetUsersWhoCanCreateOrgRepo returns users which are able to create repo in organization
396409
func GetUsersWhoCanCreateOrgRepo(orgID int64) ([]*User, error) {
397410
return getUsersWhoCanCreateOrgRepo(db.GetEngine(db.DefaultContext), orgID)

modules/structs/org.go

+9
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ type Organization struct {
1717
RepoAdminChangeTeamAccess bool `json:"repo_admin_change_team_access"`
1818
}
1919

20+
// OrganizationPermissions list differents users permissions on an organization
21+
type OrganizationPermissions struct {
22+
IsOwner bool `json:"is_owner"`
23+
IsAdmin bool `json:"is_admin"`
24+
CanWrite bool `json:"can_write"`
25+
CanRead bool `json:"can_read"`
26+
CanCreateRepository bool `json:"can_create_repository"`
27+
}
28+
2029
// CreateOrgOption options for creating an organization
2130
type CreateOrgOption struct {
2231
// required: true

routers/api/v1/api.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -973,7 +973,10 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route {
973973

974974
// Organizations
975975
m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
976-
m.Get("/users/{username}/orgs", org.ListUserOrgs)
976+
m.Group("/users/{username}/orgs", func() {
977+
m.Get("", org.ListUserOrgs)
978+
m.Get("/{org}/permissions", reqToken(), org.GetUserOrgsPermissions)
979+
})
977980
m.Post("/orgs", reqToken(), bind(api.CreateOrgOption{}), org.Create)
978981
m.Get("/orgs", org.GetAll)
979982
m.Group("/orgs/{org}", func() {

routers/api/v1/org/org.go

+71
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,77 @@ func ListUserOrgs(ctx *context.APIContext) {
9797
listUserOrgs(ctx, u)
9898
}
9999

100+
// GetUserOrgsPermissions get user permissions in organization
101+
func GetUserOrgsPermissions(ctx *context.APIContext) {
102+
// swagger:operation GET /users/{username}/orgs/{org}/permissions organization orgGetUserPermissions
103+
// ---
104+
// summary: Get user permissions in organization
105+
// produces:
106+
// - application/json
107+
// parameters:
108+
// - name: username
109+
// in: path
110+
// description: username of user
111+
// type: string
112+
// required: true
113+
// - name: org
114+
// in: path
115+
// description: name of the organization
116+
// type: string
117+
// required: true
118+
// responses:
119+
// "200":
120+
// "$ref": "#/responses/OrganizationPermissions"
121+
// "403":
122+
// "$ref": "#/responses/forbidden"
123+
// "404":
124+
// "$ref": "#/responses/notFound"
125+
126+
var u *models.User
127+
if u = user.GetUserByParams(ctx); u == nil {
128+
return
129+
}
130+
131+
var o *models.User
132+
if o = user.GetUserByParamsName(ctx, ":org"); o == nil {
133+
return
134+
}
135+
136+
op := api.OrganizationPermissions{}
137+
138+
if !models.HasOrgOrUserVisible(o, u) {
139+
ctx.NotFound("HasOrgOrUserVisible", nil)
140+
return
141+
}
142+
143+
authorizeLevel, err := o.GetOrgUserMaxAuthorizeLevel(u.ID)
144+
if err != nil {
145+
ctx.Error(http.StatusInternalServerError, "GetOrgUserAuthorizeLevel", err)
146+
return
147+
}
148+
149+
if authorizeLevel > models.AccessModeNone {
150+
op.CanRead = true
151+
}
152+
if authorizeLevel > models.AccessModeRead {
153+
op.CanWrite = true
154+
}
155+
if authorizeLevel > models.AccessModeWrite {
156+
op.IsAdmin = true
157+
}
158+
if authorizeLevel > models.AccessModeAdmin {
159+
op.IsOwner = true
160+
}
161+
162+
op.CanCreateRepository, err = o.CanCreateOrgRepo(u.ID)
163+
if err != nil {
164+
ctx.Error(http.StatusInternalServerError, "CanCreateOrgRepo", err)
165+
return
166+
}
167+
168+
ctx.JSON(http.StatusOK, op)
169+
}
170+
100171
// GetAll return list of all public organizations
101172
func GetAll(ctx *context.APIContext) {
102173
// swagger:operation Get /orgs organization orgGetAll

routers/api/v1/swagger/org.go

+7
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,10 @@ type swaggerResponseTeamList struct {
3535
// in:body
3636
Body []api.Team `json:"body"`
3737
}
38+
39+
// OrganizationPermissions
40+
// swagger:response OrganizationPermissions
41+
type swaggerResponseOrganizationPermissions struct {
42+
// in:body
43+
Body api.OrganizationPermissions `json:"body"`
44+
}

templates/swagger/v1_json.tmpl

+72
Original file line numberDiff line numberDiff line change
@@ -11856,6 +11856,45 @@
1185611856
}
1185711857
}
1185811858
},
11859+
"/users/{username}/orgs/{org}/permissions": {
11860+
"get": {
11861+
"produces": [
11862+
"application/json"
11863+
],
11864+
"tags": [
11865+
"organization"
11866+
],
11867+
"summary": "Get user permissions in organization",
11868+
"operationId": "orgGetUserPermissions",
11869+
"parameters": [
11870+
{
11871+
"type": "string",
11872+
"description": "username of user",
11873+
"name": "username",
11874+
"in": "path",
11875+
"required": true
11876+
},
11877+
{
11878+
"type": "string",
11879+
"description": "name of the organization",
11880+
"name": "org",
11881+
"in": "path",
11882+
"required": true
11883+
}
11884+
],
11885+
"responses": {
11886+
"200": {
11887+
"$ref": "#/responses/OrganizationPermissions"
11888+
},
11889+
"403": {
11890+
"$ref": "#/responses/forbidden"
11891+
},
11892+
"404": {
11893+
"$ref": "#/responses/notFound"
11894+
}
11895+
}
11896+
}
11897+
},
1185911898
"/users/{username}/repos": {
1186011899
"get": {
1186111900
"produces": [
@@ -15877,6 +15916,33 @@
1587715916
},
1587815917
"x-go-package": "code.gitea.io/gitea/modules/structs"
1587915918
},
15919+
"OrganizationPermissions": {
15920+
"description": "OrganizationPermissions list differents users permissions on an organization",
15921+
"type": "object",
15922+
"properties": {
15923+
"can_create_repository": {
15924+
"type": "boolean",
15925+
"x-go-name": "CanCreateRepository"
15926+
},
15927+
"can_read": {
15928+
"type": "boolean",
15929+
"x-go-name": "CanRead"
15930+
},
15931+
"can_write": {
15932+
"type": "boolean",
15933+
"x-go-name": "CanWrite"
15934+
},
15935+
"is_admin": {
15936+
"type": "boolean",
15937+
"x-go-name": "IsAdmin"
15938+
},
15939+
"is_owner": {
15940+
"type": "boolean",
15941+
"x-go-name": "IsOwner"
15942+
}
15943+
},
15944+
"x-go-package": "code.gitea.io/gitea/modules/structs"
15945+
},
1588015946
"PRBranchInfo": {
1588115947
"description": "PRBranchInfo information about a branch",
1588215948
"type": "object",
@@ -17742,6 +17808,12 @@
1774217808
}
1774317809
}
1774417810
},
17811+
"OrganizationPermissions": {
17812+
"description": "OrganizationPermissions",
17813+
"schema": {
17814+
"$ref": "#/definitions/OrganizationPermissions"
17815+
}
17816+
},
1774517817
"PublicKey": {
1774617818
"description": "PublicKey",
1774717819
"schema": {

0 commit comments

Comments
 (0)