##// END OF EJS Templates
user-group-api: use simple schema validator to be consistent how we validate...
marcink -
r1831:87ca65d7 default
parent child Browse files
Show More
@@ -0,0 +1,78 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2016-2017 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 import re
21 import colander
22
23 from rhodecode.model.validation_schema import types, validators
24 from rhodecode.translation import _
25
26
27 @colander.deferred
28 def deferred_user_group_name_validator(node, kw):
29
30 def name_validator(node, value):
31
32 msg = _('Allowed in name are letters, numbers, and `-`, `_`, `.` '
33 'Name must start with a letter or number. Got `{}`').format(value)
34
35 if not re.match(r'^[a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+$', value):
36 raise colander.Invalid(node, msg)
37
38 return name_validator
39
40
41 @colander.deferred
42 def deferred_user_group_owner_validator(node, kw):
43
44 def owner_validator(node, value):
45 from rhodecode.model.db import User
46 existing = User.get_by_username(value)
47 if not existing:
48 msg = _(u'User group owner with id `{}` does not exists').format(value)
49 raise colander.Invalid(node, msg)
50
51 return owner_validator
52
53
54 class UserGroupSchema(colander.Schema):
55
56 user_group_name = colander.SchemaNode(
57 colander.String(),
58 validator=deferred_user_group_name_validator)
59
60 user_group_description = colander.SchemaNode(
61 colander.String(), missing='')
62
63 user_group_owner = colander.SchemaNode(
64 colander.String(),
65 validator=deferred_user_group_owner_validator)
66
67 user_group_active = colander.SchemaNode(
68 types.StringBooleanType(),
69 missing=False)
70
71 def deserialize(self, cstruct):
72 """
73 Custom deserialize that allows to chain validation, and verify
74 permissions, and as last step uniqueness
75 """
76
77 appstruct = super(UserGroupSchema, self).deserialize(cstruct)
78 return appstruct
@@ -1,114 +1,127 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import mock
21 import mock
22 import pytest
22 import pytest
23
23
24 from rhodecode.model.meta import Session
24 from rhodecode.model.meta import Session
25 from rhodecode.model.user import UserModel
25 from rhodecode.model.user import UserModel
26 from rhodecode.model.user_group import UserGroupModel
26 from rhodecode.model.user_group import UserGroupModel
27 from rhodecode.api.tests.utils import (
27 from rhodecode.api.tests.utils import (
28 build_data, api_call, assert_error, assert_ok, crash, jsonify)
28 build_data, api_call, assert_error, assert_ok, crash, jsonify)
29 from rhodecode.tests.fixture import Fixture
29 from rhodecode.tests.fixture import Fixture
30
30
31
31
32 @pytest.mark.usefixtures("testuser_api", "app")
32 @pytest.mark.usefixtures("testuser_api", "app")
33 class TestCreateUserGroup(object):
33 class TestCreateUserGroup(object):
34 fixture = Fixture()
34 fixture = Fixture()
35
35
36 def test_api_create_user_group(self):
36 def test_api_create_user_group(self):
37 group_name = 'some_new_group'
37 group_name = 'some_new_group'
38 id_, params = build_data(
38 id_, params = build_data(
39 self.apikey, 'create_user_group', group_name=group_name)
39 self.apikey, 'create_user_group', group_name=group_name)
40 response = api_call(self.app, params)
40 response = api_call(self.app, params)
41
41
42 ret = {
42 ret = {
43 'msg': 'created new user group `%s`' % (group_name,),
43 'msg': 'created new user group `%s`' % (group_name,),
44 'user_group': jsonify(
44 'user_group': jsonify(
45 UserGroupModel()
45 UserGroupModel()
46 .get_by_name(group_name)
46 .get_by_name(group_name)
47 .get_api_data()
47 .get_api_data()
48 )
48 )
49 }
49 }
50 expected = ret
50 expected = ret
51 assert_ok(id_, expected, given=response.body)
51 assert_ok(id_, expected, given=response.body)
52 self.fixture.destroy_user_group(group_name)
52 self.fixture.destroy_user_group(group_name)
53
53
54 def test_api_create_user_group_regular_user(self):
54 def test_api_create_user_group_regular_user(self):
55 group_name = 'some_new_group'
55 group_name = 'some_new_group'
56
56
57 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
57 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
58 usr.inherit_default_permissions = False
58 usr.inherit_default_permissions = False
59 Session().add(usr)
59 Session().add(usr)
60 UserModel().grant_perm(
60 UserModel().grant_perm(
61 self.TEST_USER_LOGIN, 'hg.usergroup.create.true')
61 self.TEST_USER_LOGIN, 'hg.usergroup.create.true')
62 Session().commit()
62 Session().commit()
63
63
64 id_, params = build_data(
64 id_, params = build_data(
65 self.apikey_regular, 'create_user_group', group_name=group_name)
65 self.apikey_regular, 'create_user_group', group_name=group_name)
66 response = api_call(self.app, params)
66 response = api_call(self.app, params)
67
67
68 expected = {
68 expected = {
69 'msg': 'created new user group `%s`' % (group_name,),
69 'msg': 'created new user group `%s`' % (group_name,),
70 'user_group': jsonify(
70 'user_group': jsonify(
71 UserGroupModel()
71 UserGroupModel()
72 .get_by_name(group_name)
72 .get_by_name(group_name)
73 .get_api_data()
73 .get_api_data()
74 )
74 )
75 }
75 }
76 try:
76 try:
77 assert_ok(id_, expected, given=response.body)
77 assert_ok(id_, expected, given=response.body)
78 finally:
78 finally:
79 self.fixture.destroy_user_group(group_name)
79 self.fixture.destroy_user_group(group_name)
80 UserModel().revoke_perm(
80 UserModel().revoke_perm(
81 self.TEST_USER_LOGIN, 'hg.usergroup.create.true')
81 self.TEST_USER_LOGIN, 'hg.usergroup.create.true')
82 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
82 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
83 usr.inherit_default_permissions = True
83 usr.inherit_default_permissions = True
84 Session().add(usr)
84 Session().add(usr)
85 Session().commit()
85 Session().commit()
86
86
87 def test_api_create_user_group_regular_user_no_permission(self):
87 def test_api_create_user_group_regular_user_no_permission(self):
88 group_name = 'some_new_group'
88 group_name = 'some_new_group'
89 id_, params = build_data(
89 id_, params = build_data(
90 self.apikey_regular, 'create_user_group', group_name=group_name)
90 self.apikey_regular, 'create_user_group', group_name=group_name)
91 response = api_call(self.app, params)
91 response = api_call(self.app, params)
92 expected = "Access was denied to this resource."
92 expected = "Access was denied to this resource."
93 assert_error(id_, expected, given=response.body)
93 assert_error(id_, expected, given=response.body)
94
94
95 def test_api_create_user_group_that_exist(self, user_util):
95 def test_api_create_user_group_that_exist(self, user_util):
96 group = user_util.create_user_group()
96 group = user_util.create_user_group()
97 group_name = group.users_group_name
97 group_name = group.users_group_name
98
98
99 id_, params = build_data(
99 id_, params = build_data(
100 self.apikey, 'create_user_group', group_name=group_name)
100 self.apikey, 'create_user_group', group_name=group_name)
101 response = api_call(self.app, params)
101 response = api_call(self.app, params)
102
102
103 expected = "user group `%s` already exist" % (group_name,)
103 expected = "user group `%s` already exist" % (group_name,)
104 assert_error(id_, expected, given=response.body)
104 assert_error(id_, expected, given=response.body)
105
105
106 @mock.patch.object(UserGroupModel, 'create', crash)
106 @mock.patch.object(UserGroupModel, 'create', crash)
107 def test_api_create_user_group_exception_occurred(self):
107 def test_api_create_user_group_exception_occurred(self):
108 group_name = 'exception_happens'
108 group_name = 'exception_happens'
109 id_, params = build_data(
109 id_, params = build_data(
110 self.apikey, 'create_user_group', group_name=group_name)
110 self.apikey, 'create_user_group', group_name=group_name)
111 response = api_call(self.app, params)
111 response = api_call(self.app, params)
112
112
113 expected = 'failed to create group `%s`' % (group_name,)
113 expected = 'failed to create group `%s`' % (group_name,)
114 assert_error(id_, expected, given=response.body)
114 assert_error(id_, expected, given=response.body)
115
116 def test_api_create_user_group_with_wrong_name(self, user_util):
117
118 group_name = 'wrong NAME <>'
119 id_, params = build_data(
120 self.apikey, 'create_user_group', group_name=group_name)
121 response = api_call(self.app, params)
122
123 expected = {"user_group_name":
124 "Allowed in name are letters, numbers, and `-`, `_`, "
125 "`.` Name must start with a letter or number. "
126 "Got `{}`".format(group_name)}
127 assert_error(id_, expected, given=response.body)
@@ -1,799 +1,818 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22
22
23 from rhodecode.api import jsonrpc_method, JSONRPCError, JSONRPCForbidden
23 from rhodecode.api import jsonrpc_method, JSONRPCError, JSONRPCForbidden, \
24 JSONRPCValidationError
24 from rhodecode.api.utils import (
25 from rhodecode.api.utils import (
25 Optional, OAttr, store_update, has_superadmin_permission, get_origin,
26 Optional, OAttr, store_update, has_superadmin_permission, get_origin,
26 get_user_or_error, get_user_group_or_error, get_perm_or_error)
27 get_user_or_error, get_user_group_or_error, get_perm_or_error)
27 from rhodecode.lib import audit_logger
28 from rhodecode.lib import audit_logger
28 from rhodecode.lib.auth import HasUserGroupPermissionAnyApi, HasPermissionAnyApi
29 from rhodecode.lib.auth import HasUserGroupPermissionAnyApi, HasPermissionAnyApi
29 from rhodecode.lib.exceptions import UserGroupAssignedException
30 from rhodecode.lib.exceptions import UserGroupAssignedException
30 from rhodecode.model.db import Session
31 from rhodecode.model.db import Session
31 from rhodecode.model.scm import UserGroupList
32 from rhodecode.model.scm import UserGroupList
32 from rhodecode.model.user_group import UserGroupModel
33 from rhodecode.model.user_group import UserGroupModel
34 from rhodecode.model import validation_schema
35 from rhodecode.model.validation_schema.schemas import user_group_schema
33
36
34 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
35
38
36
39
37 @jsonrpc_method()
40 @jsonrpc_method()
38 def get_user_group(request, apiuser, usergroupid):
41 def get_user_group(request, apiuser, usergroupid):
39 """
42 """
40 Returns the data of an existing user group.
43 Returns the data of an existing user group.
41
44
42 This command can only be run using an |authtoken| with admin rights to
45 This command can only be run using an |authtoken| with admin rights to
43 the specified repository.
46 the specified repository.
44
47
45 :param apiuser: This is filled automatically from the |authtoken|.
48 :param apiuser: This is filled automatically from the |authtoken|.
46 :type apiuser: AuthUser
49 :type apiuser: AuthUser
47 :param usergroupid: Set the user group from which to return data.
50 :param usergroupid: Set the user group from which to return data.
48 :type usergroupid: str or int
51 :type usergroupid: str or int
49
52
50 Example error output:
53 Example error output:
51
54
52 .. code-block:: bash
55 .. code-block:: bash
53
56
54 {
57 {
55 "error": null,
58 "error": null,
56 "id": <id>,
59 "id": <id>,
57 "result": {
60 "result": {
58 "active": true,
61 "active": true,
59 "group_description": "group description",
62 "group_description": "group description",
60 "group_name": "group name",
63 "group_name": "group name",
61 "members": [
64 "members": [
62 {
65 {
63 "name": "owner-name",
66 "name": "owner-name",
64 "origin": "owner",
67 "origin": "owner",
65 "permission": "usergroup.admin",
68 "permission": "usergroup.admin",
66 "type": "user"
69 "type": "user"
67 },
70 },
68 {
71 {
69 {
72 {
70 "name": "user name",
73 "name": "user name",
71 "origin": "permission",
74 "origin": "permission",
72 "permission": "usergroup.admin",
75 "permission": "usergroup.admin",
73 "type": "user"
76 "type": "user"
74 },
77 },
75 {
78 {
76 "name": "user group name",
79 "name": "user group name",
77 "origin": "permission",
80 "origin": "permission",
78 "permission": "usergroup.write",
81 "permission": "usergroup.write",
79 "type": "user_group"
82 "type": "user_group"
80 }
83 }
81 ],
84 ],
82 "owner": "owner name",
85 "owner": "owner name",
83 "users": [],
86 "users": [],
84 "users_group_id": 2
87 "users_group_id": 2
85 }
88 }
86 }
89 }
87
90
88 """
91 """
89
92
90 user_group = get_user_group_or_error(usergroupid)
93 user_group = get_user_group_or_error(usergroupid)
91 if not has_superadmin_permission(apiuser):
94 if not has_superadmin_permission(apiuser):
92 # check if we have at least read permission for this user group !
95 # check if we have at least read permission for this user group !
93 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
96 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
94 if not HasUserGroupPermissionAnyApi(*_perms)(
97 if not HasUserGroupPermissionAnyApi(*_perms)(
95 user=apiuser, user_group_name=user_group.users_group_name):
98 user=apiuser, user_group_name=user_group.users_group_name):
96 raise JSONRPCError('user group `%s` does not exist' % (
99 raise JSONRPCError('user group `%s` does not exist' % (
97 usergroupid,))
100 usergroupid,))
98
101
99 permissions = []
102 permissions = []
100 for _user in user_group.permissions():
103 for _user in user_group.permissions():
101 user_data = {
104 user_data = {
102 'name': _user.username,
105 'name': _user.username,
103 'permission': _user.permission,
106 'permission': _user.permission,
104 'origin': get_origin(_user),
107 'origin': get_origin(_user),
105 'type': "user",
108 'type': "user",
106 }
109 }
107 permissions.append(user_data)
110 permissions.append(user_data)
108
111
109 for _user_group in user_group.permission_user_groups():
112 for _user_group in user_group.permission_user_groups():
110 user_group_data = {
113 user_group_data = {
111 'name': _user_group.users_group_name,
114 'name': _user_group.users_group_name,
112 'permission': _user_group.permission,
115 'permission': _user_group.permission,
113 'origin': get_origin(_user_group),
116 'origin': get_origin(_user_group),
114 'type': "user_group",
117 'type': "user_group",
115 }
118 }
116 permissions.append(user_group_data)
119 permissions.append(user_group_data)
117
120
118 data = user_group.get_api_data()
121 data = user_group.get_api_data()
119 data['members'] = permissions
122 data['members'] = permissions
120
123
121 return data
124 return data
122
125
123
126
124 @jsonrpc_method()
127 @jsonrpc_method()
125 def get_user_groups(request, apiuser):
128 def get_user_groups(request, apiuser):
126 """
129 """
127 Lists all the existing user groups within RhodeCode.
130 Lists all the existing user groups within RhodeCode.
128
131
129 This command can only be run using an |authtoken| with admin rights to
132 This command can only be run using an |authtoken| with admin rights to
130 the specified repository.
133 the specified repository.
131
134
132 This command takes the following options:
135 This command takes the following options:
133
136
134 :param apiuser: This is filled automatically from the |authtoken|.
137 :param apiuser: This is filled automatically from the |authtoken|.
135 :type apiuser: AuthUser
138 :type apiuser: AuthUser
136
139
137 Example error output:
140 Example error output:
138
141
139 .. code-block:: bash
142 .. code-block:: bash
140
143
141 id : <id_given_in_input>
144 id : <id_given_in_input>
142 result : [<user_group_obj>,...]
145 result : [<user_group_obj>,...]
143 error : null
146 error : null
144 """
147 """
145
148
146 include_secrets = has_superadmin_permission(apiuser)
149 include_secrets = has_superadmin_permission(apiuser)
147
150
148 result = []
151 result = []
149 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
152 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
150 extras = {'user': apiuser}
153 extras = {'user': apiuser}
151 for user_group in UserGroupList(UserGroupModel().get_all(),
154 for user_group in UserGroupList(UserGroupModel().get_all(),
152 perm_set=_perms, extra_kwargs=extras):
155 perm_set=_perms, extra_kwargs=extras):
153 result.append(
156 result.append(
154 user_group.get_api_data(include_secrets=include_secrets))
157 user_group.get_api_data(include_secrets=include_secrets))
155 return result
158 return result
156
159
157
160
158 @jsonrpc_method()
161 @jsonrpc_method()
159 def create_user_group(
162 def create_user_group(
160 request, apiuser, group_name, description=Optional(''),
163 request, apiuser, group_name, description=Optional(''),
161 owner=Optional(OAttr('apiuser')), active=Optional(True)):
164 owner=Optional(OAttr('apiuser')), active=Optional(True)):
162 """
165 """
163 Creates a new user group.
166 Creates a new user group.
164
167
165 This command can only be run using an |authtoken| with admin rights to
168 This command can only be run using an |authtoken| with admin rights to
166 the specified repository.
169 the specified repository.
167
170
168 This command takes the following options:
171 This command takes the following options:
169
172
170 :param apiuser: This is filled automatically from the |authtoken|.
173 :param apiuser: This is filled automatically from the |authtoken|.
171 :type apiuser: AuthUser
174 :type apiuser: AuthUser
172 :param group_name: Set the name of the new user group.
175 :param group_name: Set the name of the new user group.
173 :type group_name: str
176 :type group_name: str
174 :param description: Give a description of the new user group.
177 :param description: Give a description of the new user group.
175 :type description: str
178 :type description: str
176 :param owner: Set the owner of the new user group.
179 :param owner: Set the owner of the new user group.
177 If not set, the owner is the |authtoken| user.
180 If not set, the owner is the |authtoken| user.
178 :type owner: Optional(str or int)
181 :type owner: Optional(str or int)
179 :param active: Set this group as active.
182 :param active: Set this group as active.
180 :type active: Optional(``True`` | ``False``)
183 :type active: Optional(``True`` | ``False``)
181
184
182 Example output:
185 Example output:
183
186
184 .. code-block:: bash
187 .. code-block:: bash
185
188
186 id : <id_given_in_input>
189 id : <id_given_in_input>
187 result: {
190 result: {
188 "msg": "created new user group `<groupname>`",
191 "msg": "created new user group `<groupname>`",
189 "user_group": <user_group_object>
192 "user_group": <user_group_object>
190 }
193 }
191 error: null
194 error: null
192
195
193 Example error output:
196 Example error output:
194
197
195 .. code-block:: bash
198 .. code-block:: bash
196
199
197 id : <id_given_in_input>
200 id : <id_given_in_input>
198 result : null
201 result : null
199 error : {
202 error : {
200 "user group `<group name>` already exist"
203 "user group `<group name>` already exist"
201 or
204 or
202 "failed to create group `<group name>`"
205 "failed to create group `<group name>`"
203 }
206 }
204
207
205 """
208 """
206
209
207 if not has_superadmin_permission(apiuser):
210 if not has_superadmin_permission(apiuser):
208 if not HasPermissionAnyApi('hg.usergroup.create.true')(user=apiuser):
211 if not HasPermissionAnyApi('hg.usergroup.create.true')(user=apiuser):
209 raise JSONRPCForbidden()
212 raise JSONRPCForbidden()
210
213
211 if UserGroupModel().get_by_name(group_name):
214 if UserGroupModel().get_by_name(group_name):
212 raise JSONRPCError("user group `%s` already exist" % (group_name,))
215 raise JSONRPCError("user group `%s` already exist" % (group_name,))
213
216
214 try:
215 if isinstance(owner, Optional):
217 if isinstance(owner, Optional):
216 owner = apiuser.user_id
218 owner = apiuser.user_id
217
219
218 owner = get_user_or_error(owner)
220 owner = get_user_or_error(owner)
219 active = Optional.extract(active)
221 active = Optional.extract(active)
220 description = Optional.extract(description)
222 description = Optional.extract(description)
223
224 schema = user_group_schema.UserGroupSchema().bind(
225 # user caller
226 user=apiuser)
227 try:
228 schema_data = schema.deserialize(dict(
229 user_group_name=group_name,
230 user_group_description=description,
231 user_group_owner=owner.username,
232 user_group_active=active,
233 ))
234 except validation_schema.Invalid as err:
235 raise JSONRPCValidationError(colander_exc=err)
236
237 try:
221 user_group = UserGroupModel().create(
238 user_group = UserGroupModel().create(
222 name=group_name, description=description, owner=owner,
239 name=schema_data['user_group_name'],
223 active=active)
240 description=schema_data['user_group_description'],
241 owner=owner,
242 active=schema_data['user_group_active'])
224 Session().flush()
243 Session().flush()
225 creation_data = user_group.get_api_data()
244 creation_data = user_group.get_api_data()
226 audit_logger.store_api(
245 audit_logger.store_api(
227 'user_group.create', action_data={'data': creation_data},
246 'user_group.create', action_data={'data': creation_data},
228 user=apiuser)
247 user=apiuser)
229 Session().commit()
248 Session().commit()
230 return {
249 return {
231 'msg': 'created new user group `%s`' % group_name,
250 'msg': 'created new user group `%s`' % group_name,
232 'user_group': creation_data
251 'user_group': creation_data
233 }
252 }
234 except Exception:
253 except Exception:
235 log.exception("Error occurred during creation of user group")
254 log.exception("Error occurred during creation of user group")
236 raise JSONRPCError('failed to create group `%s`' % (group_name,))
255 raise JSONRPCError('failed to create group `%s`' % (group_name,))
237
256
238
257
239 @jsonrpc_method()
258 @jsonrpc_method()
240 def update_user_group(request, apiuser, usergroupid, group_name=Optional(''),
259 def update_user_group(request, apiuser, usergroupid, group_name=Optional(''),
241 description=Optional(''), owner=Optional(None),
260 description=Optional(''), owner=Optional(None),
242 active=Optional(True)):
261 active=Optional(True)):
243 """
262 """
244 Updates the specified `user group` with the details provided.
263 Updates the specified `user group` with the details provided.
245
264
246 This command can only be run using an |authtoken| with admin rights to
265 This command can only be run using an |authtoken| with admin rights to
247 the specified repository.
266 the specified repository.
248
267
249 :param apiuser: This is filled automatically from the |authtoken|.
268 :param apiuser: This is filled automatically from the |authtoken|.
250 :type apiuser: AuthUser
269 :type apiuser: AuthUser
251 :param usergroupid: Set the id of the `user group` to update.
270 :param usergroupid: Set the id of the `user group` to update.
252 :type usergroupid: str or int
271 :type usergroupid: str or int
253 :param group_name: Set the new name the `user group`
272 :param group_name: Set the new name the `user group`
254 :type group_name: str
273 :type group_name: str
255 :param description: Give a description for the `user group`
274 :param description: Give a description for the `user group`
256 :type description: str
275 :type description: str
257 :param owner: Set the owner of the `user group`.
276 :param owner: Set the owner of the `user group`.
258 :type owner: Optional(str or int)
277 :type owner: Optional(str or int)
259 :param active: Set the group as active.
278 :param active: Set the group as active.
260 :type active: Optional(``True`` | ``False``)
279 :type active: Optional(``True`` | ``False``)
261
280
262 Example output:
281 Example output:
263
282
264 .. code-block:: bash
283 .. code-block:: bash
265
284
266 id : <id_given_in_input>
285 id : <id_given_in_input>
267 result : {
286 result : {
268 "msg": 'updated user group ID:<user group id> <user group name>',
287 "msg": 'updated user group ID:<user group id> <user group name>',
269 "user_group": <user_group_object>
288 "user_group": <user_group_object>
270 }
289 }
271 error : null
290 error : null
272
291
273 Example error output:
292 Example error output:
274
293
275 .. code-block:: bash
294 .. code-block:: bash
276
295
277 id : <id_given_in_input>
296 id : <id_given_in_input>
278 result : null
297 result : null
279 error : {
298 error : {
280 "failed to update user group `<user group name>`"
299 "failed to update user group `<user group name>`"
281 }
300 }
282
301
283 """
302 """
284
303
285 user_group = get_user_group_or_error(usergroupid)
304 user_group = get_user_group_or_error(usergroupid)
286 include_secrets = False
305 include_secrets = False
287 if not has_superadmin_permission(apiuser):
306 if not has_superadmin_permission(apiuser):
288 # check if we have admin permission for this user group !
307 # check if we have admin permission for this user group !
289 _perms = ('usergroup.admin',)
308 _perms = ('usergroup.admin',)
290 if not HasUserGroupPermissionAnyApi(*_perms)(
309 if not HasUserGroupPermissionAnyApi(*_perms)(
291 user=apiuser, user_group_name=user_group.users_group_name):
310 user=apiuser, user_group_name=user_group.users_group_name):
292 raise JSONRPCError(
311 raise JSONRPCError(
293 'user group `%s` does not exist' % (usergroupid,))
312 'user group `%s` does not exist' % (usergroupid,))
294 else:
313 else:
295 include_secrets = True
314 include_secrets = True
296
315
297 if not isinstance(owner, Optional):
316 if not isinstance(owner, Optional):
298 owner = get_user_or_error(owner)
317 owner = get_user_or_error(owner)
299
318
300 old_data = user_group.get_api_data()
319 old_data = user_group.get_api_data()
301 updates = {}
320 updates = {}
302 store_update(updates, group_name, 'users_group_name')
321 store_update(updates, group_name, 'users_group_name')
303 store_update(updates, description, 'user_group_description')
322 store_update(updates, description, 'user_group_description')
304 store_update(updates, owner, 'user')
323 store_update(updates, owner, 'user')
305 store_update(updates, active, 'users_group_active')
324 store_update(updates, active, 'users_group_active')
306 try:
325 try:
307 UserGroupModel().update(user_group, updates)
326 UserGroupModel().update(user_group, updates)
308 audit_logger.store_api(
327 audit_logger.store_api(
309 'user_group.edit', action_data={'old_data': old_data},
328 'user_group.edit', action_data={'old_data': old_data},
310 user=apiuser)
329 user=apiuser)
311 Session().commit()
330 Session().commit()
312 return {
331 return {
313 'msg': 'updated user group ID:%s %s' % (
332 'msg': 'updated user group ID:%s %s' % (
314 user_group.users_group_id, user_group.users_group_name),
333 user_group.users_group_id, user_group.users_group_name),
315 'user_group': user_group.get_api_data(
334 'user_group': user_group.get_api_data(
316 include_secrets=include_secrets)
335 include_secrets=include_secrets)
317 }
336 }
318 except Exception:
337 except Exception:
319 log.exception("Error occurred during update of user group")
338 log.exception("Error occurred during update of user group")
320 raise JSONRPCError(
339 raise JSONRPCError(
321 'failed to update user group `%s`' % (usergroupid,))
340 'failed to update user group `%s`' % (usergroupid,))
322
341
323
342
324 @jsonrpc_method()
343 @jsonrpc_method()
325 def delete_user_group(request, apiuser, usergroupid):
344 def delete_user_group(request, apiuser, usergroupid):
326 """
345 """
327 Deletes the specified `user group`.
346 Deletes the specified `user group`.
328
347
329 This command can only be run using an |authtoken| with admin rights to
348 This command can only be run using an |authtoken| with admin rights to
330 the specified repository.
349 the specified repository.
331
350
332 This command takes the following options:
351 This command takes the following options:
333
352
334 :param apiuser: filled automatically from apikey
353 :param apiuser: filled automatically from apikey
335 :type apiuser: AuthUser
354 :type apiuser: AuthUser
336 :param usergroupid:
355 :param usergroupid:
337 :type usergroupid: int
356 :type usergroupid: int
338
357
339 Example output:
358 Example output:
340
359
341 .. code-block:: bash
360 .. code-block:: bash
342
361
343 id : <id_given_in_input>
362 id : <id_given_in_input>
344 result : {
363 result : {
345 "msg": "deleted user group ID:<user_group_id> <user_group_name>"
364 "msg": "deleted user group ID:<user_group_id> <user_group_name>"
346 }
365 }
347 error : null
366 error : null
348
367
349 Example error output:
368 Example error output:
350
369
351 .. code-block:: bash
370 .. code-block:: bash
352
371
353 id : <id_given_in_input>
372 id : <id_given_in_input>
354 result : null
373 result : null
355 error : {
374 error : {
356 "failed to delete user group ID:<user_group_id> <user_group_name>"
375 "failed to delete user group ID:<user_group_id> <user_group_name>"
357 or
376 or
358 "RepoGroup assigned to <repo_groups_list>"
377 "RepoGroup assigned to <repo_groups_list>"
359 }
378 }
360
379
361 """
380 """
362
381
363 user_group = get_user_group_or_error(usergroupid)
382 user_group = get_user_group_or_error(usergroupid)
364 if not has_superadmin_permission(apiuser):
383 if not has_superadmin_permission(apiuser):
365 # check if we have admin permission for this user group !
384 # check if we have admin permission for this user group !
366 _perms = ('usergroup.admin',)
385 _perms = ('usergroup.admin',)
367 if not HasUserGroupPermissionAnyApi(*_perms)(
386 if not HasUserGroupPermissionAnyApi(*_perms)(
368 user=apiuser, user_group_name=user_group.users_group_name):
387 user=apiuser, user_group_name=user_group.users_group_name):
369 raise JSONRPCError(
388 raise JSONRPCError(
370 'user group `%s` does not exist' % (usergroupid,))
389 'user group `%s` does not exist' % (usergroupid,))
371
390
372 old_data = user_group.get_api_data()
391 old_data = user_group.get_api_data()
373 try:
392 try:
374 UserGroupModel().delete(user_group)
393 UserGroupModel().delete(user_group)
375 audit_logger.store_api(
394 audit_logger.store_api(
376 'user_group.delete', action_data={'old_data': old_data},
395 'user_group.delete', action_data={'old_data': old_data},
377 user=apiuser)
396 user=apiuser)
378 Session().commit()
397 Session().commit()
379 return {
398 return {
380 'msg': 'deleted user group ID:%s %s' % (
399 'msg': 'deleted user group ID:%s %s' % (
381 user_group.users_group_id, user_group.users_group_name),
400 user_group.users_group_id, user_group.users_group_name),
382 'user_group': None
401 'user_group': None
383 }
402 }
384 except UserGroupAssignedException as e:
403 except UserGroupAssignedException as e:
385 log.exception("UserGroupAssigned error")
404 log.exception("UserGroupAssigned error")
386 raise JSONRPCError(str(e))
405 raise JSONRPCError(str(e))
387 except Exception:
406 except Exception:
388 log.exception("Error occurred during deletion of user group")
407 log.exception("Error occurred during deletion of user group")
389 raise JSONRPCError(
408 raise JSONRPCError(
390 'failed to delete user group ID:%s %s' %(
409 'failed to delete user group ID:%s %s' %(
391 user_group.users_group_id, user_group.users_group_name))
410 user_group.users_group_id, user_group.users_group_name))
392
411
393
412
394 @jsonrpc_method()
413 @jsonrpc_method()
395 def add_user_to_user_group(request, apiuser, usergroupid, userid):
414 def add_user_to_user_group(request, apiuser, usergroupid, userid):
396 """
415 """
397 Adds a user to a `user group`. If the user already exists in the group
416 Adds a user to a `user group`. If the user already exists in the group
398 this command will return false.
417 this command will return false.
399
418
400 This command can only be run using an |authtoken| with admin rights to
419 This command can only be run using an |authtoken| with admin rights to
401 the specified user group.
420 the specified user group.
402
421
403 This command takes the following options:
422 This command takes the following options:
404
423
405 :param apiuser: This is filled automatically from the |authtoken|.
424 :param apiuser: This is filled automatically from the |authtoken|.
406 :type apiuser: AuthUser
425 :type apiuser: AuthUser
407 :param usergroupid: Set the name of the `user group` to which a
426 :param usergroupid: Set the name of the `user group` to which a
408 user will be added.
427 user will be added.
409 :type usergroupid: int
428 :type usergroupid: int
410 :param userid: Set the `user_id` of the user to add to the group.
429 :param userid: Set the `user_id` of the user to add to the group.
411 :type userid: int
430 :type userid: int
412
431
413 Example output:
432 Example output:
414
433
415 .. code-block:: bash
434 .. code-block:: bash
416
435
417 id : <id_given_in_input>
436 id : <id_given_in_input>
418 result : {
437 result : {
419 "success": True|False # depends on if member is in group
438 "success": True|False # depends on if member is in group
420 "msg": "added member `<username>` to user group `<groupname>` |
439 "msg": "added member `<username>` to user group `<groupname>` |
421 User is already in that group"
440 User is already in that group"
422
441
423 }
442 }
424 error : null
443 error : null
425
444
426 Example error output:
445 Example error output:
427
446
428 .. code-block:: bash
447 .. code-block:: bash
429
448
430 id : <id_given_in_input>
449 id : <id_given_in_input>
431 result : null
450 result : null
432 error : {
451 error : {
433 "failed to add member to user group `<user_group_name>`"
452 "failed to add member to user group `<user_group_name>`"
434 }
453 }
435
454
436 """
455 """
437
456
438 user = get_user_or_error(userid)
457 user = get_user_or_error(userid)
439 user_group = get_user_group_or_error(usergroupid)
458 user_group = get_user_group_or_error(usergroupid)
440 if not has_superadmin_permission(apiuser):
459 if not has_superadmin_permission(apiuser):
441 # check if we have admin permission for this user group !
460 # check if we have admin permission for this user group !
442 _perms = ('usergroup.admin',)
461 _perms = ('usergroup.admin',)
443 if not HasUserGroupPermissionAnyApi(*_perms)(
462 if not HasUserGroupPermissionAnyApi(*_perms)(
444 user=apiuser, user_group_name=user_group.users_group_name):
463 user=apiuser, user_group_name=user_group.users_group_name):
445 raise JSONRPCError('user group `%s` does not exist' % (
464 raise JSONRPCError('user group `%s` does not exist' % (
446 usergroupid,))
465 usergroupid,))
447
466
448 try:
467 try:
449 ugm = UserGroupModel().add_user_to_group(user_group, user)
468 ugm = UserGroupModel().add_user_to_group(user_group, user)
450 success = True if ugm is not True else False
469 success = True if ugm is not True else False
451 msg = 'added member `%s` to user group `%s`' % (
470 msg = 'added member `%s` to user group `%s`' % (
452 user.username, user_group.users_group_name
471 user.username, user_group.users_group_name
453 )
472 )
454 msg = msg if success else 'User is already in that group'
473 msg = msg if success else 'User is already in that group'
455 if success:
474 if success:
456 user_data = user.get_api_data()
475 user_data = user.get_api_data()
457 audit_logger.store_api(
476 audit_logger.store_api(
458 'user_group.edit.member.add', action_data={'user': user_data},
477 'user_group.edit.member.add', action_data={'user': user_data},
459 user=apiuser)
478 user=apiuser)
460
479
461 Session().commit()
480 Session().commit()
462
481
463 return {
482 return {
464 'success': success,
483 'success': success,
465 'msg': msg
484 'msg': msg
466 }
485 }
467 except Exception:
486 except Exception:
468 log.exception("Error occurred during adding a member to user group")
487 log.exception("Error occurred during adding a member to user group")
469 raise JSONRPCError(
488 raise JSONRPCError(
470 'failed to add member to user group `%s`' % (
489 'failed to add member to user group `%s`' % (
471 user_group.users_group_name,
490 user_group.users_group_name,
472 )
491 )
473 )
492 )
474
493
475
494
476 @jsonrpc_method()
495 @jsonrpc_method()
477 def remove_user_from_user_group(request, apiuser, usergroupid, userid):
496 def remove_user_from_user_group(request, apiuser, usergroupid, userid):
478 """
497 """
479 Removes a user from a user group.
498 Removes a user from a user group.
480
499
481 * If the specified user is not in the group, this command will return
500 * If the specified user is not in the group, this command will return
482 `false`.
501 `false`.
483
502
484 This command can only be run using an |authtoken| with admin rights to
503 This command can only be run using an |authtoken| with admin rights to
485 the specified user group.
504 the specified user group.
486
505
487 :param apiuser: This is filled automatically from the |authtoken|.
506 :param apiuser: This is filled automatically from the |authtoken|.
488 :type apiuser: AuthUser
507 :type apiuser: AuthUser
489 :param usergroupid: Sets the user group name.
508 :param usergroupid: Sets the user group name.
490 :type usergroupid: str or int
509 :type usergroupid: str or int
491 :param userid: The user you wish to remove from |RCE|.
510 :param userid: The user you wish to remove from |RCE|.
492 :type userid: str or int
511 :type userid: str or int
493
512
494 Example output:
513 Example output:
495
514
496 .. code-block:: bash
515 .. code-block:: bash
497
516
498 id : <id_given_in_input>
517 id : <id_given_in_input>
499 result: {
518 result: {
500 "success": True|False, # depends on if member is in group
519 "success": True|False, # depends on if member is in group
501 "msg": "removed member <username> from user group <groupname> |
520 "msg": "removed member <username> from user group <groupname> |
502 User wasn't in group"
521 User wasn't in group"
503 }
522 }
504 error: null
523 error: null
505
524
506 """
525 """
507
526
508 user = get_user_or_error(userid)
527 user = get_user_or_error(userid)
509 user_group = get_user_group_or_error(usergroupid)
528 user_group = get_user_group_or_error(usergroupid)
510 if not has_superadmin_permission(apiuser):
529 if not has_superadmin_permission(apiuser):
511 # check if we have admin permission for this user group !
530 # check if we have admin permission for this user group !
512 _perms = ('usergroup.admin',)
531 _perms = ('usergroup.admin',)
513 if not HasUserGroupPermissionAnyApi(*_perms)(
532 if not HasUserGroupPermissionAnyApi(*_perms)(
514 user=apiuser, user_group_name=user_group.users_group_name):
533 user=apiuser, user_group_name=user_group.users_group_name):
515 raise JSONRPCError(
534 raise JSONRPCError(
516 'user group `%s` does not exist' % (usergroupid,))
535 'user group `%s` does not exist' % (usergroupid,))
517
536
518 try:
537 try:
519 success = UserGroupModel().remove_user_from_group(user_group, user)
538 success = UserGroupModel().remove_user_from_group(user_group, user)
520 msg = 'removed member `%s` from user group `%s`' % (
539 msg = 'removed member `%s` from user group `%s`' % (
521 user.username, user_group.users_group_name
540 user.username, user_group.users_group_name
522 )
541 )
523 msg = msg if success else "User wasn't in group"
542 msg = msg if success else "User wasn't in group"
524 if success:
543 if success:
525 user_data = user.get_api_data()
544 user_data = user.get_api_data()
526 audit_logger.store_api(
545 audit_logger.store_api(
527 'user_group.edit.member.delete', action_data={'user': user_data},
546 'user_group.edit.member.delete', action_data={'user': user_data},
528 user=apiuser)
547 user=apiuser)
529
548
530 Session().commit()
549 Session().commit()
531 return {'success': success, 'msg': msg}
550 return {'success': success, 'msg': msg}
532 except Exception:
551 except Exception:
533 log.exception("Error occurred during removing an member from user group")
552 log.exception("Error occurred during removing an member from user group")
534 raise JSONRPCError(
553 raise JSONRPCError(
535 'failed to remove member from user group `%s`' % (
554 'failed to remove member from user group `%s`' % (
536 user_group.users_group_name,
555 user_group.users_group_name,
537 )
556 )
538 )
557 )
539
558
540
559
541 @jsonrpc_method()
560 @jsonrpc_method()
542 def grant_user_permission_to_user_group(
561 def grant_user_permission_to_user_group(
543 request, apiuser, usergroupid, userid, perm):
562 request, apiuser, usergroupid, userid, perm):
544 """
563 """
545 Set permissions for a user in a user group.
564 Set permissions for a user in a user group.
546
565
547 :param apiuser: This is filled automatically from the |authtoken|.
566 :param apiuser: This is filled automatically from the |authtoken|.
548 :type apiuser: AuthUser
567 :type apiuser: AuthUser
549 :param usergroupid: Set the user group to edit permissions on.
568 :param usergroupid: Set the user group to edit permissions on.
550 :type usergroupid: str or int
569 :type usergroupid: str or int
551 :param userid: Set the user from whom you wish to set permissions.
570 :param userid: Set the user from whom you wish to set permissions.
552 :type userid: str
571 :type userid: str
553 :param perm: (usergroup.(none|read|write|admin))
572 :param perm: (usergroup.(none|read|write|admin))
554 :type perm: str
573 :type perm: str
555
574
556 Example output:
575 Example output:
557
576
558 .. code-block:: bash
577 .. code-block:: bash
559
578
560 id : <id_given_in_input>
579 id : <id_given_in_input>
561 result : {
580 result : {
562 "msg": "Granted perm: `<perm_name>` for user: `<username>` in user group: `<user_group_name>`",
581 "msg": "Granted perm: `<perm_name>` for user: `<username>` in user group: `<user_group_name>`",
563 "success": true
582 "success": true
564 }
583 }
565 error : null
584 error : null
566 """
585 """
567
586
568 user_group = get_user_group_or_error(usergroupid)
587 user_group = get_user_group_or_error(usergroupid)
569
588
570 if not has_superadmin_permission(apiuser):
589 if not has_superadmin_permission(apiuser):
571 # check if we have admin permission for this user group !
590 # check if we have admin permission for this user group !
572 _perms = ('usergroup.admin',)
591 _perms = ('usergroup.admin',)
573 if not HasUserGroupPermissionAnyApi(*_perms)(
592 if not HasUserGroupPermissionAnyApi(*_perms)(
574 user=apiuser, user_group_name=user_group.users_group_name):
593 user=apiuser, user_group_name=user_group.users_group_name):
575 raise JSONRPCError(
594 raise JSONRPCError(
576 'user group `%s` does not exist' % (usergroupid,))
595 'user group `%s` does not exist' % (usergroupid,))
577
596
578 user = get_user_or_error(userid)
597 user = get_user_or_error(userid)
579 perm = get_perm_or_error(perm, prefix='usergroup.')
598 perm = get_perm_or_error(perm, prefix='usergroup.')
580
599
581 try:
600 try:
582 UserGroupModel().grant_user_permission(
601 UserGroupModel().grant_user_permission(
583 user_group=user_group, user=user, perm=perm)
602 user_group=user_group, user=user, perm=perm)
584 Session().commit()
603 Session().commit()
585 return {
604 return {
586 'msg':
605 'msg':
587 'Granted perm: `%s` for user: `%s` in user group: `%s`' % (
606 'Granted perm: `%s` for user: `%s` in user group: `%s`' % (
588 perm.permission_name, user.username,
607 perm.permission_name, user.username,
589 user_group.users_group_name
608 user_group.users_group_name
590 ),
609 ),
591 'success': True
610 'success': True
592 }
611 }
593 except Exception:
612 except Exception:
594 log.exception("Error occurred during editing permissions "
613 log.exception("Error occurred during editing permissions "
595 "for user in user group")
614 "for user in user group")
596 raise JSONRPCError(
615 raise JSONRPCError(
597 'failed to edit permission for user: '
616 'failed to edit permission for user: '
598 '`%s` in user group: `%s`' % (
617 '`%s` in user group: `%s`' % (
599 userid, user_group.users_group_name))
618 userid, user_group.users_group_name))
600
619
601
620
602 @jsonrpc_method()
621 @jsonrpc_method()
603 def revoke_user_permission_from_user_group(
622 def revoke_user_permission_from_user_group(
604 request, apiuser, usergroupid, userid):
623 request, apiuser, usergroupid, userid):
605 """
624 """
606 Revoke a users permissions in a user group.
625 Revoke a users permissions in a user group.
607
626
608 :param apiuser: This is filled automatically from the |authtoken|.
627 :param apiuser: This is filled automatically from the |authtoken|.
609 :type apiuser: AuthUser
628 :type apiuser: AuthUser
610 :param usergroupid: Set the user group from which to revoke the user
629 :param usergroupid: Set the user group from which to revoke the user
611 permissions.
630 permissions.
612 :type: usergroupid: str or int
631 :type: usergroupid: str or int
613 :param userid: Set the userid of the user whose permissions will be
632 :param userid: Set the userid of the user whose permissions will be
614 revoked.
633 revoked.
615 :type userid: str
634 :type userid: str
616
635
617 Example output:
636 Example output:
618
637
619 .. code-block:: bash
638 .. code-block:: bash
620
639
621 id : <id_given_in_input>
640 id : <id_given_in_input>
622 result : {
641 result : {
623 "msg": "Revoked perm for user: `<username>` in user group: `<user_group_name>`",
642 "msg": "Revoked perm for user: `<username>` in user group: `<user_group_name>`",
624 "success": true
643 "success": true
625 }
644 }
626 error : null
645 error : null
627 """
646 """
628
647
629 user_group = get_user_group_or_error(usergroupid)
648 user_group = get_user_group_or_error(usergroupid)
630
649
631 if not has_superadmin_permission(apiuser):
650 if not has_superadmin_permission(apiuser):
632 # check if we have admin permission for this user group !
651 # check if we have admin permission for this user group !
633 _perms = ('usergroup.admin',)
652 _perms = ('usergroup.admin',)
634 if not HasUserGroupPermissionAnyApi(*_perms)(
653 if not HasUserGroupPermissionAnyApi(*_perms)(
635 user=apiuser, user_group_name=user_group.users_group_name):
654 user=apiuser, user_group_name=user_group.users_group_name):
636 raise JSONRPCError(
655 raise JSONRPCError(
637 'user group `%s` does not exist' % (usergroupid,))
656 'user group `%s` does not exist' % (usergroupid,))
638
657
639 user = get_user_or_error(userid)
658 user = get_user_or_error(userid)
640
659
641 try:
660 try:
642 UserGroupModel().revoke_user_permission(
661 UserGroupModel().revoke_user_permission(
643 user_group=user_group, user=user)
662 user_group=user_group, user=user)
644 Session().commit()
663 Session().commit()
645 return {
664 return {
646 'msg': 'Revoked perm for user: `%s` in user group: `%s`' % (
665 'msg': 'Revoked perm for user: `%s` in user group: `%s`' % (
647 user.username, user_group.users_group_name
666 user.username, user_group.users_group_name
648 ),
667 ),
649 'success': True
668 'success': True
650 }
669 }
651 except Exception:
670 except Exception:
652 log.exception("Error occurred during editing permissions "
671 log.exception("Error occurred during editing permissions "
653 "for user in user group")
672 "for user in user group")
654 raise JSONRPCError(
673 raise JSONRPCError(
655 'failed to edit permission for user: `%s` in user group: `%s`'
674 'failed to edit permission for user: `%s` in user group: `%s`'
656 % (userid, user_group.users_group_name))
675 % (userid, user_group.users_group_name))
657
676
658
677
659 @jsonrpc_method()
678 @jsonrpc_method()
660 def grant_user_group_permission_to_user_group(
679 def grant_user_group_permission_to_user_group(
661 request, apiuser, usergroupid, sourceusergroupid, perm):
680 request, apiuser, usergroupid, sourceusergroupid, perm):
662 """
681 """
663 Give one user group permissions to another user group.
682 Give one user group permissions to another user group.
664
683
665 :param apiuser: This is filled automatically from the |authtoken|.
684 :param apiuser: This is filled automatically from the |authtoken|.
666 :type apiuser: AuthUser
685 :type apiuser: AuthUser
667 :param usergroupid: Set the user group on which to edit permissions.
686 :param usergroupid: Set the user group on which to edit permissions.
668 :type usergroupid: str or int
687 :type usergroupid: str or int
669 :param sourceusergroupid: Set the source user group to which
688 :param sourceusergroupid: Set the source user group to which
670 access/permissions will be granted.
689 access/permissions will be granted.
671 :type sourceusergroupid: str or int
690 :type sourceusergroupid: str or int
672 :param perm: (usergroup.(none|read|write|admin))
691 :param perm: (usergroup.(none|read|write|admin))
673 :type perm: str
692 :type perm: str
674
693
675 Example output:
694 Example output:
676
695
677 .. code-block:: bash
696 .. code-block:: bash
678
697
679 id : <id_given_in_input>
698 id : <id_given_in_input>
680 result : {
699 result : {
681 "msg": "Granted perm: `<perm_name>` for user group: `<source_user_group_name>` in user group: `<user_group_name>`",
700 "msg": "Granted perm: `<perm_name>` for user group: `<source_user_group_name>` in user group: `<user_group_name>`",
682 "success": true
701 "success": true
683 }
702 }
684 error : null
703 error : null
685 """
704 """
686
705
687 user_group = get_user_group_or_error(sourceusergroupid)
706 user_group = get_user_group_or_error(sourceusergroupid)
688 target_user_group = get_user_group_or_error(usergroupid)
707 target_user_group = get_user_group_or_error(usergroupid)
689 perm = get_perm_or_error(perm, prefix='usergroup.')
708 perm = get_perm_or_error(perm, prefix='usergroup.')
690
709
691 if not has_superadmin_permission(apiuser):
710 if not has_superadmin_permission(apiuser):
692 # check if we have admin permission for this user group !
711 # check if we have admin permission for this user group !
693 _perms = ('usergroup.admin',)
712 _perms = ('usergroup.admin',)
694 if not HasUserGroupPermissionAnyApi(*_perms)(
713 if not HasUserGroupPermissionAnyApi(*_perms)(
695 user=apiuser,
714 user=apiuser,
696 user_group_name=target_user_group.users_group_name):
715 user_group_name=target_user_group.users_group_name):
697 raise JSONRPCError(
716 raise JSONRPCError(
698 'to user group `%s` does not exist' % (usergroupid,))
717 'to user group `%s` does not exist' % (usergroupid,))
699
718
700 # check if we have at least read permission for source user group !
719 # check if we have at least read permission for source user group !
701 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
720 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
702 if not HasUserGroupPermissionAnyApi(*_perms)(
721 if not HasUserGroupPermissionAnyApi(*_perms)(
703 user=apiuser, user_group_name=user_group.users_group_name):
722 user=apiuser, user_group_name=user_group.users_group_name):
704 raise JSONRPCError(
723 raise JSONRPCError(
705 'user group `%s` does not exist' % (sourceusergroupid,))
724 'user group `%s` does not exist' % (sourceusergroupid,))
706
725
707 try:
726 try:
708 UserGroupModel().grant_user_group_permission(
727 UserGroupModel().grant_user_group_permission(
709 target_user_group=target_user_group,
728 target_user_group=target_user_group,
710 user_group=user_group, perm=perm)
729 user_group=user_group, perm=perm)
711 Session().commit()
730 Session().commit()
712
731
713 return {
732 return {
714 'msg': 'Granted perm: `%s` for user group: `%s` '
733 'msg': 'Granted perm: `%s` for user group: `%s` '
715 'in user group: `%s`' % (
734 'in user group: `%s`' % (
716 perm.permission_name, user_group.users_group_name,
735 perm.permission_name, user_group.users_group_name,
717 target_user_group.users_group_name
736 target_user_group.users_group_name
718 ),
737 ),
719 'success': True
738 'success': True
720 }
739 }
721 except Exception:
740 except Exception:
722 log.exception("Error occurred during editing permissions "
741 log.exception("Error occurred during editing permissions "
723 "for user group in user group")
742 "for user group in user group")
724 raise JSONRPCError(
743 raise JSONRPCError(
725 'failed to edit permission for user group: `%s` in '
744 'failed to edit permission for user group: `%s` in '
726 'user group: `%s`' % (
745 'user group: `%s`' % (
727 sourceusergroupid, target_user_group.users_group_name
746 sourceusergroupid, target_user_group.users_group_name
728 )
747 )
729 )
748 )
730
749
731
750
732 @jsonrpc_method()
751 @jsonrpc_method()
733 def revoke_user_group_permission_from_user_group(
752 def revoke_user_group_permission_from_user_group(
734 request, apiuser, usergroupid, sourceusergroupid):
753 request, apiuser, usergroupid, sourceusergroupid):
735 """
754 """
736 Revoke the permissions that one user group has to another.
755 Revoke the permissions that one user group has to another.
737
756
738 :param apiuser: This is filled automatically from the |authtoken|.
757 :param apiuser: This is filled automatically from the |authtoken|.
739 :type apiuser: AuthUser
758 :type apiuser: AuthUser
740 :param usergroupid: Set the user group on which to edit permissions.
759 :param usergroupid: Set the user group on which to edit permissions.
741 :type usergroupid: str or int
760 :type usergroupid: str or int
742 :param sourceusergroupid: Set the user group from which permissions
761 :param sourceusergroupid: Set the user group from which permissions
743 are revoked.
762 are revoked.
744 :type sourceusergroupid: str or int
763 :type sourceusergroupid: str or int
745
764
746 Example output:
765 Example output:
747
766
748 .. code-block:: bash
767 .. code-block:: bash
749
768
750 id : <id_given_in_input>
769 id : <id_given_in_input>
751 result : {
770 result : {
752 "msg": "Revoked perm for user group: `<user_group_name>` in user group: `<target_user_group_name>`",
771 "msg": "Revoked perm for user group: `<user_group_name>` in user group: `<target_user_group_name>`",
753 "success": true
772 "success": true
754 }
773 }
755 error : null
774 error : null
756 """
775 """
757
776
758 user_group = get_user_group_or_error(sourceusergroupid)
777 user_group = get_user_group_or_error(sourceusergroupid)
759 target_user_group = get_user_group_or_error(usergroupid)
778 target_user_group = get_user_group_or_error(usergroupid)
760
779
761 if not has_superadmin_permission(apiuser):
780 if not has_superadmin_permission(apiuser):
762 # check if we have admin permission for this user group !
781 # check if we have admin permission for this user group !
763 _perms = ('usergroup.admin',)
782 _perms = ('usergroup.admin',)
764 if not HasUserGroupPermissionAnyApi(*_perms)(
783 if not HasUserGroupPermissionAnyApi(*_perms)(
765 user=apiuser,
784 user=apiuser,
766 user_group_name=target_user_group.users_group_name):
785 user_group_name=target_user_group.users_group_name):
767 raise JSONRPCError(
786 raise JSONRPCError(
768 'to user group `%s` does not exist' % (usergroupid,))
787 'to user group `%s` does not exist' % (usergroupid,))
769
788
770 # check if we have at least read permission
789 # check if we have at least read permission
771 # for the source user group !
790 # for the source user group !
772 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
791 _perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin',)
773 if not HasUserGroupPermissionAnyApi(*_perms)(
792 if not HasUserGroupPermissionAnyApi(*_perms)(
774 user=apiuser, user_group_name=user_group.users_group_name):
793 user=apiuser, user_group_name=user_group.users_group_name):
775 raise JSONRPCError(
794 raise JSONRPCError(
776 'user group `%s` does not exist' % (sourceusergroupid,))
795 'user group `%s` does not exist' % (sourceusergroupid,))
777
796
778 try:
797 try:
779 UserGroupModel().revoke_user_group_permission(
798 UserGroupModel().revoke_user_group_permission(
780 target_user_group=target_user_group, user_group=user_group)
799 target_user_group=target_user_group, user_group=user_group)
781 Session().commit()
800 Session().commit()
782
801
783 return {
802 return {
784 'msg': 'Revoked perm for user group: '
803 'msg': 'Revoked perm for user group: '
785 '`%s` in user group: `%s`' % (
804 '`%s` in user group: `%s`' % (
786 user_group.users_group_name,
805 user_group.users_group_name,
787 target_user_group.users_group_name
806 target_user_group.users_group_name
788 ),
807 ),
789 'success': True
808 'success': True
790 }
809 }
791 except Exception:
810 except Exception:
792 log.exception("Error occurred during editing permissions "
811 log.exception("Error occurred during editing permissions "
793 "for user group in user group")
812 "for user group in user group")
794 raise JSONRPCError(
813 raise JSONRPCError(
795 'failed to edit permission for user group: '
814 'failed to edit permission for user group: '
796 '`%s` in user group: `%s`' % (
815 '`%s` in user group: `%s`' % (
797 sourceusergroupid, target_user_group.users_group_name
816 sourceusergroupid, target_user_group.users_group_name
798 )
817 )
799 )
818 )
General Comments 0
You need to be logged in to leave comments. Login now