##// END OF EJS Templates
admin-users: use full ilike search on filtering
marcink -
r1521:6db2b5b9 default
parent child Browse files
Show More
@@ -1,240 +1,240 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
23 23 from pyramid.httpexceptions import HTTPFound
24 24 from pyramid.view import view_config
25 25
26 26 from rhodecode.apps._base import BaseAppView
27 27 from rhodecode.lib.auth import (
28 28 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
29 29 from rhodecode.lib import helpers as h
30 30 from rhodecode.lib.utils import PartialRenderer
31 31 from rhodecode.lib.utils2 import safe_int, safe_unicode
32 32 from rhodecode.model.auth_token import AuthTokenModel
33 33 from rhodecode.model.db import User, or_
34 34 from rhodecode.model.meta import Session
35 35
36 36 log = logging.getLogger(__name__)
37 37
38 38
39 39 class AdminUsersView(BaseAppView):
40 40 ALLOW_SCOPED_TOKENS = False
41 41 """
42 42 This view has alternative version inside EE, if modified please take a look
43 43 in there as well.
44 44 """
45 45
46 46 def load_default_context(self):
47 47 c = self._get_local_tmpl_context()
48 48 c.auth_user = self.request.user
49 49 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
50 50 self._register_global_c(c)
51 51 return c
52 52
53 53 def _redirect_for_default_user(self, username):
54 54 _ = self.request.translate
55 55 if username == User.DEFAULT_USER:
56 56 h.flash(_("You can't edit this user"), category='warning')
57 57 # TODO(marcink): redirect to 'users' admin panel once this
58 58 # is a pyramid view
59 59 raise HTTPFound('/')
60 60
61 61 def _extract_ordering(self, request):
62 62 column_index = safe_int(request.GET.get('order[0][column]'))
63 63 order_dir = request.GET.get(
64 64 'order[0][dir]', 'desc')
65 65 order_by = request.GET.get(
66 66 'columns[%s][data][sort]' % column_index, 'name_raw')
67 67
68 68 # translate datatable to DB columns
69 69 order_by = {
70 70 'first_name': 'name',
71 71 'last_name': 'lastname',
72 72 'last_activity': ''
73 73 }.get(order_by) or order_by
74 74
75 75 search_q = request.GET.get('search[value]')
76 76 return search_q, order_by, order_dir
77 77
78 78 def _extract_chunk(self, request):
79 79 start = safe_int(request.GET.get('start'), 0)
80 80 length = safe_int(request.GET.get('length'), 25)
81 81 draw = safe_int(request.GET.get('draw'))
82 82 return draw, start, length
83 83
84 84 @HasPermissionAllDecorator('hg.admin')
85 85 @view_config(
86 86 route_name='users', request_method='GET',
87 87 renderer='rhodecode:templates/admin/users/users.mako')
88 88 def users_list(self):
89 89 c = self.load_default_context()
90 90 return self._get_template_context(c)
91 91
92 92 @HasPermissionAllDecorator('hg.admin')
93 93 @view_config(
94 94 # renderer defined below
95 95 route_name='users_data', request_method='GET', renderer='json',
96 96 xhr=True)
97 97 def users_list_data(self):
98 98 draw, start, limit = self._extract_chunk(self.request)
99 99 search_q, order_by, order_dir = self._extract_ordering(self.request)
100 100
101 101 _render = PartialRenderer('data_table/_dt_elements.mako')
102 102
103 103 def user_actions(user_id, username):
104 104 return _render("user_actions", user_id, username)
105 105
106 106 users_data_total_count = User.query()\
107 107 .filter(User.username != User.DEFAULT_USER) \
108 108 .count()
109 109
110 110 # json generate
111 111 base_q = User.query().filter(User.username != User.DEFAULT_USER)
112 112
113 113 if search_q:
114 like_expression = u'{}%'.format(safe_unicode(search_q))
114 like_expression = u'%{}%'.format(safe_unicode(search_q))
115 115 base_q = base_q.filter(or_(
116 116 User.username.ilike(like_expression),
117 117 User._email.ilike(like_expression),
118 118 User.name.ilike(like_expression),
119 119 User.lastname.ilike(like_expression),
120 120 ))
121 121
122 122 users_data_total_filtered_count = base_q.count()
123 123
124 124 sort_col = getattr(User, order_by, None)
125 125 if sort_col and order_dir == 'asc':
126 126 base_q = base_q.order_by(sort_col.asc())
127 127 elif sort_col:
128 128 base_q = base_q.order_by(sort_col.desc())
129 129
130 130 base_q = base_q.offset(start).limit(limit)
131 131 users_list = base_q.all()
132 132
133 133 users_data = []
134 134 for user in users_list:
135 135 users_data.append({
136 136 "username": h.gravatar_with_user(user.username),
137 137 "email": user.email,
138 138 "first_name": h.escape(user.name),
139 139 "last_name": h.escape(user.lastname),
140 140 "last_login": h.format_date(user.last_login),
141 141 "last_activity": h.format_date(
142 142 h.time_to_datetime(user.user_data.get('last_activity', 0))),
143 143 "active": h.bool2icon(user.active),
144 144 "active_raw": user.active,
145 145 "admin": h.bool2icon(user.admin),
146 146 "extern_type": user.extern_type,
147 147 "extern_name": user.extern_name,
148 148 "action": user_actions(user.user_id, user.username),
149 149 })
150 150
151 151 data = ({
152 152 'draw': draw,
153 153 'data': users_data,
154 154 'recordsTotal': users_data_total_count,
155 155 'recordsFiltered': users_data_total_filtered_count,
156 156 })
157 157
158 158 return data
159 159
160 160 @LoginRequired()
161 161 @HasPermissionAllDecorator('hg.admin')
162 162 @view_config(
163 163 route_name='edit_user_auth_tokens', request_method='GET',
164 164 renderer='rhodecode:templates/admin/users/user_edit.mako')
165 165 def auth_tokens(self):
166 166 _ = self.request.translate
167 167 c = self.load_default_context()
168 168
169 169 user_id = self.request.matchdict.get('user_id')
170 170 c.user = User.get_or_404(user_id, pyramid_exc=True)
171 171 self._redirect_for_default_user(c.user.username)
172 172
173 173 c.active = 'auth_tokens'
174 174
175 175 c.lifetime_values = [
176 176 (str(-1), _('forever')),
177 177 (str(5), _('5 minutes')),
178 178 (str(60), _('1 hour')),
179 179 (str(60 * 24), _('1 day')),
180 180 (str(60 * 24 * 30), _('1 month')),
181 181 ]
182 182 c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
183 183 c.role_values = [
184 184 (x, AuthTokenModel.cls._get_role_name(x))
185 185 for x in AuthTokenModel.cls.ROLES]
186 186 c.role_options = [(c.role_values, _("Role"))]
187 187 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
188 188 c.user.user_id, show_expired=True)
189 189 return self._get_template_context(c)
190 190
191 191 def maybe_attach_token_scope(self, token):
192 192 # implemented in EE edition
193 193 pass
194 194
195 195 @LoginRequired()
196 196 @HasPermissionAllDecorator('hg.admin')
197 197 @CSRFRequired()
198 198 @view_config(
199 199 route_name='edit_user_auth_tokens_add', request_method='POST')
200 200 def auth_tokens_add(self):
201 201 _ = self.request.translate
202 202 c = self.load_default_context()
203 203
204 204 user_id = self.request.matchdict.get('user_id')
205 205 c.user = User.get_or_404(user_id, pyramid_exc=True)
206 206 self._redirect_for_default_user(c.user.username)
207 207
208 208 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
209 209 description = self.request.POST.get('description')
210 210 role = self.request.POST.get('role')
211 211
212 212 token = AuthTokenModel().create(
213 213 c.user.user_id, description, lifetime, role)
214 214 self.maybe_attach_token_scope(token)
215 215 Session().commit()
216 216
217 217 h.flash(_("Auth token successfully created"), category='success')
218 218 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
219 219
220 220 @LoginRequired()
221 221 @HasPermissionAllDecorator('hg.admin')
222 222 @CSRFRequired()
223 223 @view_config(
224 224 route_name='edit_user_auth_tokens_delete', request_method='POST')
225 225 def auth_tokens_delete(self):
226 226 _ = self.request.translate
227 227 c = self.load_default_context()
228 228
229 229 user_id = self.request.matchdict.get('user_id')
230 230 c.user = User.get_or_404(user_id, pyramid_exc=True)
231 231 self._redirect_for_default_user(c.user.username)
232 232
233 233 del_auth_token = self.request.POST.get('del_auth_token')
234 234
235 235 if del_auth_token:
236 236 AuthTokenModel().delete(del_auth_token, c.user.user_id)
237 237 Session().commit()
238 238 h.flash(_("Auth token successfully deleted"), category='success')
239 239
240 240 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
General Comments 0
You need to be logged in to leave comments. Login now