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