##// END OF EJS Templates
admin-users: use new json_ext renderer
marcink -
r1665:353a4541 default
parent child Browse files
Show More
@@ -1,306 +1,306 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-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 import datetime
23 23
24 24 from pyramid.httpexceptions import HTTPFound
25 25 from pyramid.view import view_config
26 26 from sqlalchemy.sql.functions import coalesce
27 27
28 28 from rhodecode.lib.helpers import Page
29 29 from rhodecode_tools.lib.ext_json import json
30 30
31 31 from rhodecode.apps._base import BaseAppView, DataGridAppView
32 32 from rhodecode.lib.auth import (
33 33 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
34 34 from rhodecode.lib import helpers as h
35 35 from rhodecode.lib.utils import PartialRenderer
36 36 from rhodecode.lib.utils2 import safe_int, safe_unicode
37 37 from rhodecode.model.auth_token import AuthTokenModel
38 38 from rhodecode.model.user import UserModel
39 39 from rhodecode.model.user_group import UserGroupModel
40 40 from rhodecode.model.db import User, or_
41 41 from rhodecode.model.meta import Session
42 42
43 43 log = logging.getLogger(__name__)
44 44
45 45
46 46 class AdminUsersView(BaseAppView, DataGridAppView):
47 47 ALLOW_SCOPED_TOKENS = False
48 48 """
49 49 This view has alternative version inside EE, if modified please take a look
50 50 in there as well.
51 51 """
52 52
53 53 def load_default_context(self):
54 54 c = self._get_local_tmpl_context()
55 55 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
56 56 self._register_global_c(c)
57 57 return c
58 58
59 59 def _redirect_for_default_user(self, username):
60 60 _ = self.request.translate
61 61 if username == User.DEFAULT_USER:
62 62 h.flash(_("You can't edit this user"), category='warning')
63 63 # TODO(marcink): redirect to 'users' admin panel once this
64 64 # is a pyramid view
65 65 raise HTTPFound('/')
66 66
67 67 @HasPermissionAllDecorator('hg.admin')
68 68 @view_config(
69 69 route_name='users', request_method='GET',
70 70 renderer='rhodecode:templates/admin/users/users.mako')
71 71 def users_list(self):
72 72 c = self.load_default_context()
73 73 return self._get_template_context(c)
74 74
75 75 @HasPermissionAllDecorator('hg.admin')
76 76 @view_config(
77 77 # renderer defined below
78 route_name='users_data', request_method='GET', renderer='json',
79 xhr=True)
78 route_name='users_data', request_method='GET',
79 renderer='json_ext', xhr=True)
80 80 def users_list_data(self):
81 81 draw, start, limit = self._extract_chunk(self.request)
82 82 search_q, order_by, order_dir = self._extract_ordering(self.request)
83 83
84 84 _render = PartialRenderer('data_table/_dt_elements.mako')
85 85
86 86 def user_actions(user_id, username):
87 87 return _render("user_actions", user_id, username)
88 88
89 89 users_data_total_count = User.query()\
90 90 .filter(User.username != User.DEFAULT_USER) \
91 91 .count()
92 92
93 93 # json generate
94 94 base_q = User.query().filter(User.username != User.DEFAULT_USER)
95 95
96 96 if search_q:
97 97 like_expression = u'%{}%'.format(safe_unicode(search_q))
98 98 base_q = base_q.filter(or_(
99 99 User.username.ilike(like_expression),
100 100 User._email.ilike(like_expression),
101 101 User.name.ilike(like_expression),
102 102 User.lastname.ilike(like_expression),
103 103 ))
104 104
105 105 users_data_total_filtered_count = base_q.count()
106 106
107 107 sort_col = getattr(User, order_by, None)
108 108 if sort_col:
109 109 if order_dir == 'asc':
110 110 # handle null values properly to order by NULL last
111 111 if order_by in ['last_activity']:
112 112 sort_col = coalesce(sort_col, datetime.date.max)
113 113 sort_col = sort_col.asc()
114 114 else:
115 115 # handle null values properly to order by NULL last
116 116 if order_by in ['last_activity']:
117 117 sort_col = coalesce(sort_col, datetime.date.min)
118 118 sort_col = sort_col.desc()
119 119
120 120 base_q = base_q.order_by(sort_col)
121 121 base_q = base_q.offset(start).limit(limit)
122 122
123 123 users_list = base_q.all()
124 124
125 125 users_data = []
126 126 for user in users_list:
127 127 users_data.append({
128 128 "username": h.gravatar_with_user(user.username),
129 129 "email": user.email,
130 130 "first_name": h.escape(user.name),
131 131 "last_name": h.escape(user.lastname),
132 132 "last_login": h.format_date(user.last_login),
133 133 "last_activity": h.format_date(user.last_activity),
134 134 "active": h.bool2icon(user.active),
135 135 "active_raw": user.active,
136 136 "admin": h.bool2icon(user.admin),
137 137 "extern_type": user.extern_type,
138 138 "extern_name": user.extern_name,
139 139 "action": user_actions(user.user_id, user.username),
140 140 })
141 141
142 142 data = ({
143 143 'draw': draw,
144 144 'data': users_data,
145 145 'recordsTotal': users_data_total_count,
146 146 'recordsFiltered': users_data_total_filtered_count,
147 147 })
148 148
149 149 return data
150 150
151 151 @LoginRequired()
152 152 @HasPermissionAllDecorator('hg.admin')
153 153 @view_config(
154 154 route_name='edit_user_auth_tokens', request_method='GET',
155 155 renderer='rhodecode:templates/admin/users/user_edit.mako')
156 156 def auth_tokens(self):
157 157 _ = self.request.translate
158 158 c = self.load_default_context()
159 159
160 160 user_id = self.request.matchdict.get('user_id')
161 161 c.user = User.get_or_404(user_id, pyramid_exc=True)
162 162 self._redirect_for_default_user(c.user.username)
163 163
164 164 c.active = 'auth_tokens'
165 165
166 166 c.lifetime_values = [
167 167 (str(-1), _('forever')),
168 168 (str(5), _('5 minutes')),
169 169 (str(60), _('1 hour')),
170 170 (str(60 * 24), _('1 day')),
171 171 (str(60 * 24 * 30), _('1 month')),
172 172 ]
173 173 c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
174 174 c.role_values = [
175 175 (x, AuthTokenModel.cls._get_role_name(x))
176 176 for x in AuthTokenModel.cls.ROLES]
177 177 c.role_options = [(c.role_values, _("Role"))]
178 178 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
179 179 c.user.user_id, show_expired=True)
180 180 return self._get_template_context(c)
181 181
182 182 def maybe_attach_token_scope(self, token):
183 183 # implemented in EE edition
184 184 pass
185 185
186 186 @LoginRequired()
187 187 @HasPermissionAllDecorator('hg.admin')
188 188 @CSRFRequired()
189 189 @view_config(
190 190 route_name='edit_user_auth_tokens_add', request_method='POST')
191 191 def auth_tokens_add(self):
192 192 _ = self.request.translate
193 193 c = self.load_default_context()
194 194
195 195 user_id = self.request.matchdict.get('user_id')
196 196 c.user = User.get_or_404(user_id, pyramid_exc=True)
197 197 self._redirect_for_default_user(c.user.username)
198 198
199 199 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
200 200 description = self.request.POST.get('description')
201 201 role = self.request.POST.get('role')
202 202
203 203 token = AuthTokenModel().create(
204 204 c.user.user_id, description, lifetime, role)
205 205 self.maybe_attach_token_scope(token)
206 206 Session().commit()
207 207
208 208 h.flash(_("Auth token successfully created"), category='success')
209 209 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
210 210
211 211 @LoginRequired()
212 212 @HasPermissionAllDecorator('hg.admin')
213 213 @CSRFRequired()
214 214 @view_config(
215 215 route_name='edit_user_auth_tokens_delete', request_method='POST')
216 216 def auth_tokens_delete(self):
217 217 _ = self.request.translate
218 218 c = self.load_default_context()
219 219
220 220 user_id = self.request.matchdict.get('user_id')
221 221 c.user = User.get_or_404(user_id, pyramid_exc=True)
222 222 self._redirect_for_default_user(c.user.username)
223 223
224 224 del_auth_token = self.request.POST.get('del_auth_token')
225 225
226 226 if del_auth_token:
227 227 AuthTokenModel().delete(del_auth_token, c.user.user_id)
228 228 Session().commit()
229 229 h.flash(_("Auth token successfully deleted"), category='success')
230 230
231 231 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
232 232
233 233 @LoginRequired()
234 234 @HasPermissionAllDecorator('hg.admin')
235 235 @view_config(
236 236 route_name='edit_user_groups_management', request_method='GET',
237 237 renderer='rhodecode:templates/admin/users/user_edit.mako')
238 238 def groups_management(self):
239 239 c = self.load_default_context()
240 240
241 241 user_id = self.request.matchdict.get('user_id')
242 242 c.user = User.get_or_404(user_id, pyramid_exc=True)
243 243 c.data = c.user.group_member
244 244 self._redirect_for_default_user(c.user.username)
245 245 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group) for group in c.user.group_member]
246 246 c.groups = json.dumps(groups)
247 247 c.active = 'groups'
248 248
249 249 return self._get_template_context(c)
250 250
251 251 @LoginRequired()
252 252 @HasPermissionAllDecorator('hg.admin')
253 253 @view_config(
254 254 route_name='edit_user_groups_management_updates', request_method='POST')
255 255 def groups_management_updates(self):
256 256 _ = self.request.translate
257 257 c = self.load_default_context()
258 258
259 259 user_id = self.request.matchdict.get('user_id')
260 260 c.user = User.get_or_404(user_id, pyramid_exc=True)
261 261 self._redirect_for_default_user(c.user.username)
262 262
263 263 users_groups = set(self.request.POST.getall('users_group_id'))
264 264 users_groups_model = []
265 265
266 266 for ugid in users_groups:
267 267 users_groups_model.append(UserGroupModel().get_group(safe_int(ugid)))
268 268 user_group_model = UserGroupModel()
269 269 user_group_model.change_groups(c.user, users_groups_model)
270 270
271 271 Session().commit()
272 272 c.active = 'user_groups_management'
273 273 h.flash(_("Groups successfully changed"), category='success')
274 274
275 275 return HTTPFound(h.route_path(
276 276 'edit_user_groups_management', user_id=user_id))
277 277
278 278 @LoginRequired()
279 279 @HasPermissionAllDecorator('hg.admin')
280 280 @view_config(
281 281 route_name='edit_user_audit_logs', request_method='GET',
282 282 renderer='rhodecode:templates/admin/users/user_edit.mako')
283 283 def user_audit_logs(self):
284 284 _ = self.request.translate
285 285 c = self.load_default_context()
286 286
287 287 user_id = self.request.matchdict.get('user_id')
288 288 c.user = User.get_or_404(user_id, pyramid_exc=True)
289 289 self._redirect_for_default_user(c.user.username)
290 290 c.active = 'audit'
291 291
292 292 p = safe_int(self.request.GET.get('page', 1), 1)
293 293
294 294 filter_term = self.request.GET.get('filter')
295 295 c.user_log = UserModel().get_user_log(c.user, filter_term)
296 296
297 297 def url_generator(**kw):
298 298 if filter_term:
299 299 kw['filter'] = filter_term
300 300 return self.request.current_route_path(_query=kw)
301 301
302 302 c.user_log = Page(c.user_log, page=p, items_per_page=10,
303 303 url=url_generator)
304 304 c.filter_term = filter_term
305 305 return self._get_template_context(c)
306 306
General Comments 0
You need to be logged in to leave comments. Login now