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