##// END OF EJS Templates
settings: use cached settings in few places we only often use it for reading.
marcink -
r260:3c0e100a default
parent child Browse files
Show More
@@ -1,551 +1,551 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 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 """
21 """
22 The base Controller API
22 The base Controller API
23 Provides the BaseController class for subclassing. And usage in different
23 Provides the BaseController class for subclassing. And usage in different
24 controllers
24 controllers
25 """
25 """
26
26
27 import logging
27 import logging
28 import socket
28 import socket
29
29
30 import ipaddress
30 import ipaddress
31
31
32 from paste.auth.basic import AuthBasicAuthenticator
32 from paste.auth.basic import AuthBasicAuthenticator
33 from paste.httpexceptions import HTTPUnauthorized, HTTPForbidden, get_exception
33 from paste.httpexceptions import HTTPUnauthorized, HTTPForbidden, get_exception
34 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
34 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
35 from pylons import config, tmpl_context as c, request, session, url
35 from pylons import config, tmpl_context as c, request, session, url
36 from pylons.controllers import WSGIController
36 from pylons.controllers import WSGIController
37 from pylons.controllers.util import redirect
37 from pylons.controllers.util import redirect
38 from pylons.i18n import translation
38 from pylons.i18n import translation
39 # marcink: don't remove this import
39 # marcink: don't remove this import
40 from pylons.templating import render_mako as render # noqa
40 from pylons.templating import render_mako as render # noqa
41 from pylons.i18n.translation import _
41 from pylons.i18n.translation import _
42 from webob.exc import HTTPFound
42 from webob.exc import HTTPFound
43
43
44
44
45 import rhodecode
45 import rhodecode
46 from rhodecode.authentication.base import VCS_TYPE
46 from rhodecode.authentication.base import VCS_TYPE
47 from rhodecode.lib import auth, utils2
47 from rhodecode.lib import auth, utils2
48 from rhodecode.lib import helpers as h
48 from rhodecode.lib import helpers as h
49 from rhodecode.lib.auth import AuthUser, CookieStoreWrapper
49 from rhodecode.lib.auth import AuthUser, CookieStoreWrapper
50 from rhodecode.lib.exceptions import UserCreationError
50 from rhodecode.lib.exceptions import UserCreationError
51 from rhodecode.lib.utils import (
51 from rhodecode.lib.utils import (
52 get_repo_slug, set_rhodecode_config, password_changed,
52 get_repo_slug, set_rhodecode_config, password_changed,
53 get_enabled_hook_classes)
53 get_enabled_hook_classes)
54 from rhodecode.lib.utils2 import (
54 from rhodecode.lib.utils2 import (
55 str2bool, safe_unicode, AttributeDict, safe_int, md5, aslist)
55 str2bool, safe_unicode, AttributeDict, safe_int, md5, aslist)
56 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
56 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
57 from rhodecode.model import meta
57 from rhodecode.model import meta
58 from rhodecode.model.db import Repository, User
58 from rhodecode.model.db import Repository, User
59 from rhodecode.model.notification import NotificationModel
59 from rhodecode.model.notification import NotificationModel
60 from rhodecode.model.scm import ScmModel
60 from rhodecode.model.scm import ScmModel
61 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
61 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
62
62
63
63
64 log = logging.getLogger(__name__)
64 log = logging.getLogger(__name__)
65
65
66
66
67 def _filter_proxy(ip):
67 def _filter_proxy(ip):
68 """
68 """
69 Passed in IP addresses in HEADERS can be in a special format of multiple
69 Passed in IP addresses in HEADERS can be in a special format of multiple
70 ips. Those comma separated IPs are passed from various proxies in the
70 ips. Those comma separated IPs are passed from various proxies in the
71 chain of request processing. The left-most being the original client.
71 chain of request processing. The left-most being the original client.
72 We only care about the first IP which came from the org. client.
72 We only care about the first IP which came from the org. client.
73
73
74 :param ip: ip string from headers
74 :param ip: ip string from headers
75 """
75 """
76 if ',' in ip:
76 if ',' in ip:
77 _ips = ip.split(',')
77 _ips = ip.split(',')
78 _first_ip = _ips[0].strip()
78 _first_ip = _ips[0].strip()
79 log.debug('Got multiple IPs %s, using %s', ','.join(_ips), _first_ip)
79 log.debug('Got multiple IPs %s, using %s', ','.join(_ips), _first_ip)
80 return _first_ip
80 return _first_ip
81 return ip
81 return ip
82
82
83
83
84 def _filter_port(ip):
84 def _filter_port(ip):
85 """
85 """
86 Removes a port from ip, there are 4 main cases to handle here.
86 Removes a port from ip, there are 4 main cases to handle here.
87 - ipv4 eg. 127.0.0.1
87 - ipv4 eg. 127.0.0.1
88 - ipv6 eg. ::1
88 - ipv6 eg. ::1
89 - ipv4+port eg. 127.0.0.1:8080
89 - ipv4+port eg. 127.0.0.1:8080
90 - ipv6+port eg. [::1]:8080
90 - ipv6+port eg. [::1]:8080
91
91
92 :param ip:
92 :param ip:
93 """
93 """
94 def is_ipv6(ip_addr):
94 def is_ipv6(ip_addr):
95 if hasattr(socket, 'inet_pton'):
95 if hasattr(socket, 'inet_pton'):
96 try:
96 try:
97 socket.inet_pton(socket.AF_INET6, ip_addr)
97 socket.inet_pton(socket.AF_INET6, ip_addr)
98 except socket.error:
98 except socket.error:
99 return False
99 return False
100 else:
100 else:
101 # fallback to ipaddress
101 # fallback to ipaddress
102 try:
102 try:
103 ipaddress.IPv6Address(ip_addr)
103 ipaddress.IPv6Address(ip_addr)
104 except Exception:
104 except Exception:
105 return False
105 return False
106 return True
106 return True
107
107
108 if ':' not in ip: # must be ipv4 pure ip
108 if ':' not in ip: # must be ipv4 pure ip
109 return ip
109 return ip
110
110
111 if '[' in ip and ']' in ip: # ipv6 with port
111 if '[' in ip and ']' in ip: # ipv6 with port
112 return ip.split(']')[0][1:].lower()
112 return ip.split(']')[0][1:].lower()
113
113
114 # must be ipv6 or ipv4 with port
114 # must be ipv6 or ipv4 with port
115 if is_ipv6(ip):
115 if is_ipv6(ip):
116 return ip
116 return ip
117 else:
117 else:
118 ip, _port = ip.split(':')[:2] # means ipv4+port
118 ip, _port = ip.split(':')[:2] # means ipv4+port
119 return ip
119 return ip
120
120
121
121
122 def get_ip_addr(environ):
122 def get_ip_addr(environ):
123 proxy_key = 'HTTP_X_REAL_IP'
123 proxy_key = 'HTTP_X_REAL_IP'
124 proxy_key2 = 'HTTP_X_FORWARDED_FOR'
124 proxy_key2 = 'HTTP_X_FORWARDED_FOR'
125 def_key = 'REMOTE_ADDR'
125 def_key = 'REMOTE_ADDR'
126 _filters = lambda x: _filter_port(_filter_proxy(x))
126 _filters = lambda x: _filter_port(_filter_proxy(x))
127
127
128 ip = environ.get(proxy_key)
128 ip = environ.get(proxy_key)
129 if ip:
129 if ip:
130 return _filters(ip)
130 return _filters(ip)
131
131
132 ip = environ.get(proxy_key2)
132 ip = environ.get(proxy_key2)
133 if ip:
133 if ip:
134 return _filters(ip)
134 return _filters(ip)
135
135
136 ip = environ.get(def_key, '0.0.0.0')
136 ip = environ.get(def_key, '0.0.0.0')
137 return _filters(ip)
137 return _filters(ip)
138
138
139
139
140 def get_server_ip_addr(environ, log_errors=True):
140 def get_server_ip_addr(environ, log_errors=True):
141 hostname = environ.get('SERVER_NAME')
141 hostname = environ.get('SERVER_NAME')
142 try:
142 try:
143 return socket.gethostbyname(hostname)
143 return socket.gethostbyname(hostname)
144 except Exception as e:
144 except Exception as e:
145 if log_errors:
145 if log_errors:
146 # in some cases this lookup is not possible, and we don't want to
146 # in some cases this lookup is not possible, and we don't want to
147 # make it an exception in logs
147 # make it an exception in logs
148 log.exception('Could not retrieve server ip address: %s', e)
148 log.exception('Could not retrieve server ip address: %s', e)
149 return hostname
149 return hostname
150
150
151
151
152 def get_server_port(environ):
152 def get_server_port(environ):
153 return environ.get('SERVER_PORT')
153 return environ.get('SERVER_PORT')
154
154
155
155
156 def get_access_path(environ):
156 def get_access_path(environ):
157 path = environ.get('PATH_INFO')
157 path = environ.get('PATH_INFO')
158 org_req = environ.get('pylons.original_request')
158 org_req = environ.get('pylons.original_request')
159 if org_req:
159 if org_req:
160 path = org_req.environ.get('PATH_INFO')
160 path = org_req.environ.get('PATH_INFO')
161 return path
161 return path
162
162
163
163
164 def vcs_operation_context(
164 def vcs_operation_context(
165 environ, repo_name, username, action, scm, check_locking=True):
165 environ, repo_name, username, action, scm, check_locking=True):
166 """
166 """
167 Generate the context for a vcs operation, e.g. push or pull.
167 Generate the context for a vcs operation, e.g. push or pull.
168
168
169 This context is passed over the layers so that hooks triggered by the
169 This context is passed over the layers so that hooks triggered by the
170 vcs operation know details like the user, the user's IP address etc.
170 vcs operation know details like the user, the user's IP address etc.
171
171
172 :param check_locking: Allows to switch of the computation of the locking
172 :param check_locking: Allows to switch of the computation of the locking
173 data. This serves mainly the need of the simplevcs middleware to be
173 data. This serves mainly the need of the simplevcs middleware to be
174 able to disable this for certain operations.
174 able to disable this for certain operations.
175
175
176 """
176 """
177 # Tri-state value: False: unlock, None: nothing, True: lock
177 # Tri-state value: False: unlock, None: nothing, True: lock
178 make_lock = None
178 make_lock = None
179 locked_by = [None, None, None]
179 locked_by = [None, None, None]
180 is_anonymous = username == User.DEFAULT_USER
180 is_anonymous = username == User.DEFAULT_USER
181 if not is_anonymous and check_locking:
181 if not is_anonymous and check_locking:
182 log.debug('Checking locking on repository "%s"', repo_name)
182 log.debug('Checking locking on repository "%s"', repo_name)
183 user = User.get_by_username(username)
183 user = User.get_by_username(username)
184 repo = Repository.get_by_repo_name(repo_name)
184 repo = Repository.get_by_repo_name(repo_name)
185 make_lock, __, locked_by = repo.get_locking_state(
185 make_lock, __, locked_by = repo.get_locking_state(
186 action, user.user_id)
186 action, user.user_id)
187
187
188 settings_model = VcsSettingsModel(repo=repo_name)
188 settings_model = VcsSettingsModel(repo=repo_name)
189 ui_settings = settings_model.get_ui_settings()
189 ui_settings = settings_model.get_ui_settings()
190
190
191 extras = {
191 extras = {
192 'ip': get_ip_addr(environ),
192 'ip': get_ip_addr(environ),
193 'username': username,
193 'username': username,
194 'action': action,
194 'action': action,
195 'repository': repo_name,
195 'repository': repo_name,
196 'scm': scm,
196 'scm': scm,
197 'config': rhodecode.CONFIG['__file__'],
197 'config': rhodecode.CONFIG['__file__'],
198 'make_lock': make_lock,
198 'make_lock': make_lock,
199 'locked_by': locked_by,
199 'locked_by': locked_by,
200 'server_url': utils2.get_server_url(environ),
200 'server_url': utils2.get_server_url(environ),
201 'hooks': get_enabled_hook_classes(ui_settings),
201 'hooks': get_enabled_hook_classes(ui_settings),
202 }
202 }
203 return extras
203 return extras
204
204
205
205
206 class BasicAuth(AuthBasicAuthenticator):
206 class BasicAuth(AuthBasicAuthenticator):
207
207
208 def __init__(self, realm, authfunc, auth_http_code=None,
208 def __init__(self, realm, authfunc, auth_http_code=None,
209 initial_call_detection=False):
209 initial_call_detection=False):
210 self.realm = realm
210 self.realm = realm
211 self.initial_call = initial_call_detection
211 self.initial_call = initial_call_detection
212 self.authfunc = authfunc
212 self.authfunc = authfunc
213 self._rc_auth_http_code = auth_http_code
213 self._rc_auth_http_code = auth_http_code
214
214
215 def _get_response_from_code(self, http_code):
215 def _get_response_from_code(self, http_code):
216 try:
216 try:
217 return get_exception(safe_int(http_code))
217 return get_exception(safe_int(http_code))
218 except Exception:
218 except Exception:
219 log.exception('Failed to fetch response for code %s' % http_code)
219 log.exception('Failed to fetch response for code %s' % http_code)
220 return HTTPForbidden
220 return HTTPForbidden
221
221
222 def build_authentication(self):
222 def build_authentication(self):
223 head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
223 head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
224 if self._rc_auth_http_code and not self.initial_call:
224 if self._rc_auth_http_code and not self.initial_call:
225 # return alternative HTTP code if alternative http return code
225 # return alternative HTTP code if alternative http return code
226 # is specified in RhodeCode config, but ONLY if it's not the
226 # is specified in RhodeCode config, but ONLY if it's not the
227 # FIRST call
227 # FIRST call
228 custom_response_klass = self._get_response_from_code(
228 custom_response_klass = self._get_response_from_code(
229 self._rc_auth_http_code)
229 self._rc_auth_http_code)
230 return custom_response_klass(headers=head)
230 return custom_response_klass(headers=head)
231 return HTTPUnauthorized(headers=head)
231 return HTTPUnauthorized(headers=head)
232
232
233 def authenticate(self, environ):
233 def authenticate(self, environ):
234 authorization = AUTHORIZATION(environ)
234 authorization = AUTHORIZATION(environ)
235 if not authorization:
235 if not authorization:
236 return self.build_authentication()
236 return self.build_authentication()
237 (authmeth, auth) = authorization.split(' ', 1)
237 (authmeth, auth) = authorization.split(' ', 1)
238 if 'basic' != authmeth.lower():
238 if 'basic' != authmeth.lower():
239 return self.build_authentication()
239 return self.build_authentication()
240 auth = auth.strip().decode('base64')
240 auth = auth.strip().decode('base64')
241 _parts = auth.split(':', 1)
241 _parts = auth.split(':', 1)
242 if len(_parts) == 2:
242 if len(_parts) == 2:
243 username, password = _parts
243 username, password = _parts
244 if self.authfunc(
244 if self.authfunc(
245 username, password, environ, VCS_TYPE):
245 username, password, environ, VCS_TYPE):
246 return username
246 return username
247 if username and password:
247 if username and password:
248 # we mark that we actually executed authentication once, at
248 # we mark that we actually executed authentication once, at
249 # that point we can use the alternative auth code
249 # that point we can use the alternative auth code
250 self.initial_call = False
250 self.initial_call = False
251
251
252 return self.build_authentication()
252 return self.build_authentication()
253
253
254 __call__ = authenticate
254 __call__ = authenticate
255
255
256
256
257 def attach_context_attributes(context):
257 def attach_context_attributes(context):
258 rc_config = SettingsModel().get_all_settings()
258 rc_config = SettingsModel().get_all_settings(cache=True)
259
259
260 context.rhodecode_version = rhodecode.__version__
260 context.rhodecode_version = rhodecode.__version__
261 context.rhodecode_edition = config.get('rhodecode.edition')
261 context.rhodecode_edition = config.get('rhodecode.edition')
262 # unique secret + version does not leak the version but keep consistency
262 # unique secret + version does not leak the version but keep consistency
263 context.rhodecode_version_hash = md5(
263 context.rhodecode_version_hash = md5(
264 config.get('beaker.session.secret', '') +
264 config.get('beaker.session.secret', '') +
265 rhodecode.__version__)[:8]
265 rhodecode.__version__)[:8]
266
266
267 # Default language set for the incoming request
267 # Default language set for the incoming request
268 context.language = translation.get_lang()[0]
268 context.language = translation.get_lang()[0]
269
269
270 # Visual options
270 # Visual options
271 context.visual = AttributeDict({})
271 context.visual = AttributeDict({})
272
272
273 # DB store
273 # DB store
274 context.visual.show_public_icon = str2bool(
274 context.visual.show_public_icon = str2bool(
275 rc_config.get('rhodecode_show_public_icon'))
275 rc_config.get('rhodecode_show_public_icon'))
276 context.visual.show_private_icon = str2bool(
276 context.visual.show_private_icon = str2bool(
277 rc_config.get('rhodecode_show_private_icon'))
277 rc_config.get('rhodecode_show_private_icon'))
278 context.visual.stylify_metatags = str2bool(
278 context.visual.stylify_metatags = str2bool(
279 rc_config.get('rhodecode_stylify_metatags'))
279 rc_config.get('rhodecode_stylify_metatags'))
280 context.visual.dashboard_items = safe_int(
280 context.visual.dashboard_items = safe_int(
281 rc_config.get('rhodecode_dashboard_items', 100))
281 rc_config.get('rhodecode_dashboard_items', 100))
282 context.visual.admin_grid_items = safe_int(
282 context.visual.admin_grid_items = safe_int(
283 rc_config.get('rhodecode_admin_grid_items', 100))
283 rc_config.get('rhodecode_admin_grid_items', 100))
284 context.visual.repository_fields = str2bool(
284 context.visual.repository_fields = str2bool(
285 rc_config.get('rhodecode_repository_fields'))
285 rc_config.get('rhodecode_repository_fields'))
286 context.visual.show_version = str2bool(
286 context.visual.show_version = str2bool(
287 rc_config.get('rhodecode_show_version'))
287 rc_config.get('rhodecode_show_version'))
288 context.visual.use_gravatar = str2bool(
288 context.visual.use_gravatar = str2bool(
289 rc_config.get('rhodecode_use_gravatar'))
289 rc_config.get('rhodecode_use_gravatar'))
290 context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
290 context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
291 context.visual.default_renderer = rc_config.get(
291 context.visual.default_renderer = rc_config.get(
292 'rhodecode_markup_renderer', 'rst')
292 'rhodecode_markup_renderer', 'rst')
293 context.visual.rhodecode_support_url = \
293 context.visual.rhodecode_support_url = \
294 rc_config.get('rhodecode_support_url') or url('rhodecode_support')
294 rc_config.get('rhodecode_support_url') or url('rhodecode_support')
295
295
296 context.pre_code = rc_config.get('rhodecode_pre_code')
296 context.pre_code = rc_config.get('rhodecode_pre_code')
297 context.post_code = rc_config.get('rhodecode_post_code')
297 context.post_code = rc_config.get('rhodecode_post_code')
298 context.rhodecode_name = rc_config.get('rhodecode_title')
298 context.rhodecode_name = rc_config.get('rhodecode_title')
299 context.default_encodings = aslist(config.get('default_encoding'), sep=',')
299 context.default_encodings = aslist(config.get('default_encoding'), sep=',')
300 # if we have specified default_encoding in the request, it has more
300 # if we have specified default_encoding in the request, it has more
301 # priority
301 # priority
302 if request.GET.get('default_encoding'):
302 if request.GET.get('default_encoding'):
303 context.default_encodings.insert(0, request.GET.get('default_encoding'))
303 context.default_encodings.insert(0, request.GET.get('default_encoding'))
304 context.clone_uri_tmpl = rc_config.get('rhodecode_clone_uri_tmpl')
304 context.clone_uri_tmpl = rc_config.get('rhodecode_clone_uri_tmpl')
305
305
306 # INI stored
306 # INI stored
307 context.labs_active = str2bool(
307 context.labs_active = str2bool(
308 config.get('labs_settings_active', 'false'))
308 config.get('labs_settings_active', 'false'))
309 context.visual.allow_repo_location_change = str2bool(
309 context.visual.allow_repo_location_change = str2bool(
310 config.get('allow_repo_location_change', True))
310 config.get('allow_repo_location_change', True))
311 context.visual.allow_custom_hooks_settings = str2bool(
311 context.visual.allow_custom_hooks_settings = str2bool(
312 config.get('allow_custom_hooks_settings', True))
312 config.get('allow_custom_hooks_settings', True))
313 context.debug_style = str2bool(config.get('debug_style', False))
313 context.debug_style = str2bool(config.get('debug_style', False))
314
314
315 context.rhodecode_instanceid = config.get('instance_id')
315 context.rhodecode_instanceid = config.get('instance_id')
316
316
317 # AppEnlight
317 # AppEnlight
318 context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
318 context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
319 context.appenlight_api_public_key = config.get(
319 context.appenlight_api_public_key = config.get(
320 'appenlight.api_public_key', '')
320 'appenlight.api_public_key', '')
321 context.appenlight_server_url = config.get('appenlight.server_url', '')
321 context.appenlight_server_url = config.get('appenlight.server_url', '')
322
322
323 # END CONFIG VARS
323 # END CONFIG VARS
324
324
325 # TODO: This dosn't work when called from pylons compatibility tween.
325 # TODO: This dosn't work when called from pylons compatibility tween.
326 # Fix this and remove it from base controller.
326 # Fix this and remove it from base controller.
327 # context.repo_name = get_repo_slug(request) # can be empty
327 # context.repo_name = get_repo_slug(request) # can be empty
328
328
329 context.csrf_token = auth.get_csrf_token()
329 context.csrf_token = auth.get_csrf_token()
330 context.backends = rhodecode.BACKENDS.keys()
330 context.backends = rhodecode.BACKENDS.keys()
331 context.backends.sort()
331 context.backends.sort()
332 context.unread_notifications = NotificationModel().get_unread_cnt_for_user(
332 context.unread_notifications = NotificationModel().get_unread_cnt_for_user(
333 context.rhodecode_user.user_id)
333 context.rhodecode_user.user_id)
334
334
335
335
336 def get_auth_user(environ):
336 def get_auth_user(environ):
337 ip_addr = get_ip_addr(environ)
337 ip_addr = get_ip_addr(environ)
338 # make sure that we update permissions each time we call controller
338 # make sure that we update permissions each time we call controller
339 _auth_token = (request.GET.get('auth_token', '') or
339 _auth_token = (request.GET.get('auth_token', '') or
340 request.GET.get('api_key', ''))
340 request.GET.get('api_key', ''))
341
341
342 if _auth_token:
342 if _auth_token:
343 # when using API_KEY we are sure user exists.
343 # when using API_KEY we are sure user exists.
344 auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr)
344 auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr)
345 authenticated = False
345 authenticated = False
346 else:
346 else:
347 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
347 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
348 try:
348 try:
349 auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
349 auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
350 ip_addr=ip_addr)
350 ip_addr=ip_addr)
351 except UserCreationError as e:
351 except UserCreationError as e:
352 h.flash(e, 'error')
352 h.flash(e, 'error')
353 # container auth or other auth functions that create users
353 # container auth or other auth functions that create users
354 # on the fly can throw this exception signaling that there's
354 # on the fly can throw this exception signaling that there's
355 # issue with user creation, explanation should be provided
355 # issue with user creation, explanation should be provided
356 # in Exception itself. We then create a simple blank
356 # in Exception itself. We then create a simple blank
357 # AuthUser
357 # AuthUser
358 auth_user = AuthUser(ip_addr=ip_addr)
358 auth_user = AuthUser(ip_addr=ip_addr)
359
359
360 if password_changed(auth_user, session):
360 if password_changed(auth_user, session):
361 session.invalidate()
361 session.invalidate()
362 cookie_store = CookieStoreWrapper(
362 cookie_store = CookieStoreWrapper(
363 session.get('rhodecode_user'))
363 session.get('rhodecode_user'))
364 auth_user = AuthUser(ip_addr=ip_addr)
364 auth_user = AuthUser(ip_addr=ip_addr)
365
365
366 authenticated = cookie_store.get('is_authenticated')
366 authenticated = cookie_store.get('is_authenticated')
367
367
368 if not auth_user.is_authenticated and auth_user.is_user_object:
368 if not auth_user.is_authenticated and auth_user.is_user_object:
369 # user is not authenticated and not empty
369 # user is not authenticated and not empty
370 auth_user.set_authenticated(authenticated)
370 auth_user.set_authenticated(authenticated)
371
371
372 return auth_user
372 return auth_user
373
373
374
374
375 class BaseController(WSGIController):
375 class BaseController(WSGIController):
376
376
377 def __before__(self):
377 def __before__(self):
378 """
378 """
379 __before__ is called before controller methods and after __call__
379 __before__ is called before controller methods and after __call__
380 """
380 """
381 # on each call propagate settings calls into global settings.
381 # on each call propagate settings calls into global settings.
382 set_rhodecode_config(config)
382 set_rhodecode_config(config)
383 attach_context_attributes(c)
383 attach_context_attributes(c)
384
384
385 # TODO: Remove this when fixed in attach_context_attributes()
385 # TODO: Remove this when fixed in attach_context_attributes()
386 c.repo_name = get_repo_slug(request) # can be empty
386 c.repo_name = get_repo_slug(request) # can be empty
387
387
388 self.cut_off_limit_diff = safe_int(config.get('cut_off_limit_diff'))
388 self.cut_off_limit_diff = safe_int(config.get('cut_off_limit_diff'))
389 self.cut_off_limit_file = safe_int(config.get('cut_off_limit_file'))
389 self.cut_off_limit_file = safe_int(config.get('cut_off_limit_file'))
390 self.sa = meta.Session
390 self.sa = meta.Session
391 self.scm_model = ScmModel(self.sa)
391 self.scm_model = ScmModel(self.sa)
392
392
393 default_lang = c.language
393 default_lang = c.language
394 user_lang = c.language
394 user_lang = c.language
395 try:
395 try:
396 user_obj = self._rhodecode_user.get_instance()
396 user_obj = self._rhodecode_user.get_instance()
397 if user_obj:
397 if user_obj:
398 user_lang = user_obj.user_data.get('language')
398 user_lang = user_obj.user_data.get('language')
399 except Exception:
399 except Exception:
400 log.exception('Failed to fetch user language for user %s',
400 log.exception('Failed to fetch user language for user %s',
401 self._rhodecode_user)
401 self._rhodecode_user)
402
402
403 if user_lang and user_lang != default_lang:
403 if user_lang and user_lang != default_lang:
404 log.debug('set language to %s for user %s', user_lang,
404 log.debug('set language to %s for user %s', user_lang,
405 self._rhodecode_user)
405 self._rhodecode_user)
406 translation.set_lang(user_lang)
406 translation.set_lang(user_lang)
407
407
408 def _dispatch_redirect(self, with_url, environ, start_response):
408 def _dispatch_redirect(self, with_url, environ, start_response):
409 resp = HTTPFound(with_url)
409 resp = HTTPFound(with_url)
410 environ['SCRIPT_NAME'] = '' # handle prefix middleware
410 environ['SCRIPT_NAME'] = '' # handle prefix middleware
411 environ['PATH_INFO'] = with_url
411 environ['PATH_INFO'] = with_url
412 return resp(environ, start_response)
412 return resp(environ, start_response)
413
413
414 def __call__(self, environ, start_response):
414 def __call__(self, environ, start_response):
415 """Invoke the Controller"""
415 """Invoke the Controller"""
416 # WSGIController.__call__ dispatches to the Controller method
416 # WSGIController.__call__ dispatches to the Controller method
417 # the request is routed to. This routing information is
417 # the request is routed to. This routing information is
418 # available in environ['pylons.routes_dict']
418 # available in environ['pylons.routes_dict']
419 from rhodecode.lib import helpers as h
419 from rhodecode.lib import helpers as h
420
420
421 # Provide the Pylons context to Pyramid's debugtoolbar if it asks
421 # Provide the Pylons context to Pyramid's debugtoolbar if it asks
422 if environ.get('debugtoolbar.wants_pylons_context', False):
422 if environ.get('debugtoolbar.wants_pylons_context', False):
423 environ['debugtoolbar.pylons_context'] = c._current_obj()
423 environ['debugtoolbar.pylons_context'] = c._current_obj()
424
424
425 _route_name = '.'.join([environ['pylons.routes_dict']['controller'],
425 _route_name = '.'.join([environ['pylons.routes_dict']['controller'],
426 environ['pylons.routes_dict']['action']])
426 environ['pylons.routes_dict']['action']])
427
427
428 self.rc_config = SettingsModel().get_all_settings()
428 self.rc_config = SettingsModel().get_all_settings(cache=True)
429 self.ip_addr = get_ip_addr(environ)
429 self.ip_addr = get_ip_addr(environ)
430
430
431 # The rhodecode auth user is looked up and passed through the
431 # The rhodecode auth user is looked up and passed through the
432 # environ by the pylons compatibility tween in pyramid.
432 # environ by the pylons compatibility tween in pyramid.
433 # So we can just grab it from there.
433 # So we can just grab it from there.
434 auth_user = environ['rc_auth_user']
434 auth_user = environ['rc_auth_user']
435
435
436 # set globals for auth user
436 # set globals for auth user
437 request.user = auth_user
437 request.user = auth_user
438 c.rhodecode_user = self._rhodecode_user = auth_user
438 c.rhodecode_user = self._rhodecode_user = auth_user
439
439
440 log.info('IP: %s User: %s accessed %s [%s]' % (
440 log.info('IP: %s User: %s accessed %s [%s]' % (
441 self.ip_addr, auth_user, safe_unicode(get_access_path(environ)),
441 self.ip_addr, auth_user, safe_unicode(get_access_path(environ)),
442 _route_name)
442 _route_name)
443 )
443 )
444
444
445 # TODO: Maybe this should be move to pyramid to cover all views.
445 # TODO: Maybe this should be move to pyramid to cover all views.
446 # check user attributes for password change flag
446 # check user attributes for password change flag
447 user_obj = auth_user.get_instance()
447 user_obj = auth_user.get_instance()
448 if user_obj and user_obj.user_data.get('force_password_change'):
448 if user_obj and user_obj.user_data.get('force_password_change'):
449 h.flash('You are required to change your password', 'warning',
449 h.flash('You are required to change your password', 'warning',
450 ignore_duplicate=True)
450 ignore_duplicate=True)
451
451
452 skip_user_check_urls = [
452 skip_user_check_urls = [
453 'error.document', 'login.logout', 'login.index',
453 'error.document', 'login.logout', 'login.index',
454 'admin/my_account.my_account_password',
454 'admin/my_account.my_account_password',
455 'admin/my_account.my_account_password_update'
455 'admin/my_account.my_account_password_update'
456 ]
456 ]
457 if _route_name not in skip_user_check_urls:
457 if _route_name not in skip_user_check_urls:
458 return self._dispatch_redirect(
458 return self._dispatch_redirect(
459 url('my_account_password'), environ, start_response)
459 url('my_account_password'), environ, start_response)
460
460
461 return WSGIController.__call__(self, environ, start_response)
461 return WSGIController.__call__(self, environ, start_response)
462
462
463
463
464 class BaseRepoController(BaseController):
464 class BaseRepoController(BaseController):
465 """
465 """
466 Base class for controllers responsible for loading all needed data for
466 Base class for controllers responsible for loading all needed data for
467 repository loaded items are
467 repository loaded items are
468
468
469 c.rhodecode_repo: instance of scm repository
469 c.rhodecode_repo: instance of scm repository
470 c.rhodecode_db_repo: instance of db
470 c.rhodecode_db_repo: instance of db
471 c.repository_requirements_missing: shows that repository specific data
471 c.repository_requirements_missing: shows that repository specific data
472 could not be displayed due to the missing requirements
472 could not be displayed due to the missing requirements
473 c.repository_pull_requests: show number of open pull requests
473 c.repository_pull_requests: show number of open pull requests
474 """
474 """
475
475
476 def __before__(self):
476 def __before__(self):
477 super(BaseRepoController, self).__before__()
477 super(BaseRepoController, self).__before__()
478 if c.repo_name: # extracted from routes
478 if c.repo_name: # extracted from routes
479 db_repo = Repository.get_by_repo_name(c.repo_name)
479 db_repo = Repository.get_by_repo_name(c.repo_name)
480 if not db_repo:
480 if not db_repo:
481 return
481 return
482
482
483 log.debug(
483 log.debug(
484 'Found repository in database %s with state `%s`',
484 'Found repository in database %s with state `%s`',
485 safe_unicode(db_repo), safe_unicode(db_repo.repo_state))
485 safe_unicode(db_repo), safe_unicode(db_repo.repo_state))
486 route = getattr(request.environ.get('routes.route'), 'name', '')
486 route = getattr(request.environ.get('routes.route'), 'name', '')
487
487
488 # allow to delete repos that are somehow damages in filesystem
488 # allow to delete repos that are somehow damages in filesystem
489 if route in ['delete_repo']:
489 if route in ['delete_repo']:
490 return
490 return
491
491
492 if db_repo.repo_state in [Repository.STATE_PENDING]:
492 if db_repo.repo_state in [Repository.STATE_PENDING]:
493 if route in ['repo_creating_home']:
493 if route in ['repo_creating_home']:
494 return
494 return
495 check_url = url('repo_creating_home', repo_name=c.repo_name)
495 check_url = url('repo_creating_home', repo_name=c.repo_name)
496 return redirect(check_url)
496 return redirect(check_url)
497
497
498 self.rhodecode_db_repo = db_repo
498 self.rhodecode_db_repo = db_repo
499
499
500 missing_requirements = False
500 missing_requirements = False
501 try:
501 try:
502 self.rhodecode_repo = self.rhodecode_db_repo.scm_instance()
502 self.rhodecode_repo = self.rhodecode_db_repo.scm_instance()
503 except RepositoryRequirementError as e:
503 except RepositoryRequirementError as e:
504 missing_requirements = True
504 missing_requirements = True
505 self._handle_missing_requirements(e)
505 self._handle_missing_requirements(e)
506
506
507 if self.rhodecode_repo is None and not missing_requirements:
507 if self.rhodecode_repo is None and not missing_requirements:
508 log.error('%s this repository is present in database but it '
508 log.error('%s this repository is present in database but it '
509 'cannot be created as an scm instance', c.repo_name)
509 'cannot be created as an scm instance', c.repo_name)
510
510
511 h.flash(_(
511 h.flash(_(
512 "The repository at %(repo_name)s cannot be located.") %
512 "The repository at %(repo_name)s cannot be located.") %
513 {'repo_name': c.repo_name},
513 {'repo_name': c.repo_name},
514 category='error', ignore_duplicate=True)
514 category='error', ignore_duplicate=True)
515 redirect(url('home'))
515 redirect(url('home'))
516
516
517 # update last change according to VCS data
517 # update last change according to VCS data
518 if not missing_requirements:
518 if not missing_requirements:
519 commit = db_repo.get_commit(
519 commit = db_repo.get_commit(
520 pre_load=["author", "date", "message", "parents"])
520 pre_load=["author", "date", "message", "parents"])
521 db_repo.update_commit_cache(commit)
521 db_repo.update_commit_cache(commit)
522
522
523 # Prepare context
523 # Prepare context
524 c.rhodecode_db_repo = db_repo
524 c.rhodecode_db_repo = db_repo
525 c.rhodecode_repo = self.rhodecode_repo
525 c.rhodecode_repo = self.rhodecode_repo
526 c.repository_requirements_missing = missing_requirements
526 c.repository_requirements_missing = missing_requirements
527
527
528 self._update_global_counters(self.scm_model, db_repo)
528 self._update_global_counters(self.scm_model, db_repo)
529
529
530 def _update_global_counters(self, scm_model, db_repo):
530 def _update_global_counters(self, scm_model, db_repo):
531 """
531 """
532 Base variables that are exposed to every page of repository
532 Base variables that are exposed to every page of repository
533 """
533 """
534 c.repository_pull_requests = scm_model.get_pull_requests(db_repo)
534 c.repository_pull_requests = scm_model.get_pull_requests(db_repo)
535
535
536 def _handle_missing_requirements(self, error):
536 def _handle_missing_requirements(self, error):
537 self.rhodecode_repo = None
537 self.rhodecode_repo = None
538 log.error(
538 log.error(
539 'Requirements are missing for repository %s: %s',
539 'Requirements are missing for repository %s: %s',
540 c.repo_name, error.message)
540 c.repo_name, error.message)
541
541
542 summary_url = url('summary_home', repo_name=c.repo_name)
542 summary_url = url('summary_home', repo_name=c.repo_name)
543 statistics_url = url('edit_repo_statistics', repo_name=c.repo_name)
543 statistics_url = url('edit_repo_statistics', repo_name=c.repo_name)
544 settings_update_url = url('repo', repo_name=c.repo_name)
544 settings_update_url = url('repo', repo_name=c.repo_name)
545 path = request.path
545 path = request.path
546 should_redirect = (
546 should_redirect = (
547 path not in (summary_url, settings_update_url)
547 path not in (summary_url, settings_update_url)
548 and '/settings' not in path or path == statistics_url
548 and '/settings' not in path or path == statistics_url
549 )
549 )
550 if should_redirect:
550 if should_redirect:
551 redirect(summary_url)
551 redirect(summary_url)
General Comments 0
You need to be logged in to leave comments. Login now