Mercurial > kallithea
comparison rhodecode/controllers/admin/repo_groups.py @ 4116:ffd45b185016 rhodecode-2.2.5-gpl
Imported some of the GPLv3'd changes from RhodeCode v2.2.5.
This imports changes between changesets 21af6c4eab3d and 6177597791c2 in
RhodeCode's original repository, including only changes to Python files and HTML.
RhodeCode clearly licensed its changes to these files under GPLv3
in their /LICENSE file, which states the following:
The Python code and integrated HTML are licensed under the GPLv3 license.
(See:
https://code.rhodecode.com/rhodecode/files/v2.2.5/LICENSE
or
http://web.archive.org/web/20140512193334/https://code.rhodecode.com/rhodecode/files/f3b123159901f15426d18e3dc395e8369f70ebe0/LICENSE
for an online copy of that LICENSE file)
Conservancy reviewed these changes and confirmed that they can be licensed as
a whole to the Kallithea project under GPLv3-only.
While some of the contents committed herein are clearly licensed
GPLv3-or-later, on the whole we must assume the are GPLv3-only, since the
statement above from RhodeCode indicates that they intend GPLv3-only as their
license, per GPLv3ยง14 and other relevant sections of GPLv3.
author | Bradley M. Kuhn <bkuhn@sfconservancy.org> |
---|---|
date | Wed, 02 Jul 2014 19:03:13 -0400 |
parents | |
children | 7e5f8c12a3fc |
comparison
equal
deleted
inserted
replaced
4115:8b7294a804a0 | 4116:ffd45b185016 |
---|---|
1 # -*- coding: utf-8 -*- | |
2 # This program is free software: you can redistribute it and/or modify | |
3 # it under the terms of the GNU General Public License as published by | |
4 # the Free Software Foundation, either version 3 of the License, or | |
5 # (at your option) any later version. | |
6 # | |
7 # This program is distributed in the hope that it will be useful, | |
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
10 # GNU General Public License for more details. | |
11 # | |
12 # You should have received a copy of the GNU General Public License | |
13 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
14 """ | |
15 rhodecode.controllers.admin.repo_groups | |
16 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
17 | |
18 Repository groups controller for RhodeCode | |
19 | |
20 :created_on: Mar 23, 2010 | |
21 :author: marcink | |
22 :copyright: (c) 2013 RhodeCode GmbH. | |
23 :license: GPLv3, see LICENSE for more details. | |
24 """ | |
25 | |
26 import logging | |
27 import traceback | |
28 import formencode | |
29 import itertools | |
30 | |
31 from formencode import htmlfill | |
32 | |
33 from pylons import request, tmpl_context as c, url | |
34 from pylons.controllers.util import abort, redirect | |
35 from pylons.i18n.translation import _, ungettext | |
36 | |
37 from sqlalchemy.exc import IntegrityError | |
38 | |
39 import rhodecode | |
40 from rhodecode.lib import helpers as h | |
41 from rhodecode.lib.compat import json | |
42 from rhodecode.lib.auth import LoginRequired, HasPermissionAnyDecorator,\ | |
43 HasRepoGroupPermissionAnyDecorator, HasRepoGroupPermissionAll,\ | |
44 HasPermissionAll | |
45 from rhodecode.lib.base import BaseController, render | |
46 from rhodecode.model.db import RepoGroup, Repository | |
47 from rhodecode.model.scm import RepoGroupList | |
48 from rhodecode.model.repo_group import RepoGroupModel | |
49 from rhodecode.model.forms import RepoGroupForm, RepoGroupPermsForm | |
50 from rhodecode.model.meta import Session | |
51 from rhodecode.model.repo import RepoModel | |
52 from webob.exc import HTTPInternalServerError, HTTPNotFound | |
53 from rhodecode.lib.utils2 import str2bool, safe_int | |
54 from sqlalchemy.sql.expression import func | |
55 | |
56 | |
57 log = logging.getLogger(__name__) | |
58 | |
59 | |
60 class RepoGroupsController(BaseController): | |
61 """REST Controller styled on the Atom Publishing Protocol""" | |
62 | |
63 @LoginRequired() | |
64 def __before__(self): | |
65 super(RepoGroupsController, self).__before__() | |
66 | |
67 def __load_defaults(self, allow_empty_group=False, exclude_group_ids=[]): | |
68 if HasPermissionAll('hg.admin')('group edit'): | |
69 #we're global admin, we're ok and we can create TOP level groups | |
70 allow_empty_group = True | |
71 | |
72 #override the choices for this form, we need to filter choices | |
73 #and display only those we have ADMIN right | |
74 groups_with_admin_rights = RepoGroupList(RepoGroup.query().all(), | |
75 perm_set=['group.admin']) | |
76 c.repo_groups = RepoGroup.groups_choices(groups=groups_with_admin_rights, | |
77 show_empty_group=allow_empty_group) | |
78 # exclude filtered ids | |
79 c.repo_groups = filter(lambda x: x[0] not in exclude_group_ids, | |
80 c.repo_groups) | |
81 c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups) | |
82 repo_model = RepoModel() | |
83 c.users_array = repo_model.get_users_js() | |
84 c.user_groups_array = repo_model.get_user_groups_js() | |
85 | |
86 def __load_data(self, group_id): | |
87 """ | |
88 Load defaults settings for edit, and update | |
89 | |
90 :param group_id: | |
91 """ | |
92 repo_group = RepoGroup.get_or_404(group_id) | |
93 data = repo_group.get_dict() | |
94 data['group_name'] = repo_group.name | |
95 | |
96 # fill repository group users | |
97 for p in repo_group.repo_group_to_perm: | |
98 data.update({'u_perm_%s' % p.user.username: | |
99 p.permission.permission_name}) | |
100 | |
101 # fill repository group groups | |
102 for p in repo_group.users_group_to_perm: | |
103 data.update({'g_perm_%s' % p.users_group.users_group_name: | |
104 p.permission.permission_name}) | |
105 | |
106 return data | |
107 | |
108 def _revoke_perms_on_yourself(self, form_result): | |
109 _up = filter(lambda u: c.rhodecode_user.username == u[0], | |
110 form_result['perms_updates']) | |
111 _new = filter(lambda u: c.rhodecode_user.username == u[0], | |
112 form_result['perms_new']) | |
113 if _new and _new[0][1] != 'group.admin' or _up and _up[0][1] != 'group.admin': | |
114 return True | |
115 return False | |
116 | |
117 def index(self, format='html'): | |
118 """GET /repo_groups: All items in the collection""" | |
119 # url('repos_groups') | |
120 _list = RepoGroup.query()\ | |
121 .order_by(func.lower(RepoGroup.group_name))\ | |
122 .all() | |
123 group_iter = RepoGroupList(_list, perm_set=['group.admin']) | |
124 repo_groups_data = [] | |
125 total_records = len(group_iter) | |
126 _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup | |
127 template = _tmpl_lookup.get_template('data_table/_dt_elements.html') | |
128 | |
129 repo_group_name = lambda repo_group_name, children_groups: ( | |
130 template.get_def("repo_group_name") | |
131 .render(repo_group_name, children_groups, _=_, h=h, c=c) | |
132 ) | |
133 repo_group_actions = lambda repo_group_id, repo_group_name, gr_count: ( | |
134 template.get_def("repo_group_actions") | |
135 .render(repo_group_id, repo_group_name, gr_count, _=_, h=h, c=c, | |
136 ungettext=ungettext) | |
137 ) | |
138 | |
139 for repo_gr in group_iter: | |
140 children_groups = map(h.safe_unicode, | |
141 itertools.chain((g.name for g in repo_gr.parents), | |
142 (x.name for x in [repo_gr]))) | |
143 repo_count = repo_gr.repositories.count() | |
144 repo_groups_data.append({ | |
145 "raw_name": repo_gr.group_name, | |
146 "group_name": repo_group_name(repo_gr.group_name, children_groups), | |
147 "desc": repo_gr.group_description, | |
148 "repos": repo_count, | |
149 "owner": h.person(repo_gr.user.username), | |
150 "action": repo_group_actions(repo_gr.group_id, repo_gr.group_name, | |
151 repo_count) | |
152 }) | |
153 | |
154 c.data = json.dumps({ | |
155 "totalRecords": total_records, | |
156 "startIndex": 0, | |
157 "sort": None, | |
158 "dir": "asc", | |
159 "records": repo_groups_data | |
160 }) | |
161 | |
162 return render('admin/repo_groups/repo_groups.html') | |
163 | |
164 def create(self): | |
165 """POST /repo_groups: Create a new item""" | |
166 # url('repos_groups') | |
167 | |
168 self.__load_defaults() | |
169 | |
170 # permissions for can create group based on parent_id are checked | |
171 # here in the Form | |
172 repo_group_form = RepoGroupForm(available_groups= | |
173 map(lambda k: unicode(k[0]), c.repo_groups))() | |
174 try: | |
175 form_result = repo_group_form.to_python(dict(request.POST)) | |
176 RepoGroupModel().create( | |
177 group_name=form_result['group_name'], | |
178 group_description=form_result['group_description'], | |
179 parent=form_result['group_parent_id'], | |
180 owner=self.rhodecode_user.user_id, | |
181 copy_permissions=form_result['group_copy_permissions'] | |
182 ) | |
183 Session().commit() | |
184 h.flash(_('Created repository group %s') \ | |
185 % form_result['group_name'], category='success') | |
186 #TODO: in futureaction_logger(, '', '', '', self.sa) | |
187 except formencode.Invalid, errors: | |
188 return htmlfill.render( | |
189 render('admin/repo_groups/repo_group_add.html'), | |
190 defaults=errors.value, | |
191 errors=errors.error_dict or {}, | |
192 prefix_error=False, | |
193 encoding="UTF-8") | |
194 except Exception: | |
195 log.error(traceback.format_exc()) | |
196 h.flash(_('Error occurred during creation of repository group %s') \ | |
197 % request.POST.get('group_name'), category='error') | |
198 parent_group_id = form_result['group_parent_id'] | |
199 #TODO: maybe we should get back to the main view, not the admin one | |
200 return redirect(url('repos_groups', parent_group=parent_group_id)) | |
201 | |
202 def new(self): | |
203 """GET /repo_groups/new: Form to create a new item""" | |
204 # url('new_repos_group') | |
205 if HasPermissionAll('hg.admin')('group create'): | |
206 #we're global admin, we're ok and we can create TOP level groups | |
207 pass | |
208 else: | |
209 # we pass in parent group into creation form, thus we know | |
210 # what would be the group, we can check perms here ! | |
211 group_id = safe_int(request.GET.get('parent_group')) | |
212 group = RepoGroup.get(group_id) if group_id else None | |
213 group_name = group.group_name if group else None | |
214 if HasRepoGroupPermissionAll('group.admin')(group_name, 'group create'): | |
215 pass | |
216 else: | |
217 return abort(403) | |
218 | |
219 self.__load_defaults() | |
220 return render('admin/repo_groups/repo_group_add.html') | |
221 | |
222 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
223 def update(self, group_name): | |
224 """PUT /repo_groups/group_name: Update an existing item""" | |
225 # Forms posted to this method should contain a hidden field: | |
226 # <input type="hidden" name="_method" value="PUT" /> | |
227 # Or using helpers: | |
228 # h.form(url('repos_group', group_name=GROUP_NAME), | |
229 # method='put') | |
230 # url('repos_group', group_name=GROUP_NAME) | |
231 | |
232 c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
233 if HasPermissionAll('hg.admin')('group edit'): | |
234 #we're global admin, we're ok and we can create TOP level groups | |
235 allow_empty_group = True | |
236 elif not c.repo_group.parent_group: | |
237 allow_empty_group = True | |
238 else: | |
239 allow_empty_group = False | |
240 self.__load_defaults(allow_empty_group=allow_empty_group, | |
241 exclude_group_ids=[c.repo_group.group_id]) | |
242 | |
243 repo_group_form = RepoGroupForm( | |
244 edit=True, | |
245 old_data=c.repo_group.get_dict(), | |
246 available_groups=c.repo_groups_choices, | |
247 can_create_in_root=allow_empty_group, | |
248 )() | |
249 try: | |
250 form_result = repo_group_form.to_python(dict(request.POST)) | |
251 | |
252 new_gr = RepoGroupModel().update(group_name, form_result) | |
253 Session().commit() | |
254 h.flash(_('Updated repository group %s') \ | |
255 % form_result['group_name'], category='success') | |
256 # we now have new name ! | |
257 group_name = new_gr.group_name | |
258 #TODO: in future action_logger(, '', '', '', self.sa) | |
259 except formencode.Invalid, errors: | |
260 | |
261 return htmlfill.render( | |
262 render('admin/repo_groups/repo_group_edit.html'), | |
263 defaults=errors.value, | |
264 errors=errors.error_dict or {}, | |
265 prefix_error=False, | |
266 encoding="UTF-8") | |
267 except Exception: | |
268 log.error(traceback.format_exc()) | |
269 h.flash(_('Error occurred during update of repository group %s') \ | |
270 % request.POST.get('group_name'), category='error') | |
271 | |
272 return redirect(url('edit_repo_group', group_name=group_name)) | |
273 | |
274 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
275 def delete(self, group_name): | |
276 """DELETE /repo_groups/group_name: Delete an existing item""" | |
277 # Forms posted to this method should contain a hidden field: | |
278 # <input type="hidden" name="_method" value="DELETE" /> | |
279 # Or using helpers: | |
280 # h.form(url('repos_group', group_name=GROUP_NAME), | |
281 # method='delete') | |
282 # url('repos_group', group_name=GROUP_NAME) | |
283 | |
284 gr = c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
285 repos = gr.repositories.all() | |
286 if repos: | |
287 h.flash(_('This group contains %s repositores and cannot be ' | |
288 'deleted') % len(repos), category='warning') | |
289 return redirect(url('repos_groups')) | |
290 | |
291 children = gr.children.all() | |
292 if children: | |
293 h.flash(_('This group contains %s subgroups and cannot be deleted' | |
294 % (len(children))), category='warning') | |
295 return redirect(url('repos_groups')) | |
296 | |
297 try: | |
298 RepoGroupModel().delete(group_name) | |
299 Session().commit() | |
300 h.flash(_('Removed repository group %s') % group_name, | |
301 category='success') | |
302 #TODO: in future action_logger(, '', '', '', self.sa) | |
303 except Exception: | |
304 log.error(traceback.format_exc()) | |
305 h.flash(_('Error occurred during deletion of repository group %s') | |
306 % group_name, category='error') | |
307 | |
308 return redirect(url('repos_groups')) | |
309 | |
310 def show_by_name(self, group_name): | |
311 """ | |
312 This is a proxy that does a lookup group_name -> id, and shows | |
313 the group by id view instead | |
314 """ | |
315 group_name = group_name.rstrip('/') | |
316 id_ = RepoGroup.get_by_group_name(group_name) | |
317 if id_: | |
318 return self.show(group_name) | |
319 raise HTTPNotFound | |
320 | |
321 @HasRepoGroupPermissionAnyDecorator('group.read', 'group.write', | |
322 'group.admin') | |
323 def show(self, group_name): | |
324 """GET /repo_groups/group_name: Show a specific item""" | |
325 # url('repos_group', group_name=GROUP_NAME) | |
326 c.active = 'settings' | |
327 | |
328 c.group = c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
329 c.group_repos = c.group.repositories.all() | |
330 | |
331 #overwrite our cached list with current filter | |
332 gr_filter = c.group_repos | |
333 c.repo_cnt = 0 | |
334 | |
335 groups = RepoGroup.query().order_by(RepoGroup.group_name)\ | |
336 .filter(RepoGroup.group_parent_id == c.group.group_id).all() | |
337 c.groups = self.scm_model.get_repo_groups(groups) | |
338 | |
339 c.repos_list = Repository.query()\ | |
340 .filter(Repository.group_id == c.group.group_id)\ | |
341 .order_by(func.lower(Repository.repo_name))\ | |
342 .all() | |
343 | |
344 repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list, | |
345 admin=False) | |
346 #json used to render the grid | |
347 c.data = json.dumps(repos_data) | |
348 | |
349 return render('admin/repo_groups/repo_group_show.html') | |
350 | |
351 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
352 def edit(self, group_name): | |
353 """GET /repo_groups/group_name/edit: Form to edit an existing item""" | |
354 # url('edit_repo_group', group_name=GROUP_NAME) | |
355 c.active = 'settings' | |
356 | |
357 c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
358 #we can only allow moving empty group if it's already a top-level | |
359 #group, ie has no parents, or we're admin | |
360 if HasPermissionAll('hg.admin')('group edit'): | |
361 #we're global admin, we're ok and we can create TOP level groups | |
362 allow_empty_group = True | |
363 elif not c.repo_group.parent_group: | |
364 allow_empty_group = True | |
365 else: | |
366 allow_empty_group = False | |
367 | |
368 self.__load_defaults(allow_empty_group=allow_empty_group, | |
369 exclude_group_ids=[c.repo_group.group_id]) | |
370 defaults = self.__load_data(c.repo_group.group_id) | |
371 | |
372 return htmlfill.render( | |
373 render('admin/repo_groups/repo_group_edit.html'), | |
374 defaults=defaults, | |
375 encoding="UTF-8", | |
376 force_defaults=False | |
377 ) | |
378 | |
379 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
380 def edit_repo_group_advanced(self, group_name): | |
381 """GET /repo_groups/group_name/edit: Form to edit an existing item""" | |
382 # url('edit_repo_group', group_name=GROUP_NAME) | |
383 c.active = 'advanced' | |
384 c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
385 | |
386 return render('admin/repo_groups/repo_group_edit.html') | |
387 | |
388 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
389 def edit_repo_group_perms(self, group_name): | |
390 """GET /repo_groups/group_name/edit: Form to edit an existing item""" | |
391 # url('edit_repo_group', group_name=GROUP_NAME) | |
392 c.active = 'perms' | |
393 c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
394 self.__load_defaults() | |
395 defaults = self.__load_data(c.repo_group.group_id) | |
396 | |
397 return htmlfill.render( | |
398 render('admin/repo_groups/repo_group_edit.html'), | |
399 defaults=defaults, | |
400 encoding="UTF-8", | |
401 force_defaults=False | |
402 ) | |
403 | |
404 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
405 def update_perms(self, group_name): | |
406 """ | |
407 Update permissions for given repository group | |
408 | |
409 :param group_name: | |
410 """ | |
411 | |
412 c.repo_group = RepoGroupModel()._get_repo_group(group_name) | |
413 valid_recursive_choices = ['none', 'repos', 'groups', 'all'] | |
414 form_result = RepoGroupPermsForm(valid_recursive_choices)().to_python(request.POST) | |
415 if not c.rhodecode_user.is_admin: | |
416 if self._revoke_perms_on_yourself(form_result): | |
417 msg = _('Cannot revoke permission for yourself as admin') | |
418 h.flash(msg, category='warning') | |
419 return redirect(url('edit_repo_group_perms', group_name=group_name)) | |
420 recursive = form_result['recursive'] | |
421 # iterate over all members(if in recursive mode) of this groups and | |
422 # set the permissions ! | |
423 # this can be potentially heavy operation | |
424 RepoGroupModel()._update_permissions(c.repo_group, | |
425 form_result['perms_new'], | |
426 form_result['perms_updates'], | |
427 recursive) | |
428 #TODO: implement this | |
429 #action_logger(self.rhodecode_user, 'admin_changed_repo_permissions', | |
430 # repo_name, self.ip_addr, self.sa) | |
431 Session().commit() | |
432 h.flash(_('Repository Group permissions updated'), category='success') | |
433 return redirect(url('edit_repo_group_perms', group_name=group_name)) | |
434 | |
435 @HasRepoGroupPermissionAnyDecorator('group.admin') | |
436 def delete_perms(self, group_name): | |
437 """ | |
438 DELETE an existing repository group permission user | |
439 | |
440 :param group_name: | |
441 """ | |
442 try: | |
443 obj_type = request.POST.get('obj_type') | |
444 obj_id = None | |
445 if obj_type == 'user': | |
446 obj_id = safe_int(request.POST.get('user_id')) | |
447 elif obj_type == 'user_group': | |
448 obj_id = safe_int(request.POST.get('user_group_id')) | |
449 | |
450 if not c.rhodecode_user.is_admin: | |
451 if obj_type == 'user' and c.rhodecode_user.user_id == obj_id: | |
452 msg = _('Cannot revoke permission for yourself as admin') | |
453 h.flash(msg, category='warning') | |
454 raise Exception('revoke admin permission on self') | |
455 recursive = request.POST.get('recursive', 'none') | |
456 if obj_type == 'user': | |
457 RepoGroupModel().delete_permission(repo_group=group_name, | |
458 obj=obj_id, obj_type='user', | |
459 recursive=recursive) | |
460 elif obj_type == 'user_group': | |
461 RepoGroupModel().delete_permission(repo_group=group_name, | |
462 obj=obj_id, | |
463 obj_type='user_group', | |
464 recursive=recursive) | |
465 | |
466 Session().commit() | |
467 except Exception: | |
468 log.error(traceback.format_exc()) | |
469 h.flash(_('An error occurred during revoking of permission'), | |
470 category='error') | |
471 raise HTTPInternalServerError() |