##// END OF EJS Templates
user-groups: fix sync flag extraction.
marcink -
r2672:6e24e065 default
parent child Browse files
Show More
@@ -1,245 +1,246 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22
22
23 import formencode
23 import formencode
24 import formencode.htmlfill
24 import formencode.htmlfill
25
25
26 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
27 from pyramid.view import view_config
27 from pyramid.view import view_config
28 from pyramid.response import Response
28 from pyramid.response import Response
29 from pyramid.renderers import render
29 from pyramid.renderers import render
30
30
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 from rhodecode.lib.auth import (
32 from rhodecode.lib.auth import (
33 LoginRequired, NotAnonymous, CSRFRequired, HasPermissionAnyDecorator)
33 LoginRequired, NotAnonymous, CSRFRequired, HasPermissionAnyDecorator)
34 from rhodecode.lib import helpers as h, audit_logger
34 from rhodecode.lib import helpers as h, audit_logger
35 from rhodecode.lib.utils2 import safe_unicode
35 from rhodecode.lib.utils2 import safe_unicode
36
36
37 from rhodecode.model.forms import UserGroupForm
37 from rhodecode.model.forms import UserGroupForm
38 from rhodecode.model.permission import PermissionModel
38 from rhodecode.model.permission import PermissionModel
39 from rhodecode.model.scm import UserGroupList
39 from rhodecode.model.scm import UserGroupList
40 from rhodecode.model.db import (
40 from rhodecode.model.db import (
41 or_, count, User, UserGroup, UserGroupMember)
41 or_, count, User, UserGroup, UserGroupMember)
42 from rhodecode.model.meta import Session
42 from rhodecode.model.meta import Session
43 from rhodecode.model.user_group import UserGroupModel
43 from rhodecode.model.user_group import UserGroupModel
44
44
45 log = logging.getLogger(__name__)
45 log = logging.getLogger(__name__)
46
46
47
47
48 class AdminUserGroupsView(BaseAppView, DataGridAppView):
48 class AdminUserGroupsView(BaseAppView, DataGridAppView):
49
49
50 def load_default_context(self):
50 def load_default_context(self):
51 c = self._get_local_tmpl_context()
51 c = self._get_local_tmpl_context()
52
52
53 PermissionModel().set_global_permission_choices(
53 PermissionModel().set_global_permission_choices(
54 c, gettext_translator=self.request.translate)
54 c, gettext_translator=self.request.translate)
55
55
56 return c
56 return c
57
57
58 # permission check in data loading of
58 # permission check in data loading of
59 # `user_groups_list_data` via UserGroupList
59 # `user_groups_list_data` via UserGroupList
60 @LoginRequired()
60 @LoginRequired()
61 @NotAnonymous()
61 @NotAnonymous()
62 @view_config(
62 @view_config(
63 route_name='user_groups', request_method='GET',
63 route_name='user_groups', request_method='GET',
64 renderer='rhodecode:templates/admin/user_groups/user_groups.mako')
64 renderer='rhodecode:templates/admin/user_groups/user_groups.mako')
65 def user_groups_list(self):
65 def user_groups_list(self):
66 c = self.load_default_context()
66 c = self.load_default_context()
67 return self._get_template_context(c)
67 return self._get_template_context(c)
68
68
69 # permission check inside
69 # permission check inside
70 @LoginRequired()
70 @LoginRequired()
71 @NotAnonymous()
71 @NotAnonymous()
72 @view_config(
72 @view_config(
73 route_name='user_groups_data', request_method='GET',
73 route_name='user_groups_data', request_method='GET',
74 renderer='json_ext', xhr=True)
74 renderer='json_ext', xhr=True)
75 def user_groups_list_data(self):
75 def user_groups_list_data(self):
76 self.load_default_context()
76 self.load_default_context()
77 column_map = {
77 column_map = {
78 'active': 'users_group_active',
78 'active': 'users_group_active',
79 'description': 'user_group_description',
79 'description': 'user_group_description',
80 'members': 'members_total',
80 'members': 'members_total',
81 'owner': 'user_username',
81 'owner': 'user_username',
82 'sync': 'group_data'
82 'sync': 'group_data'
83 }
83 }
84 draw, start, limit = self._extract_chunk(self.request)
84 draw, start, limit = self._extract_chunk(self.request)
85 search_q, order_by, order_dir = self._extract_ordering(
85 search_q, order_by, order_dir = self._extract_ordering(
86 self.request, column_map=column_map)
86 self.request, column_map=column_map)
87
87
88 _render = self.request.get_partial_renderer(
88 _render = self.request.get_partial_renderer(
89 'rhodecode:templates/data_table/_dt_elements.mako')
89 'rhodecode:templates/data_table/_dt_elements.mako')
90
90
91 def user_group_name(user_group_name):
91 def user_group_name(user_group_name):
92 return _render("user_group_name", user_group_name)
92 return _render("user_group_name", user_group_name)
93
93
94 def user_group_actions(user_group_id, user_group_name):
94 def user_group_actions(user_group_id, user_group_name):
95 return _render("user_group_actions", user_group_id, user_group_name)
95 return _render("user_group_actions", user_group_id, user_group_name)
96
96
97 def user_profile(username):
97 def user_profile(username):
98 return _render('user_profile', username)
98 return _render('user_profile', username)
99
99
100 auth_user_group_list = UserGroupList(
100 auth_user_group_list = UserGroupList(
101 UserGroup.query().all(), perm_set=['usergroup.admin'])
101 UserGroup.query().all(), perm_set=['usergroup.admin'])
102
102
103 allowed_ids = [-1]
103 allowed_ids = [-1]
104 for user_group in auth_user_group_list:
104 for user_group in auth_user_group_list:
105 allowed_ids.append(user_group.users_group_id)
105 allowed_ids.append(user_group.users_group_id)
106
106
107 user_groups_data_total_count = UserGroup.query()\
107 user_groups_data_total_count = UserGroup.query()\
108 .filter(UserGroup.users_group_id.in_(allowed_ids))\
108 .filter(UserGroup.users_group_id.in_(allowed_ids))\
109 .count()
109 .count()
110
110
111 member_count = count(UserGroupMember.user_id)
111 member_count = count(UserGroupMember.user_id)
112 base_q = Session.query(
112 base_q = Session.query(
113 UserGroup.users_group_name,
113 UserGroup.users_group_name,
114 UserGroup.user_group_description,
114 UserGroup.user_group_description,
115 UserGroup.users_group_active,
115 UserGroup.users_group_active,
116 UserGroup.users_group_id,
116 UserGroup.users_group_id,
117 UserGroup.group_data,
117 UserGroup.group_data,
118 User,
118 User,
119 member_count.label('member_count')
119 member_count.label('member_count')
120 ) \
120 ) \
121 .filter(UserGroup.users_group_id.in_(allowed_ids)) \
121 .filter(UserGroup.users_group_id.in_(allowed_ids)) \
122 .outerjoin(UserGroupMember) \
122 .outerjoin(UserGroupMember) \
123 .join(User, User.user_id == UserGroup.user_id) \
123 .join(User, User.user_id == UserGroup.user_id) \
124 .group_by(UserGroup, User)
124 .group_by(UserGroup, User)
125
125
126 if search_q:
126 if search_q:
127 like_expression = u'%{}%'.format(safe_unicode(search_q))
127 like_expression = u'%{}%'.format(safe_unicode(search_q))
128 base_q = base_q.filter(or_(
128 base_q = base_q.filter(or_(
129 UserGroup.users_group_name.ilike(like_expression),
129 UserGroup.users_group_name.ilike(like_expression),
130 ))
130 ))
131
131
132 user_groups_data_total_filtered_count = base_q.count()
132 user_groups_data_total_filtered_count = base_q.count()
133
133
134 if order_by == 'members_total':
134 if order_by == 'members_total':
135 sort_col = member_count
135 sort_col = member_count
136 elif order_by == 'user_username':
136 elif order_by == 'user_username':
137 sort_col = User.username
137 sort_col = User.username
138 else:
138 else:
139 sort_col = getattr(UserGroup, order_by, None)
139 sort_col = getattr(UserGroup, order_by, None)
140
140
141 if isinstance(sort_col, count) or sort_col:
141 if isinstance(sort_col, count) or sort_col:
142 if order_dir == 'asc':
142 if order_dir == 'asc':
143 sort_col = sort_col.asc()
143 sort_col = sort_col.asc()
144 else:
144 else:
145 sort_col = sort_col.desc()
145 sort_col = sort_col.desc()
146
146
147 base_q = base_q.order_by(sort_col)
147 base_q = base_q.order_by(sort_col)
148 base_q = base_q.offset(start).limit(limit)
148 base_q = base_q.offset(start).limit(limit)
149
149
150 # authenticated access to user groups
150 # authenticated access to user groups
151 auth_user_group_list = base_q.all()
151 auth_user_group_list = base_q.all()
152
152
153 user_groups_data = []
153 user_groups_data = []
154 for user_gr in auth_user_group_list:
154 for user_gr in auth_user_group_list:
155 user_groups_data.append({
155 user_groups_data.append({
156 "users_group_name": user_group_name(user_gr.users_group_name),
156 "users_group_name": user_group_name(user_gr.users_group_name),
157 "name_raw": h.escape(user_gr.users_group_name),
157 "name_raw": h.escape(user_gr.users_group_name),
158 "description": h.escape(user_gr.user_group_description),
158 "description": h.escape(user_gr.user_group_description),
159 "members": user_gr.member_count,
159 "members": user_gr.member_count,
160 # NOTE(marcink): because of advanced query we
160 # NOTE(marcink): because of advanced query we
161 # need to load it like that
161 # need to load it like that
162 "sync": UserGroup._load_sync(user_gr.group_data),
162 "sync": UserGroup._load_sync(
163 UserGroup._load_group_data(user_gr.group_data)),
163 "active": h.bool2icon(user_gr.users_group_active),
164 "active": h.bool2icon(user_gr.users_group_active),
164 "owner": user_profile(user_gr.User.username),
165 "owner": user_profile(user_gr.User.username),
165 "action": user_group_actions(
166 "action": user_group_actions(
166 user_gr.users_group_id, user_gr.users_group_name)
167 user_gr.users_group_id, user_gr.users_group_name)
167 })
168 })
168
169
169 data = ({
170 data = ({
170 'draw': draw,
171 'draw': draw,
171 'data': user_groups_data,
172 'data': user_groups_data,
172 'recordsTotal': user_groups_data_total_count,
173 'recordsTotal': user_groups_data_total_count,
173 'recordsFiltered': user_groups_data_total_filtered_count,
174 'recordsFiltered': user_groups_data_total_filtered_count,
174 })
175 })
175
176
176 return data
177 return data
177
178
178 @LoginRequired()
179 @LoginRequired()
179 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
180 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
180 @view_config(
181 @view_config(
181 route_name='user_groups_new', request_method='GET',
182 route_name='user_groups_new', request_method='GET',
182 renderer='rhodecode:templates/admin/user_groups/user_group_add.mako')
183 renderer='rhodecode:templates/admin/user_groups/user_group_add.mako')
183 def user_groups_new(self):
184 def user_groups_new(self):
184 c = self.load_default_context()
185 c = self.load_default_context()
185 return self._get_template_context(c)
186 return self._get_template_context(c)
186
187
187 @LoginRequired()
188 @LoginRequired()
188 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
189 @HasPermissionAnyDecorator('hg.admin', 'hg.usergroup.create.true')
189 @CSRFRequired()
190 @CSRFRequired()
190 @view_config(
191 @view_config(
191 route_name='user_groups_create', request_method='POST',
192 route_name='user_groups_create', request_method='POST',
192 renderer='rhodecode:templates/admin/user_groups/user_group_add.mako')
193 renderer='rhodecode:templates/admin/user_groups/user_group_add.mako')
193 def user_groups_create(self):
194 def user_groups_create(self):
194 _ = self.request.translate
195 _ = self.request.translate
195 c = self.load_default_context()
196 c = self.load_default_context()
196 users_group_form = UserGroupForm(self.request.translate)()
197 users_group_form = UserGroupForm(self.request.translate)()
197
198
198 user_group_name = self.request.POST.get('users_group_name')
199 user_group_name = self.request.POST.get('users_group_name')
199 try:
200 try:
200 form_result = users_group_form.to_python(dict(self.request.POST))
201 form_result = users_group_form.to_python(dict(self.request.POST))
201 user_group = UserGroupModel().create(
202 user_group = UserGroupModel().create(
202 name=form_result['users_group_name'],
203 name=form_result['users_group_name'],
203 description=form_result['user_group_description'],
204 description=form_result['user_group_description'],
204 owner=self._rhodecode_user.user_id,
205 owner=self._rhodecode_user.user_id,
205 active=form_result['users_group_active'])
206 active=form_result['users_group_active'])
206 Session().flush()
207 Session().flush()
207 creation_data = user_group.get_api_data()
208 creation_data = user_group.get_api_data()
208 user_group_name = form_result['users_group_name']
209 user_group_name = form_result['users_group_name']
209
210
210 audit_logger.store_web(
211 audit_logger.store_web(
211 'user_group.create', action_data={'data': creation_data},
212 'user_group.create', action_data={'data': creation_data},
212 user=self._rhodecode_user)
213 user=self._rhodecode_user)
213
214
214 user_group_link = h.link_to(
215 user_group_link = h.link_to(
215 h.escape(user_group_name),
216 h.escape(user_group_name),
216 h.route_path(
217 h.route_path(
217 'edit_user_group', user_group_id=user_group.users_group_id))
218 'edit_user_group', user_group_id=user_group.users_group_id))
218 h.flash(h.literal(_('Created user group %(user_group_link)s')
219 h.flash(h.literal(_('Created user group %(user_group_link)s')
219 % {'user_group_link': user_group_link}),
220 % {'user_group_link': user_group_link}),
220 category='success')
221 category='success')
221 Session().commit()
222 Session().commit()
222 user_group_id = user_group.users_group_id
223 user_group_id = user_group.users_group_id
223 except formencode.Invalid as errors:
224 except formencode.Invalid as errors:
224
225
225 data = render(
226 data = render(
226 'rhodecode:templates/admin/user_groups/user_group_add.mako',
227 'rhodecode:templates/admin/user_groups/user_group_add.mako',
227 self._get_template_context(c), self.request)
228 self._get_template_context(c), self.request)
228 html = formencode.htmlfill.render(
229 html = formencode.htmlfill.render(
229 data,
230 data,
230 defaults=errors.value,
231 defaults=errors.value,
231 errors=errors.error_dict or {},
232 errors=errors.error_dict or {},
232 prefix_error=False,
233 prefix_error=False,
233 encoding="UTF-8",
234 encoding="UTF-8",
234 force_defaults=False
235 force_defaults=False
235 )
236 )
236 return Response(html)
237 return Response(html)
237
238
238 except Exception:
239 except Exception:
239 log.exception("Exception creating user group")
240 log.exception("Exception creating user group")
240 h.flash(_('Error occurred during creation of user group %s') \
241 h.flash(_('Error occurred during creation of user group %s') \
241 % user_group_name, category='error')
242 % user_group_name, category='error')
242 raise HTTPFound(h.route_path('user_groups_new'))
243 raise HTTPFound(h.route_path('user_groups_new'))
243
244
244 raise HTTPFound(
245 raise HTTPFound(
245 h.route_path('edit_user_group', user_group_id=user_group_id))
246 h.route_path('edit_user_group', user_group_id=user_group_id))
General Comments 0
You need to be logged in to leave comments. Login now