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