##// END OF EJS Templates
permissions: fixed audit log data on user group permissions view.
marcink -
r2854:35372254 stable
parent child Browse files
Show More
@@ -1,519 +1,519 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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 23 import peppercorn
24 24 import formencode
25 25 import formencode.htmlfill
26 26 from pyramid.httpexceptions import HTTPFound
27 27 from pyramid.view import view_config
28 28 from pyramid.response import Response
29 29 from pyramid.renderers import render
30 30
31 31 from rhodecode.lib.exceptions import (
32 32 RepoGroupAssignmentError, UserGroupAssignedException)
33 33 from rhodecode.model.forms import (
34 34 UserGroupPermsForm, UserGroupForm, UserIndividualPermissionsForm,
35 35 UserPermissionsForm)
36 36 from rhodecode.model.permission import PermissionModel
37 37
38 38 from rhodecode.apps._base import UserGroupAppView
39 39 from rhodecode.lib.auth import (
40 40 LoginRequired, HasUserGroupPermissionAnyDecorator, CSRFRequired)
41 41 from rhodecode.lib import helpers as h, audit_logger
42 42 from rhodecode.lib.utils2 import str2bool
43 43 from rhodecode.model.db import User
44 44 from rhodecode.model.meta import Session
45 45 from rhodecode.model.user_group import UserGroupModel
46 46
47 47 log = logging.getLogger(__name__)
48 48
49 49
50 50 class UserGroupsView(UserGroupAppView):
51 51
52 52 def load_default_context(self):
53 53 c = self._get_local_tmpl_context()
54 54
55 55 PermissionModel().set_global_permission_choices(
56 56 c, gettext_translator=self.request.translate)
57 57
58 58 return c
59 59
60 60 @LoginRequired()
61 61 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
62 62 @view_config(
63 63 route_name='user_group_members_data', request_method='GET',
64 64 renderer='json_ext', xhr=True)
65 65 def user_group_members(self):
66 66 """
67 67 Return members of given user group
68 68 """
69 69 self.load_default_context()
70 70 user_group = self.db_user_group
71 71 group_members_obj = sorted((x.user for x in user_group.members),
72 72 key=lambda u: u.username.lower())
73 73
74 74 group_members = [
75 75 {
76 76 'id': user.user_id,
77 77 'first_name': user.first_name,
78 78 'last_name': user.last_name,
79 79 'username': user.username,
80 80 'icon_link': h.gravatar_url(user.email, 30),
81 81 'value_display': h.person(user.email),
82 82 'value': user.username,
83 83 'value_type': 'user',
84 84 'active': user.active,
85 85 }
86 86 for user in group_members_obj
87 87 ]
88 88
89 89 return {
90 90 'members': group_members
91 91 }
92 92
93 93 @LoginRequired()
94 94 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
95 95 @view_config(
96 96 route_name='edit_user_group_perms_summary', request_method='GET',
97 97 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
98 98 def user_group_perms_summary(self):
99 99 c = self.load_default_context()
100 100 c.user_group = self.db_user_group
101 101 c.active = 'perms_summary'
102 102 c.permissions = UserGroupModel().get_perms_summary(
103 103 c.user_group.users_group_id)
104 104 return self._get_template_context(c)
105 105
106 106 @LoginRequired()
107 107 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
108 108 @view_config(
109 109 route_name='edit_user_group_perms_summary_json', request_method='GET',
110 110 renderer='json_ext')
111 111 def user_group_perms_summary_json(self):
112 112 self.load_default_context()
113 113 user_group = self.db_user_group
114 114 return UserGroupModel().get_perms_summary(user_group.users_group_id)
115 115
116 116 def _revoke_perms_on_yourself(self, form_result):
117 117 _updates = filter(lambda u: self._rhodecode_user.user_id == int(u[0]),
118 118 form_result['perm_updates'])
119 119 _additions = filter(lambda u: self._rhodecode_user.user_id == int(u[0]),
120 120 form_result['perm_additions'])
121 121 _deletions = filter(lambda u: self._rhodecode_user.user_id == int(u[0]),
122 122 form_result['perm_deletions'])
123 123 admin_perm = 'usergroup.admin'
124 124 if _updates and _updates[0][1] != admin_perm or \
125 125 _additions and _additions[0][1] != admin_perm or \
126 126 _deletions and _deletions[0][1] != admin_perm:
127 127 return True
128 128 return False
129 129
130 130 @LoginRequired()
131 131 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
132 132 @CSRFRequired()
133 133 @view_config(
134 134 route_name='user_groups_update', request_method='POST',
135 135 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
136 136 def user_group_update(self):
137 137 _ = self.request.translate
138 138
139 139 user_group = self.db_user_group
140 140 user_group_id = user_group.users_group_id
141 141
142 142 c = self.load_default_context()
143 143 c.user_group = user_group
144 144 c.group_members_obj = [x.user for x in c.user_group.members]
145 145 c.group_members_obj.sort(key=lambda u: u.username.lower())
146 146 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
147 147 c.active = 'settings'
148 148
149 149 users_group_form = UserGroupForm(
150 150 self.request.translate, edit=True,
151 151 old_data=c.user_group.get_dict(), allow_disabled=True)()
152 152
153 153 old_values = c.user_group.get_api_data()
154 154 user_group_name = self.request.POST.get('users_group_name')
155 155 try:
156 156 form_result = users_group_form.to_python(self.request.POST)
157 157 pstruct = peppercorn.parse(self.request.POST.items())
158 158 form_result['users_group_members'] = pstruct['user_group_members']
159 159
160 160 user_group, added_members, removed_members = \
161 161 UserGroupModel().update(c.user_group, form_result)
162 162 updated_user_group = form_result['users_group_name']
163 163
164 164 for user_id in added_members:
165 165 user = User.get(user_id)
166 166 user_data = user.get_api_data()
167 167 audit_logger.store_web(
168 168 'user_group.edit.member.add',
169 169 action_data={'user': user_data, 'old_data': old_values},
170 170 user=self._rhodecode_user)
171 171
172 172 for user_id in removed_members:
173 173 user = User.get(user_id)
174 174 user_data = user.get_api_data()
175 175 audit_logger.store_web(
176 176 'user_group.edit.member.delete',
177 177 action_data={'user': user_data, 'old_data': old_values},
178 178 user=self._rhodecode_user)
179 179
180 180 audit_logger.store_web(
181 181 'user_group.edit', action_data={'old_data': old_values},
182 182 user=self._rhodecode_user)
183 183
184 184 h.flash(_('Updated user group %s') % updated_user_group,
185 185 category='success')
186 186 Session().commit()
187 187 except formencode.Invalid as errors:
188 188 defaults = errors.value
189 189 e = errors.error_dict or {}
190 190
191 191 data = render(
192 192 'rhodecode:templates/admin/user_groups/user_group_edit.mako',
193 193 self._get_template_context(c), self.request)
194 194 html = formencode.htmlfill.render(
195 195 data,
196 196 defaults=defaults,
197 197 errors=e,
198 198 prefix_error=False,
199 199 encoding="UTF-8",
200 200 force_defaults=False
201 201 )
202 202 return Response(html)
203 203
204 204 except Exception:
205 205 log.exception("Exception during update of user group")
206 206 h.flash(_('Error occurred during update of user group %s')
207 207 % user_group_name, category='error')
208 208
209 209 raise HTTPFound(
210 210 h.route_path('edit_user_group', user_group_id=user_group_id))
211 211
212 212 @LoginRequired()
213 213 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
214 214 @CSRFRequired()
215 215 @view_config(
216 216 route_name='user_groups_delete', request_method='POST',
217 217 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
218 218 def user_group_delete(self):
219 219 _ = self.request.translate
220 220 user_group = self.db_user_group
221 221
222 222 self.load_default_context()
223 223 force = str2bool(self.request.POST.get('force'))
224 224
225 225 old_values = user_group.get_api_data()
226 226 try:
227 227 UserGroupModel().delete(user_group, force=force)
228 228 audit_logger.store_web(
229 229 'user.delete', action_data={'old_data': old_values},
230 230 user=self._rhodecode_user)
231 231 Session().commit()
232 232 h.flash(_('Successfully deleted user group'), category='success')
233 233 except UserGroupAssignedException as e:
234 234 h.flash(str(e), category='error')
235 235 except Exception:
236 236 log.exception("Exception during deletion of user group")
237 237 h.flash(_('An error occurred during deletion of user group'),
238 238 category='error')
239 239 raise HTTPFound(h.route_path('user_groups'))
240 240
241 241 @LoginRequired()
242 242 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
243 243 @view_config(
244 244 route_name='edit_user_group', request_method='GET',
245 245 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
246 246 def user_group_edit(self):
247 247 user_group = self.db_user_group
248 248
249 249 c = self.load_default_context()
250 250 c.user_group = user_group
251 251 c.group_members_obj = [x.user for x in c.user_group.members]
252 252 c.group_members_obj.sort(key=lambda u: u.username.lower())
253 253 c.group_members = [(x.user_id, x.username) for x in c.group_members_obj]
254 254
255 255 c.active = 'settings'
256 256
257 257 defaults = user_group.get_dict()
258 258 # fill owner
259 259 if user_group.user:
260 260 defaults.update({'user': user_group.user.username})
261 261 else:
262 262 replacement_user = User.get_first_super_admin().username
263 263 defaults.update({'user': replacement_user})
264 264
265 265 data = render(
266 266 'rhodecode:templates/admin/user_groups/user_group_edit.mako',
267 267 self._get_template_context(c), self.request)
268 268 html = formencode.htmlfill.render(
269 269 data,
270 270 defaults=defaults,
271 271 encoding="UTF-8",
272 272 force_defaults=False
273 273 )
274 274 return Response(html)
275 275
276 276 @LoginRequired()
277 277 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
278 278 @view_config(
279 279 route_name='edit_user_group_perms', request_method='GET',
280 280 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
281 281 def user_group_edit_perms(self):
282 282 user_group = self.db_user_group
283 283 c = self.load_default_context()
284 284 c.user_group = user_group
285 285 c.active = 'perms'
286 286
287 287 defaults = {}
288 288 # fill user group users
289 289 for p in c.user_group.user_user_group_to_perm:
290 290 defaults.update({'u_perm_%s' % p.user.user_id:
291 291 p.permission.permission_name})
292 292
293 293 for p in c.user_group.user_group_user_group_to_perm:
294 294 defaults.update({'g_perm_%s' % p.user_group.users_group_id:
295 295 p.permission.permission_name})
296 296
297 297 data = render(
298 298 'rhodecode:templates/admin/user_groups/user_group_edit.mako',
299 299 self._get_template_context(c), self.request)
300 300 html = formencode.htmlfill.render(
301 301 data,
302 302 defaults=defaults,
303 303 encoding="UTF-8",
304 304 force_defaults=False
305 305 )
306 306 return Response(html)
307 307
308 308 @LoginRequired()
309 309 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
310 310 @CSRFRequired()
311 311 @view_config(
312 312 route_name='edit_user_group_perms_update', request_method='POST',
313 313 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
314 314 def user_group_update_perms(self):
315 315 """
316 316 grant permission for given user group
317 317 """
318 318 _ = self.request.translate
319 319
320 320 user_group = self.db_user_group
321 321 user_group_id = user_group.users_group_id
322 322 c = self.load_default_context()
323 323 c.user_group = user_group
324 324 form = UserGroupPermsForm(self.request.translate)().to_python(self.request.POST)
325 325
326 326 if not self._rhodecode_user.is_admin:
327 327 if self._revoke_perms_on_yourself(form):
328 328 msg = _('Cannot change permission for yourself as admin')
329 329 h.flash(msg, category='warning')
330 330 raise HTTPFound(
331 331 h.route_path('edit_user_group_perms',
332 332 user_group_id=user_group_id))
333 333
334 334 try:
335 335 changes = UserGroupModel().update_permissions(
336 user_group_id,
336 user_group,
337 337 form['perm_additions'], form['perm_updates'],
338 338 form['perm_deletions'])
339 339
340 340 except RepoGroupAssignmentError:
341 341 h.flash(_('Target group cannot be the same'), category='error')
342 342 raise HTTPFound(
343 343 h.route_path('edit_user_group_perms',
344 344 user_group_id=user_group_id))
345 345
346 346 action_data = {
347 347 'added': changes['added'],
348 348 'updated': changes['updated'],
349 349 'deleted': changes['deleted'],
350 350 }
351 351 audit_logger.store_web(
352 352 'user_group.edit.permissions', action_data=action_data,
353 353 user=self._rhodecode_user)
354 354
355 355 Session().commit()
356 356 h.flash(_('User Group permissions updated'), category='success')
357 357 raise HTTPFound(
358 358 h.route_path('edit_user_group_perms', user_group_id=user_group_id))
359 359
360 360 @LoginRequired()
361 361 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
362 362 @view_config(
363 363 route_name='edit_user_group_global_perms', request_method='GET',
364 364 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
365 365 def user_group_global_perms_edit(self):
366 366 user_group = self.db_user_group
367 367 c = self.load_default_context()
368 368 c.user_group = user_group
369 369 c.active = 'global_perms'
370 370
371 371 c.default_user = User.get_default_user()
372 372 defaults = c.user_group.get_dict()
373 373 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
374 374 defaults.update(c.user_group.get_default_perms())
375 375
376 376 data = render(
377 377 'rhodecode:templates/admin/user_groups/user_group_edit.mako',
378 378 self._get_template_context(c), self.request)
379 379 html = formencode.htmlfill.render(
380 380 data,
381 381 defaults=defaults,
382 382 encoding="UTF-8",
383 383 force_defaults=False
384 384 )
385 385 return Response(html)
386 386
387 387 @LoginRequired()
388 388 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
389 389 @CSRFRequired()
390 390 @view_config(
391 391 route_name='edit_user_group_global_perms_update', request_method='POST',
392 392 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
393 393 def user_group_global_perms_update(self):
394 394 _ = self.request.translate
395 395 user_group = self.db_user_group
396 396 user_group_id = self.db_user_group.users_group_id
397 397
398 398 c = self.load_default_context()
399 399 c.user_group = user_group
400 400 c.active = 'global_perms'
401 401
402 402 try:
403 403 # first stage that verifies the checkbox
404 404 _form = UserIndividualPermissionsForm(self.request.translate)
405 405 form_result = _form.to_python(dict(self.request.POST))
406 406 inherit_perms = form_result['inherit_default_permissions']
407 407 user_group.inherit_default_permissions = inherit_perms
408 408 Session().add(user_group)
409 409
410 410 if not inherit_perms:
411 411 # only update the individual ones if we un check the flag
412 412 _form = UserPermissionsForm(
413 413 self.request.translate,
414 414 [x[0] for x in c.repo_create_choices],
415 415 [x[0] for x in c.repo_create_on_write_choices],
416 416 [x[0] for x in c.repo_group_create_choices],
417 417 [x[0] for x in c.user_group_create_choices],
418 418 [x[0] for x in c.fork_choices],
419 419 [x[0] for x in c.inherit_default_permission_choices])()
420 420
421 421 form_result = _form.to_python(dict(self.request.POST))
422 422 form_result.update(
423 423 {'perm_user_group_id': user_group.users_group_id})
424 424
425 425 PermissionModel().update_user_group_permissions(form_result)
426 426
427 427 Session().commit()
428 428 h.flash(_('User Group global permissions updated successfully'),
429 429 category='success')
430 430
431 431 except formencode.Invalid as errors:
432 432 defaults = errors.value
433 433
434 434 data = render(
435 435 'rhodecode:templates/admin/user_groups/user_group_edit.mako',
436 436 self._get_template_context(c), self.request)
437 437 html = formencode.htmlfill.render(
438 438 data,
439 439 defaults=defaults,
440 440 errors=errors.error_dict or {},
441 441 prefix_error=False,
442 442 encoding="UTF-8",
443 443 force_defaults=False
444 444 )
445 445 return Response(html)
446 446 except Exception:
447 447 log.exception("Exception during permissions saving")
448 448 h.flash(_('An error occurred during permissions saving'),
449 449 category='error')
450 450
451 451 raise HTTPFound(
452 452 h.route_path('edit_user_group_global_perms',
453 453 user_group_id=user_group_id))
454 454
455 455 @LoginRequired()
456 456 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
457 457 @view_config(
458 458 route_name='edit_user_group_advanced', request_method='GET',
459 459 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
460 460 def user_group_edit_advanced(self):
461 461 user_group = self.db_user_group
462 462
463 463 c = self.load_default_context()
464 464 c.user_group = user_group
465 465 c.active = 'advanced'
466 466 c.group_members_obj = sorted(
467 467 (x.user for x in c.user_group.members),
468 468 key=lambda u: u.username.lower())
469 469
470 470 c.group_to_repos = sorted(
471 471 (x.repository for x in c.user_group.users_group_repo_to_perm),
472 472 key=lambda u: u.repo_name.lower())
473 473
474 474 c.group_to_repo_groups = sorted(
475 475 (x.group for x in c.user_group.users_group_repo_group_to_perm),
476 476 key=lambda u: u.group_name.lower())
477 477
478 478 c.group_to_review_rules = sorted(
479 479 (x.users_group for x in c.user_group.user_group_review_rules),
480 480 key=lambda u: u.users_group_name.lower())
481 481
482 482 return self._get_template_context(c)
483 483
484 484 @LoginRequired()
485 485 @HasUserGroupPermissionAnyDecorator('usergroup.admin')
486 486 @CSRFRequired()
487 487 @view_config(
488 488 route_name='edit_user_group_advanced_sync', request_method='POST',
489 489 renderer='rhodecode:templates/admin/user_groups/user_group_edit.mako')
490 490 def user_group_edit_advanced_set_synchronization(self):
491 491 _ = self.request.translate
492 492 user_group = self.db_user_group
493 493 user_group_id = user_group.users_group_id
494 494
495 495 existing = user_group.group_data.get('extern_type')
496 496
497 497 if existing:
498 498 new_state = user_group.group_data
499 499 new_state['extern_type'] = None
500 500 else:
501 501 new_state = user_group.group_data
502 502 new_state['extern_type'] = 'manual'
503 503 new_state['extern_type_set_by'] = self._rhodecode_user.username
504 504
505 505 try:
506 506 user_group.group_data = new_state
507 507 Session().add(user_group)
508 508 Session().commit()
509 509
510 510 h.flash(_('User Group synchronization updated successfully'),
511 511 category='success')
512 512 except Exception:
513 513 log.exception("Exception during sync settings saving")
514 514 h.flash(_('An error occurred during synchronization update'),
515 515 category='error')
516 516
517 517 raise HTTPFound(
518 518 h.route_path('edit_user_group_advanced',
519 519 user_group_id=user_group_id))
General Comments 0
You need to be logged in to leave comments. Login now