##// END OF EJS Templates
user group: sort lists of current and available members by username...
Mads Kiilerich -
r3624:4dddb7ee beta
parent child Browse files
Show More
@@ -1,282 +1,284 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 rhodecode.controllers.admin.users_groups
4 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 5
6 6 User Groups crud controller for pylons
7 7
8 8 :created_on: Jan 25, 2011
9 9 :author: marcink
10 10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
11 11 :license: GPLv3, see COPYING for more details.
12 12 """
13 13 # This program is free software: you can redistribute it and/or modify
14 14 # it under the terms of the GNU General Public License as published by
15 15 # the Free Software Foundation, either version 3 of the License, or
16 16 # (at your option) any later version.
17 17 #
18 18 # This program is distributed in the hope that it will be useful,
19 19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 21 # GNU General Public License for more details.
22 22 #
23 23 # You should have received a copy of the GNU General Public License
24 24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 25
26 26 import logging
27 27 import traceback
28 28 import formencode
29 29
30 30 from formencode import htmlfill
31 31 from pylons import request, session, tmpl_context as c, url, config
32 32 from pylons.controllers.util import abort, redirect
33 33 from pylons.i18n.translation import _
34 34
35 35 from rhodecode.lib import helpers as h
36 36 from rhodecode.lib.exceptions import UserGroupsAssignedException
37 37 from rhodecode.lib.utils2 import safe_unicode, str2bool
38 38 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
39 39 from rhodecode.lib.base import BaseController, render
40 40
41 41 from rhodecode.model.users_group import UserGroupModel
42 42
43 43 from rhodecode.model.db import User, UserGroup, UserGroupToPerm,\
44 44 UserGroupRepoToPerm, UserGroupRepoGroupToPerm
45 45 from rhodecode.model.forms import UserGroupForm
46 46 from rhodecode.model.meta import Session
47 47 from rhodecode.lib.utils import action_logger
48 48 from sqlalchemy.orm import joinedload
49 49
50 50 log = logging.getLogger(__name__)
51 51
52 52
53 53 class UsersGroupsController(BaseController):
54 54 """REST Controller styled on the Atom Publishing Protocol"""
55 55 # To properly map this controller, ensure your config/routing.py
56 56 # file has a resource setup:
57 57 # map.resource('users_group', 'users_groups')
58 58
59 59 @LoginRequired()
60 60 @HasPermissionAllDecorator('hg.admin')
61 61 def __before__(self):
62 62 c.admin_user = session.get('admin_user')
63 63 c.admin_username = session.get('admin_username')
64 64 super(UsersGroupsController, self).__before__()
65 65 c.available_permissions = config['available_permissions']
66 66
67 67 def index(self, format='html'):
68 68 """GET /users_groups: All items in the collection"""
69 69 # url('users_groups')
70 70 c.users_groups_list = UserGroup().query().all()
71 71 return render('admin/users_groups/users_groups.html')
72 72
73 73 def create(self):
74 74 """POST /users_groups: Create a new item"""
75 75 # url('users_groups')
76 76
77 77 users_group_form = UserGroupForm()()
78 78 try:
79 79 form_result = users_group_form.to_python(dict(request.POST))
80 80 UserGroupModel().create(name=form_result['users_group_name'],
81 81 active=form_result['users_group_active'])
82 82 gr = form_result['users_group_name']
83 83 action_logger(self.rhodecode_user,
84 84 'admin_created_users_group:%s' % gr,
85 85 None, self.ip_addr, self.sa)
86 86 h.flash(_('Created user group %s') % gr, category='success')
87 87 Session().commit()
88 88 except formencode.Invalid, errors:
89 89 return htmlfill.render(
90 90 render('admin/users_groups/users_group_add.html'),
91 91 defaults=errors.value,
92 92 errors=errors.error_dict or {},
93 93 prefix_error=False,
94 94 encoding="UTF-8")
95 95 except Exception:
96 96 log.error(traceback.format_exc())
97 97 h.flash(_('Error occurred during creation of user group %s') \
98 98 % request.POST.get('users_group_name'), category='error')
99 99
100 100 return redirect(url('users_groups'))
101 101
102 102 def new(self, format='html'):
103 103 """GET /users_groups/new: Form to create a new item"""
104 104 # url('new_users_group')
105 105 return render('admin/users_groups/users_group_add.html')
106 106
107 107 def _load_data(self, id):
108 108 c.users_group.permissions = {
109 109 'repositories': {},
110 110 'repositories_groups': {}
111 111 }
112 112
113 113 ugroup_repo_perms = UserGroupRepoToPerm.query()\
114 114 .options(joinedload(UserGroupRepoToPerm.permission))\
115 115 .options(joinedload(UserGroupRepoToPerm.repository))\
116 116 .filter(UserGroupRepoToPerm.users_group_id == id)\
117 117 .all()
118 118
119 119 for gr in ugroup_repo_perms:
120 120 c.users_group.permissions['repositories'][gr.repository.repo_name] \
121 121 = gr.permission.permission_name
122 122
123 123 ugroup_group_perms = UserGroupRepoGroupToPerm.query()\
124 124 .options(joinedload(UserGroupRepoGroupToPerm.permission))\
125 125 .options(joinedload(UserGroupRepoGroupToPerm.group))\
126 126 .filter(UserGroupRepoGroupToPerm.users_group_id == id)\
127 127 .all()
128 128
129 129 for gr in ugroup_group_perms:
130 130 c.users_group.permissions['repositories_groups'][gr.group.group_name] \
131 131 = gr.permission.permission_name
132 132
133 c.group_members_obj = [x.user for x in c.users_group.members]
133 c.group_members_obj = sorted((x.user for x in c.users_group.members),
134 key=lambda u: u.username.lower())
134 135 c.group_members = [(x.user_id, x.username) for x in
135 136 c.group_members_obj]
136 c.available_members = [(x.user_id, x.username) for x in
137 User.query().all()]
137 c.available_members = sorted(((x.user_id, x.username) for x in
138 User.query().all()),
139 key=lambda u: u[1].lower())
138 140
139 141 def update(self, id):
140 142 """PUT /users_groups/id: Update an existing item"""
141 143 # Forms posted to this method should contain a hidden field:
142 144 # <input type="hidden" name="_method" value="PUT" />
143 145 # Or using helpers:
144 146 # h.form(url('users_group', id=ID),
145 147 # method='put')
146 148 # url('users_group', id=ID)
147 149
148 150 c.users_group = UserGroup.get_or_404(id)
149 151 self._load_data(id)
150 152
151 153 available_members = [safe_unicode(x[0]) for x in c.available_members]
152 154
153 155 users_group_form = UserGroupForm(edit=True,
154 156 old_data=c.users_group.get_dict(),
155 157 available_members=available_members)()
156 158
157 159 try:
158 160 form_result = users_group_form.to_python(request.POST)
159 161 UserGroupModel().update(c.users_group, form_result)
160 162 gr = form_result['users_group_name']
161 163 action_logger(self.rhodecode_user,
162 164 'admin_updated_users_group:%s' % gr,
163 165 None, self.ip_addr, self.sa)
164 166 h.flash(_('Updated user group %s') % gr, category='success')
165 167 Session().commit()
166 168 except formencode.Invalid, errors:
167 169 ug_model = UserGroupModel()
168 170 defaults = errors.value
169 171 e = errors.error_dict or {}
170 172 defaults.update({
171 173 'create_repo_perm': ug_model.has_perm(id,
172 174 'hg.create.repository'),
173 175 'fork_repo_perm': ug_model.has_perm(id,
174 176 'hg.fork.repository'),
175 177 '_method': 'put'
176 178 })
177 179
178 180 return htmlfill.render(
179 181 render('admin/users_groups/users_group_edit.html'),
180 182 defaults=defaults,
181 183 errors=e,
182 184 prefix_error=False,
183 185 encoding="UTF-8")
184 186 except Exception:
185 187 log.error(traceback.format_exc())
186 188 h.flash(_('Error occurred during update of user group %s') \
187 189 % request.POST.get('users_group_name'), category='error')
188 190
189 191 return redirect(url('edit_users_group', id=id))
190 192
191 193 def delete(self, id):
192 194 """DELETE /users_groups/id: Delete an existing item"""
193 195 # Forms posted to this method should contain a hidden field:
194 196 # <input type="hidden" name="_method" value="DELETE" />
195 197 # Or using helpers:
196 198 # h.form(url('users_group', id=ID),
197 199 # method='delete')
198 200 # url('users_group', id=ID)
199 201 usr_gr = UserGroup.get_or_404(id)
200 202 try:
201 203 UserGroupModel().delete(usr_gr)
202 204 Session().commit()
203 205 h.flash(_('Successfully deleted user group'), category='success')
204 206 except UserGroupsAssignedException, e:
205 207 h.flash(e, category='error')
206 208 except Exception:
207 209 log.error(traceback.format_exc())
208 210 h.flash(_('An error occurred during deletion of user group'),
209 211 category='error')
210 212 return redirect(url('users_groups'))
211 213
212 214 def show(self, id, format='html'):
213 215 """GET /users_groups/id: Show a specific item"""
214 216 # url('users_group', id=ID)
215 217
216 218 def edit(self, id, format='html'):
217 219 """GET /users_groups/id/edit: Form to edit an existing item"""
218 220 # url('edit_users_group', id=ID)
219 221
220 222 c.users_group = UserGroup.get_or_404(id)
221 223 self._load_data(id)
222 224
223 225 ug_model = UserGroupModel()
224 226 defaults = c.users_group.get_dict()
225 227 defaults.update({
226 228 'create_repo_perm': ug_model.has_perm(c.users_group,
227 229 'hg.create.repository'),
228 230 'fork_repo_perm': ug_model.has_perm(c.users_group,
229 231 'hg.fork.repository'),
230 232 })
231 233
232 234 return htmlfill.render(
233 235 render('admin/users_groups/users_group_edit.html'),
234 236 defaults=defaults,
235 237 encoding="UTF-8",
236 238 force_defaults=False
237 239 )
238 240
239 241 def update_perm(self, id):
240 242 """PUT /users_perm/id: Update an existing item"""
241 243 # url('users_group_perm', id=ID, method='put')
242 244
243 245 users_group = UserGroup.get_or_404(id)
244 246 grant_create_perm = str2bool(request.POST.get('create_repo_perm'))
245 247 grant_fork_perm = str2bool(request.POST.get('fork_repo_perm'))
246 248 inherit_perms = str2bool(request.POST.get('inherit_default_permissions'))
247 249
248 250 usergroup_model = UserGroupModel()
249 251
250 252 try:
251 253 users_group.inherit_default_permissions = inherit_perms
252 254 Session().add(users_group)
253 255
254 256 if grant_create_perm:
255 257 usergroup_model.revoke_perm(id, 'hg.create.none')
256 258 usergroup_model.grant_perm(id, 'hg.create.repository')
257 259 h.flash(_("Granted 'repository create' permission to user group"),
258 260 category='success')
259 261 else:
260 262 usergroup_model.revoke_perm(id, 'hg.create.repository')
261 263 usergroup_model.grant_perm(id, 'hg.create.none')
262 264 h.flash(_("Revoked 'repository create' permission to user group"),
263 265 category='success')
264 266
265 267 if grant_fork_perm:
266 268 usergroup_model.revoke_perm(id, 'hg.fork.none')
267 269 usergroup_model.grant_perm(id, 'hg.fork.repository')
268 270 h.flash(_("Granted 'repository fork' permission to user group"),
269 271 category='success')
270 272 else:
271 273 usergroup_model.revoke_perm(id, 'hg.fork.repository')
272 274 usergroup_model.grant_perm(id, 'hg.fork.none')
273 275 h.flash(_("Revoked 'repository fork' permission to user group"),
274 276 category='success')
275 277
276 278 Session().commit()
277 279 except Exception:
278 280 log.error(traceback.format_exc())
279 281 h.flash(_('An error occurred during permissions saving'),
280 282 category='error')
281 283
282 284 return redirect(url('edit_users_group', id=id))
@@ -1,228 +1,228 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="/base/base.html"/>
3 3
4 4 <%def name="title()">
5 5 ${_('Edit user group')} ${c.users_group.users_group_name} &middot; ${c.rhodecode_name}
6 6 </%def>
7 7
8 8 <%def name="breadcrumbs_links()">
9 9 ${h.link_to(_('Admin'),h.url('admin_home'))}
10 10 &raquo;
11 11 ${h.link_to(_('UserGroups'),h.url('users_groups'))}
12 12 &raquo;
13 13 ${_('edit')} "${c.users_group.users_group_name}"
14 14 </%def>
15 15
16 16 <%def name="page_nav()">
17 17 ${self.menu('admin')}
18 18 </%def>
19 19
20 20 <%def name="main()">
21 21 <div class="box box-left">
22 22 <!-- box / title -->
23 23 <div class="title">
24 24 ${self.breadcrumbs()}
25 25 </div>
26 26 <!-- end box / title -->
27 27 ${h.form(url('users_group', id=c.users_group.users_group_id),method='put', id='edit_users_group')}
28 28 <div class="form">
29 29 <!-- fields -->
30 30 <div class="fields">
31 31 <div class="field">
32 32 <div class="label">
33 33 <label for="users_group_name">${_('Group name')}:</label>
34 34 </div>
35 35 <div class="input">
36 36 ${h.text('users_group_name',class_='small')}
37 37 </div>
38 38 </div>
39 39
40 40 <div class="field">
41 41 <div class="label label-checkbox">
42 42 <label for="users_group_active">${_('Active')}:</label>
43 43 </div>
44 44 <div class="checkboxes">
45 45 ${h.checkbox('users_group_active',value=True)}
46 46 </div>
47 47 </div>
48 48 <div class="field">
49 49 <div class="label">
50 50 <label for="users_group_active">${_('Members')}:</label>
51 51 </div>
52 52 <div class="select">
53 53 <table>
54 54 <tr>
55 55 <td>
56 56 <div>
57 57 <div style="float:left">
58 58 <div class="text" style="padding: 0px 0px 6px;">${_('Chosen group members')}</div>
59 59 ${h.select('users_group_members',[x[0] for x in c.group_members],c.group_members,multiple=True,size=8,style="min-width:210px")}
60 <div id="remove_all_elements" style="cursor:pointer;text-align:center">
60 <div id="remove_all_elements" style="cursor:pointer;text-align:center">
61 61 ${_('Remove all elements')}
62 62 <img alt="remove" style="vertical-align:text-bottom" src="${h.url('/images/icons/arrow_right.png')}"/>
63 63 </div>
64 64 </div>
65 65 <div style="float:left;width:20px;padding-top:50px">
66 66 <img alt="add" id="add_element"
67 67 style="padding:2px;cursor:pointer"
68 68 src="${h.url('/images/icons/arrow_left.png')}"/>
69 69 <br />
70 70 <img alt="remove" id="remove_element"
71 71 style="padding:2px;cursor:pointer"
72 72 src="${h.url('/images/icons/arrow_right.png')}"/>
73 73 </div>
74 74 <div style="float:left">
75 75 <div class="text" style="padding: 0px 0px 6px;">${_('Available members')}</div>
76 76 ${h.select('available_members',[],c.available_members,multiple=True,size=8,style="min-width:210px")}
77 77 <div id="add_all_elements" style="cursor:pointer;text-align:center">
78 78 <img alt="add" style="vertical-align:text-bottom" src="${h.url('/images/icons/arrow_left.png')}"/>
79 79 ${_('Add all elements')}
80 80 </div>
81 81 </div>
82 82 </div>
83 83 </td>
84 84 </tr>
85 85 </table>
86 86 </div>
87 87
88 88 </div>
89 89 <div class="buttons">
90 ${h.submit('save',_('save'),class_="ui-btn large")}
90 ${h.submit('Save',_('save'),class_="ui-btn large")}
91 91 </div>
92 92 </div>
93 93 </div>
94 94 ${h.end_form()}
95 95 </div>
96 96
97 97 <div class="box box-right">
98 98 <!-- box / title -->
99 99 <div class="title">
100 100 <h5>${_('Permissions')}</h5>
101 101 </div>
102 102 ${h.form(url('users_group_perm', id=c.users_group.users_group_id), method='put')}
103 103 <div class="form">
104 104 <!-- fields -->
105 105 <div class="fields">
106 106 <div class="field">
107 107 <div class="label label-checkbox">
108 108 <label for="inherit_permissions">${_('Inherit default permissions')}:</label>
109 109 </div>
110 110 <div class="checkboxes">
111 111 ${h.checkbox('inherit_default_permissions',value=True)}
112 112 </div>
113 113 <span class="help-block">${h.literal(_('Select to inherit permissions from %s settings. '
114 114 'With this selected below options does not have any action') % h.link_to('default', url('edit_permission', id='default')))}</span>
115 115 </div>
116 116 <div id="inherit_overlay" style="${'opacity:0.3' if c.users_group.inherit_default_permissions else ''}" >
117 117 <div class="field">
118 118 <div class="label label-checkbox">
119 119 <label for="create_repo_perm">${_('Create repositories')}:</label>
120 120 </div>
121 121 <div class="checkboxes">
122 122 ${h.checkbox('create_repo_perm',value=True)}
123 123 </div>
124 124 </div>
125 125 <div class="field">
126 126 <div class="label label-checkbox">
127 127 <label for="fork_repo_perm">${_('Fork repositories')}:</label>
128 128 </div>
129 129 <div class="checkboxes">
130 130 ${h.checkbox('fork_repo_perm',value=True)}
131 131 </div>
132 132 </div>
133 133 </div>
134 134 <div class="buttons">
135 135 ${h.submit('save',_('Save'),class_="ui-btn large")}
136 136 ${h.reset('reset',_('Reset'),class_="ui-btn large")}
137 137 </div>
138 138 </div>
139 139 </div>
140 140 ${h.end_form()}
141 141 </div>
142 142
143 143 <div class="box box-right">
144 144 <!-- box / title -->
145 145 <div class="title">
146 146 <h5>${_('Group members')}</h5>
147 147 </div>
148 148
149 149 <div class="group_members_wrap">
150 150 % if c.group_members_obj:
151 151 <ul class="group_members">
152 152 %for user in c.group_members_obj:
153 153 <li>
154 154 <div class="group_member">
155 155 <div class="gravatar"><img alt="gravatar" src="${h.gravatar_url(user.email,24)}"/> </div>
156 156 <div>${h.link_to(user.username, h.url('edit_user',id=user.user_id))}</div>
157 157 <div>${user.full_name}</div>
158 158 </div>
159 159 </li>
160 160 %endfor
161 161 </ul>
162 162 %else:
163 163 <span class="empty_data">${_('No members yet')}</span>
164 164 %endif
165 165 </div>
166 166 </div>
167 167
168 168 <div class="box box-left">
169 169 <!-- box / title -->
170 170 <div class="title">
171 171 <h5>${_('Permissions defined for this group')}</h5>
172 172 </div>
173 173 ## permissions overview
174 174 <div id="perms" class="table">
175 175 %for section in sorted(c.users_group.permissions.keys()):
176 176 <div class="perms_section_head">${section.replace("_"," ").capitalize()}</div>
177 177 %if not c.users_group.permissions:
178 178 <span class="empty_data">${_('No permissions set yet')}</span>
179 179 %else:
180 180 <div id='tbl_list_wrap_${section}' class="yui-skin-sam">
181 181 <table id="tbl_list_repository">
182 182 <thead>
183 183 <tr>
184 184 <th class="left">${_('Name')}</th>
185 185 <th class="left">${_('Permission')}</th>
186 186 <th class="left">${_('Edit Permission')}</th>
187 187 </thead>
188 188 <tbody>
189 189 %for k in sorted(c.users_group.permissions[section], key=lambda s: s.lower):
190 190 <%
191 191 section_perm = c.users_group.permissions[section].get(k)
192 192 _perm = section_perm.split('.')[-1]
193 193 %>
194 194 <tr>
195 195 <td>
196 196 %if section == 'repositories':
197 197 <a href="${h.url('summary_home',repo_name=k)}">${k}</a>
198 198 %elif section == 'repositories_groups':
199 199 <a href="${h.url('repos_group_home',group_name=k)}">${k}</a>
200 200 %endif
201 201 </td>
202 202 <td>
203 203 <span class="perm_tag ${_perm}">${section_perm}</span>
204 204 </td>
205 205 <td>
206 206 %if section == 'repositories':
207 207 <a href="${h.url('edit_repo',repo_name=k,anchor='permissions_manage')}">${_('edit')}</a>
208 208 %elif section == 'repositories_groups':
209 209 <a href="${h.url('edit_repos_group',group_name=k,anchor='permissions_manage')}">${_('edit')}</a>
210 210 %else:
211 211 --
212 212 %endif
213 213 </td>
214 214 </tr>
215 215 %endfor
216 216 </tbody>
217 217 </table>
218 218 </div>
219 219 %endif
220 220 %endfor
221 221 </div>
222 222 </div>
223 223
224 224
225 225 <script type="text/javascript">
226 226 MultiSelectWidget('users_group_members','available_members','edit_users_group');
227 227 </script>
228 228 </%def>
General Comments 0
You need to be logged in to leave comments. Login now