##// END OF EJS Templates
routing: optionally use explicit db object on route....
marcink -
r1989:f7b19fb3 default
parent child Browse files
Show More
@@ -1,454 +1,461 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 time
21 import time
22 import logging
22 import logging
23
23
24 from pyramid.httpexceptions import HTTPFound
24 from pyramid.httpexceptions import HTTPFound
25
25
26 from rhodecode.lib import helpers as h
26 from rhodecode.lib import helpers as h
27 from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time
27 from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time
28 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
28 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
29 from rhodecode.model import repo
29 from rhodecode.model import repo
30 from rhodecode.model import repo_group
30 from rhodecode.model import repo_group
31 from rhodecode.model.db import User
31 from rhodecode.model.db import User
32 from rhodecode.model.scm import ScmModel
32 from rhodecode.model.scm import ScmModel
33
33
34 log = logging.getLogger(__name__)
34 log = logging.getLogger(__name__)
35
35
36
36
37 ADMIN_PREFIX = '/_admin'
37 ADMIN_PREFIX = '/_admin'
38 STATIC_FILE_PREFIX = '/_static'
38 STATIC_FILE_PREFIX = '/_static'
39
39
40 URL_NAME_REQUIREMENTS = {
40 URL_NAME_REQUIREMENTS = {
41 # group name can have a slash in them, but they must not end with a slash
41 # group name can have a slash in them, but they must not end with a slash
42 'group_name': r'.*?[^/]',
42 'group_name': r'.*?[^/]',
43 'repo_group_name': r'.*?[^/]',
43 'repo_group_name': r'.*?[^/]',
44 # repo names can have a slash in them, but they must not end with a slash
44 # repo names can have a slash in them, but they must not end with a slash
45 'repo_name': r'.*?[^/]',
45 'repo_name': r'.*?[^/]',
46 # file path eats up everything at the end
46 # file path eats up everything at the end
47 'f_path': r'.*',
47 'f_path': r'.*',
48 # reference types
48 # reference types
49 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
49 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
50 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
50 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
51 }
51 }
52
52
53
53
54 def add_route_with_slash(config,name, pattern, **kw):
54 def add_route_with_slash(config,name, pattern, **kw):
55 config.add_route(name, pattern, **kw)
55 config.add_route(name, pattern, **kw)
56 if not pattern.endswith('/'):
56 if not pattern.endswith('/'):
57 config.add_route(name + '_slash', pattern + '/', **kw)
57 config.add_route(name + '_slash', pattern + '/', **kw)
58
58
59
59
60 def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS):
60 def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS):
61 """
61 """
62 Adds regex requirements to pyramid routes using a mapping dict
62 Adds regex requirements to pyramid routes using a mapping dict
63 e.g::
63 e.g::
64 add_route_requirements('{repo_name}/settings')
64 add_route_requirements('{repo_name}/settings')
65 """
65 """
66 for key, regex in requirements.items():
66 for key, regex in requirements.items():
67 route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex))
67 route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex))
68 return route_path
68 return route_path
69
69
70
70
71 def get_format_ref_id(repo):
71 def get_format_ref_id(repo):
72 """Returns a `repo` specific reference formatter function"""
72 """Returns a `repo` specific reference formatter function"""
73 if h.is_svn(repo):
73 if h.is_svn(repo):
74 return _format_ref_id_svn
74 return _format_ref_id_svn
75 else:
75 else:
76 return _format_ref_id
76 return _format_ref_id
77
77
78
78
79 def _format_ref_id(name, raw_id):
79 def _format_ref_id(name, raw_id):
80 """Default formatting of a given reference `name`"""
80 """Default formatting of a given reference `name`"""
81 return name
81 return name
82
82
83
83
84 def _format_ref_id_svn(name, raw_id):
84 def _format_ref_id_svn(name, raw_id):
85 """Special way of formatting a reference for Subversion including path"""
85 """Special way of formatting a reference for Subversion including path"""
86 return '%s@%s' % (name, raw_id)
86 return '%s@%s' % (name, raw_id)
87
87
88
88
89 class TemplateArgs(StrictAttributeDict):
89 class TemplateArgs(StrictAttributeDict):
90 pass
90 pass
91
91
92
92
93 class BaseAppView(object):
93 class BaseAppView(object):
94
94
95 def __init__(self, context, request):
95 def __init__(self, context, request):
96 self.request = request
96 self.request = request
97 self.context = context
97 self.context = context
98 self.session = request.session
98 self.session = request.session
99 self._rhodecode_user = request.user # auth user
99 self._rhodecode_user = request.user # auth user
100 self._rhodecode_db_user = self._rhodecode_user.get_instance()
100 self._rhodecode_db_user = self._rhodecode_user.get_instance()
101 self._maybe_needs_password_change(
101 self._maybe_needs_password_change(
102 request.matched_route.name, self._rhodecode_db_user)
102 request.matched_route.name, self._rhodecode_db_user)
103
103
104 def _maybe_needs_password_change(self, view_name, user_obj):
104 def _maybe_needs_password_change(self, view_name, user_obj):
105 log.debug('Checking if user %s needs password change on view %s',
105 log.debug('Checking if user %s needs password change on view %s',
106 user_obj, view_name)
106 user_obj, view_name)
107 skip_user_views = [
107 skip_user_views = [
108 'logout', 'login',
108 'logout', 'login',
109 'my_account_password', 'my_account_password_update'
109 'my_account_password', 'my_account_password_update'
110 ]
110 ]
111
111
112 if not user_obj:
112 if not user_obj:
113 return
113 return
114
114
115 if user_obj.username == User.DEFAULT_USER:
115 if user_obj.username == User.DEFAULT_USER:
116 return
116 return
117
117
118 now = time.time()
118 now = time.time()
119 should_change = user_obj.user_data.get('force_password_change')
119 should_change = user_obj.user_data.get('force_password_change')
120 change_after = safe_int(should_change) or 0
120 change_after = safe_int(should_change) or 0
121 if should_change and now > change_after:
121 if should_change and now > change_after:
122 log.debug('User %s requires password change', user_obj)
122 log.debug('User %s requires password change', user_obj)
123 h.flash('You are required to change your password', 'warning',
123 h.flash('You are required to change your password', 'warning',
124 ignore_duplicate=True)
124 ignore_duplicate=True)
125
125
126 if view_name not in skip_user_views:
126 if view_name not in skip_user_views:
127 raise HTTPFound(
127 raise HTTPFound(
128 self.request.route_path('my_account_password'))
128 self.request.route_path('my_account_password'))
129
129
130 def _log_creation_exception(self, e, repo_name):
130 def _log_creation_exception(self, e, repo_name):
131 _ = self.request.translate
131 _ = self.request.translate
132 reason = None
132 reason = None
133 if len(e.args) == 2:
133 if len(e.args) == 2:
134 reason = e.args[1]
134 reason = e.args[1]
135
135
136 if reason == 'INVALID_CERTIFICATE':
136 if reason == 'INVALID_CERTIFICATE':
137 log.exception(
137 log.exception(
138 'Exception creating a repository: invalid certificate')
138 'Exception creating a repository: invalid certificate')
139 msg = (_('Error creating repository %s: invalid certificate')
139 msg = (_('Error creating repository %s: invalid certificate')
140 % repo_name)
140 % repo_name)
141 else:
141 else:
142 log.exception("Exception creating a repository")
142 log.exception("Exception creating a repository")
143 msg = (_('Error creating repository %s')
143 msg = (_('Error creating repository %s')
144 % repo_name)
144 % repo_name)
145 return msg
145 return msg
146
146
147 def _get_local_tmpl_context(self, include_app_defaults=False):
147 def _get_local_tmpl_context(self, include_app_defaults=False):
148 c = TemplateArgs()
148 c = TemplateArgs()
149 c.auth_user = self.request.user
149 c.auth_user = self.request.user
150 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
150 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
151 c.rhodecode_user = self.request.user
151 c.rhodecode_user = self.request.user
152
152
153 if include_app_defaults:
153 if include_app_defaults:
154 # NOTE(marcink): after full pyramid migration include_app_defaults
154 # NOTE(marcink): after full pyramid migration include_app_defaults
155 # should be turned on by default
155 # should be turned on by default
156 from rhodecode.lib.base import attach_context_attributes
156 from rhodecode.lib.base import attach_context_attributes
157 attach_context_attributes(c, self.request, self.request.user.user_id)
157 attach_context_attributes(c, self.request, self.request.user.user_id)
158
158
159 return c
159 return c
160
160
161 def _register_global_c(self, tmpl_args):
161 def _register_global_c(self, tmpl_args):
162 """
162 """
163 Registers attributes to pylons global `c`
163 Registers attributes to pylons global `c`
164 """
164 """
165
165
166 # TODO(marcink): remove once pyramid migration is finished
166 # TODO(marcink): remove once pyramid migration is finished
167 from pylons import tmpl_context as c
167 from pylons import tmpl_context as c
168 try:
168 try:
169 for k, v in tmpl_args.items():
169 for k, v in tmpl_args.items():
170 setattr(c, k, v)
170 setattr(c, k, v)
171 except TypeError:
171 except TypeError:
172 log.exception('Failed to register pylons C')
172 log.exception('Failed to register pylons C')
173 pass
173 pass
174
174
175 def _get_template_context(self, tmpl_args):
175 def _get_template_context(self, tmpl_args):
176 self._register_global_c(tmpl_args)
176 self._register_global_c(tmpl_args)
177
177
178 local_tmpl_args = {
178 local_tmpl_args = {
179 'defaults': {},
179 'defaults': {},
180 'errors': {},
180 'errors': {},
181 # register a fake 'c' to be used in templates instead of global
181 # register a fake 'c' to be used in templates instead of global
182 # pylons c, after migration to pyramid we should rename it to 'c'
182 # pylons c, after migration to pyramid we should rename it to 'c'
183 # make sure we replace usage of _c in templates too
183 # make sure we replace usage of _c in templates too
184 '_c': tmpl_args
184 '_c': tmpl_args
185 }
185 }
186 local_tmpl_args.update(tmpl_args)
186 local_tmpl_args.update(tmpl_args)
187 return local_tmpl_args
187 return local_tmpl_args
188
188
189 def load_default_context(self):
189 def load_default_context(self):
190 """
190 """
191 example:
191 example:
192
192
193 def load_default_context(self):
193 def load_default_context(self):
194 c = self._get_local_tmpl_context()
194 c = self._get_local_tmpl_context()
195 c.custom_var = 'foobar'
195 c.custom_var = 'foobar'
196 self._register_global_c(c)
196 self._register_global_c(c)
197 return c
197 return c
198 """
198 """
199 raise NotImplementedError('Needs implementation in view class')
199 raise NotImplementedError('Needs implementation in view class')
200
200
201
201
202 class RepoAppView(BaseAppView):
202 class RepoAppView(BaseAppView):
203
203
204 def __init__(self, context, request):
204 def __init__(self, context, request):
205 super(RepoAppView, self).__init__(context, request)
205 super(RepoAppView, self).__init__(context, request)
206 self.db_repo = request.db_repo
206 self.db_repo = request.db_repo
207 self.db_repo_name = self.db_repo.repo_name
207 self.db_repo_name = self.db_repo.repo_name
208 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
208 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
209
209
210 def _handle_missing_requirements(self, error):
210 def _handle_missing_requirements(self, error):
211 log.error(
211 log.error(
212 'Requirements are missing for repository %s: %s',
212 'Requirements are missing for repository %s: %s',
213 self.db_repo_name, error.message)
213 self.db_repo_name, error.message)
214
214
215 def _get_local_tmpl_context(self, include_app_defaults=False):
215 def _get_local_tmpl_context(self, include_app_defaults=False):
216 _ = self.request.translate
216 _ = self.request.translate
217 c = super(RepoAppView, self)._get_local_tmpl_context(
217 c = super(RepoAppView, self)._get_local_tmpl_context(
218 include_app_defaults=include_app_defaults)
218 include_app_defaults=include_app_defaults)
219
219
220 # register common vars for this type of view
220 # register common vars for this type of view
221 c.rhodecode_db_repo = self.db_repo
221 c.rhodecode_db_repo = self.db_repo
222 c.repo_name = self.db_repo_name
222 c.repo_name = self.db_repo_name
223 c.repository_pull_requests = self.db_repo_pull_requests
223 c.repository_pull_requests = self.db_repo_pull_requests
224
224
225 c.repository_requirements_missing = False
225 c.repository_requirements_missing = False
226 try:
226 try:
227 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
227 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
228 except RepositoryRequirementError as e:
228 except RepositoryRequirementError as e:
229 c.repository_requirements_missing = True
229 c.repository_requirements_missing = True
230 self._handle_missing_requirements(e)
230 self._handle_missing_requirements(e)
231 self.rhodecode_vcs_repo = None
231 self.rhodecode_vcs_repo = None
232
232
233 if (not c.repository_requirements_missing
233 if (not c.repository_requirements_missing
234 and self.rhodecode_vcs_repo is None):
234 and self.rhodecode_vcs_repo is None):
235 # unable to fetch this repo as vcs instance, report back to user
235 # unable to fetch this repo as vcs instance, report back to user
236 h.flash(_(
236 h.flash(_(
237 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
237 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
238 "Please check if it exist, or is not damaged.") %
238 "Please check if it exist, or is not damaged.") %
239 {'repo_name': c.repo_name},
239 {'repo_name': c.repo_name},
240 category='error', ignore_duplicate=True)
240 category='error', ignore_duplicate=True)
241 raise HTTPFound(h.route_path('home'))
241 raise HTTPFound(h.route_path('home'))
242
242
243 return c
243 return c
244
244
245 def _get_f_path(self, matchdict, default=None):
245 def _get_f_path(self, matchdict, default=None):
246 f_path = matchdict.get('f_path')
246 f_path = matchdict.get('f_path')
247 if f_path:
247 if f_path:
248 # fix for multiple initial slashes that causes errors for GIT
248 # fix for multiple initial slashes that causes errors for GIT
249 return f_path.lstrip('/')
249 return f_path.lstrip('/')
250
250
251 return default
251 return default
252
252
253
253
254 class RepoGroupAppView(BaseAppView):
255 def __init__(self, context, request):
256 super(RepoGroupAppView, self).__init__(context, request)
257 self.db_repo_group = request.db_repo_group
258 self.db_repo_group_name = self.db_repo_group.group_name
259
260
254 class DataGridAppView(object):
261 class DataGridAppView(object):
255 """
262 """
256 Common class to have re-usable grid rendering components
263 Common class to have re-usable grid rendering components
257 """
264 """
258
265
259 def _extract_ordering(self, request, column_map=None):
266 def _extract_ordering(self, request, column_map=None):
260 column_map = column_map or {}
267 column_map = column_map or {}
261 column_index = safe_int(request.GET.get('order[0][column]'))
268 column_index = safe_int(request.GET.get('order[0][column]'))
262 order_dir = request.GET.get(
269 order_dir = request.GET.get(
263 'order[0][dir]', 'desc')
270 'order[0][dir]', 'desc')
264 order_by = request.GET.get(
271 order_by = request.GET.get(
265 'columns[%s][data][sort]' % column_index, 'name_raw')
272 'columns[%s][data][sort]' % column_index, 'name_raw')
266
273
267 # translate datatable to DB columns
274 # translate datatable to DB columns
268 order_by = column_map.get(order_by) or order_by
275 order_by = column_map.get(order_by) or order_by
269
276
270 search_q = request.GET.get('search[value]')
277 search_q = request.GET.get('search[value]')
271 return search_q, order_by, order_dir
278 return search_q, order_by, order_dir
272
279
273 def _extract_chunk(self, request):
280 def _extract_chunk(self, request):
274 start = safe_int(request.GET.get('start'), 0)
281 start = safe_int(request.GET.get('start'), 0)
275 length = safe_int(request.GET.get('length'), 25)
282 length = safe_int(request.GET.get('length'), 25)
276 draw = safe_int(request.GET.get('draw'))
283 draw = safe_int(request.GET.get('draw'))
277 return draw, start, length
284 return draw, start, length
278
285
279
286
280 class BaseReferencesView(RepoAppView):
287 class BaseReferencesView(RepoAppView):
281 """
288 """
282 Base for reference view for branches, tags and bookmarks.
289 Base for reference view for branches, tags and bookmarks.
283 """
290 """
284 def load_default_context(self):
291 def load_default_context(self):
285 c = self._get_local_tmpl_context()
292 c = self._get_local_tmpl_context()
286
293
287 # TODO(marcink): remove repo_info and use c.rhodecode_db_repo instead
294 # TODO(marcink): remove repo_info and use c.rhodecode_db_repo instead
288 c.repo_info = self.db_repo
295 c.repo_info = self.db_repo
289
296
290 self._register_global_c(c)
297 self._register_global_c(c)
291 return c
298 return c
292
299
293 def load_refs_context(self, ref_items, partials_template):
300 def load_refs_context(self, ref_items, partials_template):
294 _render = self.request.get_partial_renderer(partials_template)
301 _render = self.request.get_partial_renderer(partials_template)
295 pre_load = ["author", "date", "message"]
302 pre_load = ["author", "date", "message"]
296
303
297 is_svn = h.is_svn(self.rhodecode_vcs_repo)
304 is_svn = h.is_svn(self.rhodecode_vcs_repo)
298 is_hg = h.is_hg(self.rhodecode_vcs_repo)
305 is_hg = h.is_hg(self.rhodecode_vcs_repo)
299
306
300 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
307 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
301
308
302 closed_refs = {}
309 closed_refs = {}
303 if is_hg:
310 if is_hg:
304 closed_refs = self.rhodecode_vcs_repo.branches_closed
311 closed_refs = self.rhodecode_vcs_repo.branches_closed
305
312
306 data = []
313 data = []
307 for ref_name, commit_id in ref_items:
314 for ref_name, commit_id in ref_items:
308 commit = self.rhodecode_vcs_repo.get_commit(
315 commit = self.rhodecode_vcs_repo.get_commit(
309 commit_id=commit_id, pre_load=pre_load)
316 commit_id=commit_id, pre_load=pre_load)
310 closed = ref_name in closed_refs
317 closed = ref_name in closed_refs
311
318
312 # TODO: johbo: Unify generation of reference links
319 # TODO: johbo: Unify generation of reference links
313 use_commit_id = '/' in ref_name or is_svn
320 use_commit_id = '/' in ref_name or is_svn
314
321
315 if use_commit_id:
322 if use_commit_id:
316 files_url = h.route_path(
323 files_url = h.route_path(
317 'repo_files',
324 'repo_files',
318 repo_name=self.db_repo_name,
325 repo_name=self.db_repo_name,
319 f_path=ref_name if is_svn else '',
326 f_path=ref_name if is_svn else '',
320 commit_id=commit_id)
327 commit_id=commit_id)
321
328
322 else:
329 else:
323 files_url = h.route_path(
330 files_url = h.route_path(
324 'repo_files',
331 'repo_files',
325 repo_name=self.db_repo_name,
332 repo_name=self.db_repo_name,
326 f_path=ref_name if is_svn else '',
333 f_path=ref_name if is_svn else '',
327 commit_id=ref_name,
334 commit_id=ref_name,
328 _query=dict(at=ref_name))
335 _query=dict(at=ref_name))
329
336
330 data.append({
337 data.append({
331 "name": _render('name', ref_name, files_url, closed),
338 "name": _render('name', ref_name, files_url, closed),
332 "name_raw": ref_name,
339 "name_raw": ref_name,
333 "date": _render('date', commit.date),
340 "date": _render('date', commit.date),
334 "date_raw": datetime_to_time(commit.date),
341 "date_raw": datetime_to_time(commit.date),
335 "author": _render('author', commit.author),
342 "author": _render('author', commit.author),
336 "commit": _render(
343 "commit": _render(
337 'commit', commit.message, commit.raw_id, commit.idx),
344 'commit', commit.message, commit.raw_id, commit.idx),
338 "commit_raw": commit.idx,
345 "commit_raw": commit.idx,
339 "compare": _render(
346 "compare": _render(
340 'compare', format_ref_id(ref_name, commit.raw_id)),
347 'compare', format_ref_id(ref_name, commit.raw_id)),
341 })
348 })
342
349
343 return data
350 return data
344
351
345
352
346 class RepoRoutePredicate(object):
353 class RepoRoutePredicate(object):
347 def __init__(self, val, config):
354 def __init__(self, val, config):
348 self.val = val
355 self.val = val
349
356
350 def text(self):
357 def text(self):
351 return 'repo_route = %s' % self.val
358 return 'repo_route = %s' % self.val
352
359
353 phash = text
360 phash = text
354
361
355 def __call__(self, info, request):
362 def __call__(self, info, request):
356
363
357 if hasattr(request, 'vcs_call'):
364 if hasattr(request, 'vcs_call'):
358 # skip vcs calls
365 # skip vcs calls
359 return
366 return
360
367
361 repo_name = info['match']['repo_name']
368 repo_name = info['match']['repo_name']
362 repo_model = repo.RepoModel()
369 repo_model = repo.RepoModel()
363 by_name_match = repo_model.get_by_repo_name(repo_name, cache=True)
370 by_name_match = repo_model.get_by_repo_name(repo_name, cache=True)
364
371
365 def redirect_if_creating(db_repo):
372 def redirect_if_creating(db_repo):
366 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
373 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
367 raise HTTPFound(
374 raise HTTPFound(
368 request.route_path('repo_creating',
375 request.route_path('repo_creating',
369 repo_name=db_repo.repo_name))
376 repo_name=db_repo.repo_name))
370
377
371 if by_name_match:
378 if by_name_match:
372 # register this as request object we can re-use later
379 # register this as request object we can re-use later
373 request.db_repo = by_name_match
380 request.db_repo = by_name_match
374 redirect_if_creating(by_name_match)
381 redirect_if_creating(by_name_match)
375 return True
382 return True
376
383
377 by_id_match = repo_model.get_repo_by_id(repo_name)
384 by_id_match = repo_model.get_repo_by_id(repo_name)
378 if by_id_match:
385 if by_id_match:
379 request.db_repo = by_id_match
386 request.db_repo = by_id_match
380 redirect_if_creating(by_id_match)
387 redirect_if_creating(by_id_match)
381 return True
388 return True
382
389
383 return False
390 return False
384
391
385
392
386 class RepoTypeRoutePredicate(object):
393 class RepoTypeRoutePredicate(object):
387 def __init__(self, val, config):
394 def __init__(self, val, config):
388 self.val = val or ['hg', 'git', 'svn']
395 self.val = val or ['hg', 'git', 'svn']
389
396
390 def text(self):
397 def text(self):
391 return 'repo_accepted_type = %s' % self.val
398 return 'repo_accepted_type = %s' % self.val
392
399
393 phash = text
400 phash = text
394
401
395 def __call__(self, info, request):
402 def __call__(self, info, request):
396 if hasattr(request, 'vcs_call'):
403 if hasattr(request, 'vcs_call'):
397 # skip vcs calls
404 # skip vcs calls
398 return
405 return
399
406
400 rhodecode_db_repo = request.db_repo
407 rhodecode_db_repo = request.db_repo
401
408
402 log.debug(
409 log.debug(
403 '%s checking repo type for %s in %s',
410 '%s checking repo type for %s in %s',
404 self.__class__.__name__, rhodecode_db_repo.repo_type, self.val)
411 self.__class__.__name__, rhodecode_db_repo.repo_type, self.val)
405
412
406 if rhodecode_db_repo.repo_type in self.val:
413 if rhodecode_db_repo.repo_type in self.val:
407 return True
414 return True
408 else:
415 else:
409 log.warning('Current view is not supported for repo type:%s',
416 log.warning('Current view is not supported for repo type:%s',
410 rhodecode_db_repo.repo_type)
417 rhodecode_db_repo.repo_type)
411 #
418 #
412 # h.flash(h.literal(
419 # h.flash(h.literal(
413 # _('Action not supported for %s.' % rhodecode_repo.alias)),
420 # _('Action not supported for %s.' % rhodecode_repo.alias)),
414 # category='warning')
421 # category='warning')
415 # return redirect(
422 # return redirect(
416 # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name))
423 # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name))
417
424
418 return False
425 return False
419
426
420
427
421 class RepoGroupRoutePredicate(object):
428 class RepoGroupRoutePredicate(object):
422 def __init__(self, val, config):
429 def __init__(self, val, config):
423 self.val = val
430 self.val = val
424
431
425 def text(self):
432 def text(self):
426 return 'repo_group_route = %s' % self.val
433 return 'repo_group_route = %s' % self.val
427
434
428 phash = text
435 phash = text
429
436
430 def __call__(self, info, request):
437 def __call__(self, info, request):
431 if hasattr(request, 'vcs_call'):
438 if hasattr(request, 'vcs_call'):
432 # skip vcs calls
439 # skip vcs calls
433 return
440 return
434
441
435 repo_group_name = info['match']['repo_group_name']
442 repo_group_name = info['match']['repo_group_name']
436 repo_group_model = repo_group.RepoGroupModel()
443 repo_group_model = repo_group.RepoGroupModel()
437 by_name_match = repo_group_model.get_by_group_name(
444 by_name_match = repo_group_model.get_by_group_name(
438 repo_group_name, cache=True)
445 repo_group_name, cache=True)
439
446
440 if by_name_match:
447 if by_name_match:
441 # register this as request object we can re-use later
448 # register this as request object we can re-use later
442 request.db_repo_group = by_name_match
449 request.db_repo_group = by_name_match
443 return True
450 return True
444
451
445 return False
452 return False
446
453
447
454
448 def includeme(config):
455 def includeme(config):
449 config.add_route_predicate(
456 config.add_route_predicate(
450 'repo_route', RepoRoutePredicate)
457 'repo_route', RepoRoutePredicate)
451 config.add_route_predicate(
458 config.add_route_predicate(
452 'repo_accepted_types', RepoTypeRoutePredicate)
459 'repo_accepted_types', RepoTypeRoutePredicate)
453 config.add_route_predicate(
460 config.add_route_predicate(
454 'repo_group_route', RepoGroupRoutePredicate)
461 'repo_group_route', RepoGroupRoutePredicate)
@@ -1,534 +1,534 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-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 """
21 """
22 Pylons middleware initialization
22 Pylons middleware initialization
23 """
23 """
24 import logging
24 import logging
25 import traceback
25 import traceback
26 from collections import OrderedDict
26 from collections import OrderedDict
27
27
28 from paste.registry import RegistryManager
28 from paste.registry import RegistryManager
29 from paste.gzipper import make_gzip_middleware
29 from paste.gzipper import make_gzip_middleware
30 from pylons.wsgiapp import PylonsApp
30 from pylons.wsgiapp import PylonsApp
31 from pyramid.authorization import ACLAuthorizationPolicy
31 from pyramid.authorization import ACLAuthorizationPolicy
32 from pyramid.config import Configurator
32 from pyramid.config import Configurator
33 from pyramid.settings import asbool, aslist
33 from pyramid.settings import asbool, aslist
34 from pyramid.wsgi import wsgiapp
34 from pyramid.wsgi import wsgiapp
35 from pyramid.httpexceptions import (
35 from pyramid.httpexceptions import (
36 HTTPException, HTTPError, HTTPInternalServerError, HTTPFound)
36 HTTPException, HTTPError, HTTPInternalServerError, HTTPFound)
37 from pyramid.events import ApplicationCreated
37 from pyramid.events import ApplicationCreated
38 from pyramid.renderers import render_to_response
38 from pyramid.renderers import render_to_response
39 from routes.middleware import RoutesMiddleware
39 from routes.middleware import RoutesMiddleware
40 import rhodecode
40 import rhodecode
41
41
42 from rhodecode.model import meta
42 from rhodecode.model import meta
43 from rhodecode.config import patches
43 from rhodecode.config import patches
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.environment import (
45 from rhodecode.config.environment import (
46 load_environment, load_pyramid_environment)
46 load_environment, load_pyramid_environment)
47
47
48 from rhodecode.lib.vcs import VCSCommunicationError
48 from rhodecode.lib.vcs import VCSCommunicationError
49 from rhodecode.lib.exceptions import VCSServerUnavailable
49 from rhodecode.lib.exceptions import VCSServerUnavailable
50 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
50 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
51 from rhodecode.lib.middleware.error_handling import (
51 from rhodecode.lib.middleware.error_handling import (
52 PylonsErrorHandlingMiddleware)
52 PylonsErrorHandlingMiddleware)
53 from rhodecode.lib.middleware.https_fixup import HttpsFixup
53 from rhodecode.lib.middleware.https_fixup import HttpsFixup
54 from rhodecode.lib.middleware.vcs import VCSMiddleware
54 from rhodecode.lib.middleware.vcs import VCSMiddleware
55 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
55 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
56 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
56 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 from rhodecode.subscribers import (
57 from rhodecode.subscribers import (
58 scan_repositories_if_enabled, write_js_routes_if_enabled,
58 scan_repositories_if_enabled, write_js_routes_if_enabled,
59 write_metadata_if_needed)
59 write_metadata_if_needed)
60
60
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64
64
65 # this is used to avoid avoid the route lookup overhead in routesmiddleware
65 # this is used to avoid avoid the route lookup overhead in routesmiddleware
66 # for certain routes which won't go to pylons to - eg. static files, debugger
66 # for certain routes which won't go to pylons to - eg. static files, debugger
67 # it is only needed for the pylons migration and can be removed once complete
67 # it is only needed for the pylons migration and can be removed once complete
68 class SkippableRoutesMiddleware(RoutesMiddleware):
68 class SkippableRoutesMiddleware(RoutesMiddleware):
69 """ Routes middleware that allows you to skip prefixes """
69 """ Routes middleware that allows you to skip prefixes """
70
70
71 def __init__(self, *args, **kw):
71 def __init__(self, *args, **kw):
72 self.skip_prefixes = kw.pop('skip_prefixes', [])
72 self.skip_prefixes = kw.pop('skip_prefixes', [])
73 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
73 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
74
74
75 def __call__(self, environ, start_response):
75 def __call__(self, environ, start_response):
76 for prefix in self.skip_prefixes:
76 for prefix in self.skip_prefixes:
77 if environ['PATH_INFO'].startswith(prefix):
77 if environ['PATH_INFO'].startswith(prefix):
78 # added to avoid the case when a missing /_static route falls
78 # added to avoid the case when a missing /_static route falls
79 # through to pylons and causes an exception as pylons is
79 # through to pylons and causes an exception as pylons is
80 # expecting wsgiorg.routingargs to be set in the environ
80 # expecting wsgiorg.routingargs to be set in the environ
81 # by RoutesMiddleware.
81 # by RoutesMiddleware.
82 if 'wsgiorg.routing_args' not in environ:
82 if 'wsgiorg.routing_args' not in environ:
83 environ['wsgiorg.routing_args'] = (None, {})
83 environ['wsgiorg.routing_args'] = (None, {})
84 return self.app(environ, start_response)
84 return self.app(environ, start_response)
85
85
86 return super(SkippableRoutesMiddleware, self).__call__(
86 return super(SkippableRoutesMiddleware, self).__call__(
87 environ, start_response)
87 environ, start_response)
88
88
89
89
90 def make_app(global_conf, static_files=True, **app_conf):
90 def make_app(global_conf, static_files=True, **app_conf):
91 """Create a Pylons WSGI application and return it
91 """Create a Pylons WSGI application and return it
92
92
93 ``global_conf``
93 ``global_conf``
94 The inherited configuration for this application. Normally from
94 The inherited configuration for this application. Normally from
95 the [DEFAULT] section of the Paste ini file.
95 the [DEFAULT] section of the Paste ini file.
96
96
97 ``app_conf``
97 ``app_conf``
98 The application's local configuration. Normally specified in
98 The application's local configuration. Normally specified in
99 the [app:<name>] section of the Paste ini file (where <name>
99 the [app:<name>] section of the Paste ini file (where <name>
100 defaults to main).
100 defaults to main).
101
101
102 """
102 """
103 # Apply compatibility patches
103 # Apply compatibility patches
104 patches.kombu_1_5_1_python_2_7_11()
104 patches.kombu_1_5_1_python_2_7_11()
105 patches.inspect_getargspec()
105 patches.inspect_getargspec()
106
106
107 # Configure the Pylons environment
107 # Configure the Pylons environment
108 config = load_environment(global_conf, app_conf)
108 config = load_environment(global_conf, app_conf)
109
109
110 # The Pylons WSGI app
110 # The Pylons WSGI app
111 app = PylonsApp(config=config)
111 app = PylonsApp(config=config)
112
112
113 # Establish the Registry for this application
113 # Establish the Registry for this application
114 app = RegistryManager(app)
114 app = RegistryManager(app)
115
115
116 app.config = config
116 app.config = config
117
117
118 return app
118 return app
119
119
120
120
121 def make_pyramid_app(global_config, **settings):
121 def make_pyramid_app(global_config, **settings):
122 """
122 """
123 Constructs the WSGI application based on Pyramid and wraps the Pylons based
123 Constructs the WSGI application based on Pyramid and wraps the Pylons based
124 application.
124 application.
125
125
126 Specials:
126 Specials:
127
127
128 * We migrate from Pylons to Pyramid. While doing this, we keep both
128 * We migrate from Pylons to Pyramid. While doing this, we keep both
129 frameworks functional. This involves moving some WSGI middlewares around
129 frameworks functional. This involves moving some WSGI middlewares around
130 and providing access to some data internals, so that the old code is
130 and providing access to some data internals, so that the old code is
131 still functional.
131 still functional.
132
132
133 * The application can also be integrated like a plugin via the call to
133 * The application can also be integrated like a plugin via the call to
134 `includeme`. This is accompanied with the other utility functions which
134 `includeme`. This is accompanied with the other utility functions which
135 are called. Changing this should be done with great care to not break
135 are called. Changing this should be done with great care to not break
136 cases when these fragments are assembled from another place.
136 cases when these fragments are assembled from another place.
137
137
138 """
138 """
139 # The edition string should be available in pylons too, so we add it here
139 # The edition string should be available in pylons too, so we add it here
140 # before copying the settings.
140 # before copying the settings.
141 settings.setdefault('rhodecode.edition', 'Community Edition')
141 settings.setdefault('rhodecode.edition', 'Community Edition')
142
142
143 # As long as our Pylons application does expect "unprepared" settings, make
143 # As long as our Pylons application does expect "unprepared" settings, make
144 # sure that we keep an unmodified copy. This avoids unintentional change of
144 # sure that we keep an unmodified copy. This avoids unintentional change of
145 # behavior in the old application.
145 # behavior in the old application.
146 settings_pylons = settings.copy()
146 settings_pylons = settings.copy()
147
147
148 sanitize_settings_and_apply_defaults(settings)
148 sanitize_settings_and_apply_defaults(settings)
149 config = Configurator(settings=settings)
149 config = Configurator(settings=settings)
150 add_pylons_compat_data(config.registry, global_config, settings_pylons)
150 add_pylons_compat_data(config.registry, global_config, settings_pylons)
151
151
152 load_pyramid_environment(global_config, settings)
152 load_pyramid_environment(global_config, settings)
153
153
154 includeme_first(config)
154 includeme_first(config)
155 includeme(config)
155 includeme(config)
156
156
157 pyramid_app = config.make_wsgi_app()
157 pyramid_app = config.make_wsgi_app()
158 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
158 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
159 pyramid_app.config = config
159 pyramid_app.config = config
160
160
161 # creating the app uses a connection - return it after we are done
161 # creating the app uses a connection - return it after we are done
162 meta.Session.remove()
162 meta.Session.remove()
163
163
164 return pyramid_app
164 return pyramid_app
165
165
166
166
167 def make_not_found_view(config):
167 def make_not_found_view(config):
168 """
168 """
169 This creates the view which should be registered as not-found-view to
169 This creates the view which should be registered as not-found-view to
170 pyramid. Basically it contains of the old pylons app, converted to a view.
170 pyramid. Basically it contains of the old pylons app, converted to a view.
171 Additionally it is wrapped by some other middlewares.
171 Additionally it is wrapped by some other middlewares.
172 """
172 """
173 settings = config.registry.settings
173 settings = config.registry.settings
174 vcs_server_enabled = settings['vcs.server.enable']
174 vcs_server_enabled = settings['vcs.server.enable']
175
175
176 # Make pylons app from unprepared settings.
176 # Make pylons app from unprepared settings.
177 pylons_app = make_app(
177 pylons_app = make_app(
178 config.registry._pylons_compat_global_config,
178 config.registry._pylons_compat_global_config,
179 **config.registry._pylons_compat_settings)
179 **config.registry._pylons_compat_settings)
180 config.registry._pylons_compat_config = pylons_app.config
180 config.registry._pylons_compat_config = pylons_app.config
181
181
182 # Appenlight monitoring.
182 # Appenlight monitoring.
183 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
183 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
184 pylons_app, settings)
184 pylons_app, settings)
185
185
186 # The pylons app is executed inside of the pyramid 404 exception handler.
186 # The pylons app is executed inside of the pyramid 404 exception handler.
187 # Exceptions which are raised inside of it are not handled by pyramid
187 # Exceptions which are raised inside of it are not handled by pyramid
188 # again. Therefore we add a middleware that invokes the error handler in
188 # again. Therefore we add a middleware that invokes the error handler in
189 # case of an exception or error response. This way we return proper error
189 # case of an exception or error response. This way we return proper error
190 # HTML pages in case of an error.
190 # HTML pages in case of an error.
191 reraise = (settings.get('debugtoolbar.enabled', False) or
191 reraise = (settings.get('debugtoolbar.enabled', False) or
192 rhodecode.disable_error_handler)
192 rhodecode.disable_error_handler)
193 pylons_app = PylonsErrorHandlingMiddleware(
193 pylons_app = PylonsErrorHandlingMiddleware(
194 pylons_app, error_handler, reraise)
194 pylons_app, error_handler, reraise)
195
195
196 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
196 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
197 # view to handle the request. Therefore it is wrapped around the pylons
197 # view to handle the request. Therefore it is wrapped around the pylons
198 # app. It has to be outside of the error handling otherwise error responses
198 # app. It has to be outside of the error handling otherwise error responses
199 # from the vcsserver are converted to HTML error pages. This confuses the
199 # from the vcsserver are converted to HTML error pages. This confuses the
200 # command line tools and the user won't get a meaningful error message.
200 # command line tools and the user won't get a meaningful error message.
201 if vcs_server_enabled:
201 if vcs_server_enabled:
202 pylons_app = VCSMiddleware(
202 pylons_app = VCSMiddleware(
203 pylons_app, settings, appenlight_client, registry=config.registry)
203 pylons_app, settings, appenlight_client, registry=config.registry)
204
204
205 # Convert WSGI app to pyramid view and return it.
205 # Convert WSGI app to pyramid view and return it.
206 return wsgiapp(pylons_app)
206 return wsgiapp(pylons_app)
207
207
208
208
209 def add_pylons_compat_data(registry, global_config, settings):
209 def add_pylons_compat_data(registry, global_config, settings):
210 """
210 """
211 Attach data to the registry to support the Pylons integration.
211 Attach data to the registry to support the Pylons integration.
212 """
212 """
213 registry._pylons_compat_global_config = global_config
213 registry._pylons_compat_global_config = global_config
214 registry._pylons_compat_settings = settings
214 registry._pylons_compat_settings = settings
215
215
216
216
217 def error_handler(exception, request):
217 def error_handler(exception, request):
218 import rhodecode
218 import rhodecode
219 from rhodecode.lib import helpers
219 from rhodecode.lib import helpers
220
220
221 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
221 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
222
222
223 base_response = HTTPInternalServerError()
223 base_response = HTTPInternalServerError()
224 # prefer original exception for the response since it may have headers set
224 # prefer original exception for the response since it may have headers set
225 if isinstance(exception, HTTPException):
225 if isinstance(exception, HTTPException):
226 base_response = exception
226 base_response = exception
227 elif isinstance(exception, VCSCommunicationError):
227 elif isinstance(exception, VCSCommunicationError):
228 base_response = VCSServerUnavailable()
228 base_response = VCSServerUnavailable()
229
229
230 def is_http_error(response):
230 def is_http_error(response):
231 # error which should have traceback
231 # error which should have traceback
232 return response.status_code > 499
232 return response.status_code > 499
233
233
234 if is_http_error(base_response):
234 if is_http_error(base_response):
235 log.exception(
235 log.exception(
236 'error occurred handling this request for path: %s', request.path)
236 'error occurred handling this request for path: %s', request.path)
237
237
238 c = AttributeDict()
238 c = AttributeDict()
239 c.error_message = base_response.status
239 c.error_message = base_response.status
240 c.error_explanation = base_response.explanation or str(base_response)
240 c.error_explanation = base_response.explanation or str(base_response)
241 c.visual = AttributeDict()
241 c.visual = AttributeDict()
242
242
243 c.visual.rhodecode_support_url = (
243 c.visual.rhodecode_support_url = (
244 request.registry.settings.get('rhodecode_support_url') or
244 request.registry.settings.get('rhodecode_support_url') or
245 request.route_url('rhodecode_support')
245 request.route_url('rhodecode_support')
246 )
246 )
247 c.redirect_time = 0
247 c.redirect_time = 0
248 c.rhodecode_name = rhodecode_title
248 c.rhodecode_name = rhodecode_title
249 if not c.rhodecode_name:
249 if not c.rhodecode_name:
250 c.rhodecode_name = 'Rhodecode'
250 c.rhodecode_name = 'Rhodecode'
251
251
252 c.causes = []
252 c.causes = []
253 if hasattr(base_response, 'causes'):
253 if hasattr(base_response, 'causes'):
254 c.causes = base_response.causes
254 c.causes = base_response.causes
255 c.messages = helpers.flash.pop_messages(request=request)
255 c.messages = helpers.flash.pop_messages(request=request)
256 c.traceback = traceback.format_exc()
256 c.traceback = traceback.format_exc()
257 response = render_to_response(
257 response = render_to_response(
258 '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request,
258 '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request,
259 response=base_response)
259 response=base_response)
260
260
261 return response
261 return response
262
262
263
263
264 def includeme(config):
264 def includeme(config):
265 settings = config.registry.settings
265 settings = config.registry.settings
266
266
267 # plugin information
267 # plugin information
268 config.registry.rhodecode_plugins = OrderedDict()
268 config.registry.rhodecode_plugins = OrderedDict()
269
269
270 config.add_directive(
270 config.add_directive(
271 'register_rhodecode_plugin', register_rhodecode_plugin)
271 'register_rhodecode_plugin', register_rhodecode_plugin)
272
272
273 if asbool(settings.get('appenlight', 'false')):
273 if asbool(settings.get('appenlight', 'false')):
274 config.include('appenlight_client.ext.pyramid_tween')
274 config.include('appenlight_client.ext.pyramid_tween')
275
275
276 if not 'mako.default_filters' in settings:
276 if 'mako.default_filters' not in settings:
277 # set custom default filters if we don't have it defined
277 # set custom default filters if we don't have it defined
278 settings['mako.imports'] = 'from rhodecode.lib.base import h_filter'
278 settings['mako.imports'] = 'from rhodecode.lib.base import h_filter'
279 settings['mako.default_filters'] = 'h_filter'
279 settings['mako.default_filters'] = 'h_filter'
280
280
281 # Includes which are required. The application would fail without them.
281 # Includes which are required. The application would fail without them.
282 config.include('pyramid_mako')
282 config.include('pyramid_mako')
283 config.include('pyramid_beaker')
283 config.include('pyramid_beaker')
284
284
285 config.include('rhodecode.authentication')
285 config.include('rhodecode.authentication')
286 config.include('rhodecode.integrations')
286 config.include('rhodecode.integrations')
287
287
288 # apps
288 # apps
289 config.include('rhodecode.apps._base')
289 config.include('rhodecode.apps._base')
290 config.include('rhodecode.apps.ops')
290 config.include('rhodecode.apps.ops')
291
291
292 config.include('rhodecode.apps.admin')
292 config.include('rhodecode.apps.admin')
293 config.include('rhodecode.apps.channelstream')
293 config.include('rhodecode.apps.channelstream')
294 config.include('rhodecode.apps.login')
294 config.include('rhodecode.apps.login')
295 config.include('rhodecode.apps.home')
295 config.include('rhodecode.apps.home')
296 config.include('rhodecode.apps.journal')
296 config.include('rhodecode.apps.journal')
297 config.include('rhodecode.apps.repository')
297 config.include('rhodecode.apps.repository')
298 config.include('rhodecode.apps.repo_group')
298 config.include('rhodecode.apps.repo_group')
299 config.include('rhodecode.apps.search')
299 config.include('rhodecode.apps.search')
300 config.include('rhodecode.apps.user_profile')
300 config.include('rhodecode.apps.user_profile')
301 config.include('rhodecode.apps.my_account')
301 config.include('rhodecode.apps.my_account')
302 config.include('rhodecode.apps.svn_support')
302 config.include('rhodecode.apps.svn_support')
303 config.include('rhodecode.apps.gist')
303 config.include('rhodecode.apps.gist')
304
304
305 config.include('rhodecode.apps.debug_style')
305 config.include('rhodecode.apps.debug_style')
306 config.include('rhodecode.tweens')
306 config.include('rhodecode.tweens')
307 config.include('rhodecode.api')
307 config.include('rhodecode.api')
308
308
309 config.add_route(
309 config.add_route(
310 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
310 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
311
311
312 config.add_translation_dirs('rhodecode:i18n/')
312 config.add_translation_dirs('rhodecode:i18n/')
313 settings['default_locale_name'] = settings.get('lang', 'en')
313 settings['default_locale_name'] = settings.get('lang', 'en')
314
314
315 # Add subscribers.
315 # Add subscribers.
316 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
316 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
317 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
317 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
318 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
318 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
319
319
320 config.add_request_method(
320 config.add_request_method(
321 'rhodecode.lib.partial_renderer.get_partial_renderer',
321 'rhodecode.lib.partial_renderer.get_partial_renderer',
322 'get_partial_renderer')
322 'get_partial_renderer')
323
323
324 # events
324 # events
325 # TODO(marcink): this should be done when pyramid migration is finished
325 # TODO(marcink): this should be done when pyramid migration is finished
326 # config.add_subscriber(
326 # config.add_subscriber(
327 # 'rhodecode.integrations.integrations_event_handler',
327 # 'rhodecode.integrations.integrations_event_handler',
328 # 'rhodecode.events.RhodecodeEvent')
328 # 'rhodecode.events.RhodecodeEvent')
329
329
330 # Set the authorization policy.
330 # Set the authorization policy.
331 authz_policy = ACLAuthorizationPolicy()
331 authz_policy = ACLAuthorizationPolicy()
332 config.set_authorization_policy(authz_policy)
332 config.set_authorization_policy(authz_policy)
333
333
334 # Set the default renderer for HTML templates to mako.
334 # Set the default renderer for HTML templates to mako.
335 config.add_mako_renderer('.html')
335 config.add_mako_renderer('.html')
336
336
337 config.add_renderer(
337 config.add_renderer(
338 name='json_ext',
338 name='json_ext',
339 factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json')
339 factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json')
340
340
341 # include RhodeCode plugins
341 # include RhodeCode plugins
342 includes = aslist(settings.get('rhodecode.includes', []))
342 includes = aslist(settings.get('rhodecode.includes', []))
343 for inc in includes:
343 for inc in includes:
344 config.include(inc)
344 config.include(inc)
345
345
346 # This is the glue which allows us to migrate in chunks. By registering the
346 # This is the glue which allows us to migrate in chunks. By registering the
347 # pylons based application as the "Not Found" view in Pyramid, we will
347 # pylons based application as the "Not Found" view in Pyramid, we will
348 # fallback to the old application each time the new one does not yet know
348 # fallback to the old application each time the new one does not yet know
349 # how to handle a request.
349 # how to handle a request.
350 config.add_notfound_view(make_not_found_view(config))
350 config.add_notfound_view(make_not_found_view(config))
351
351
352 if not settings.get('debugtoolbar.enabled', False):
352 if not settings.get('debugtoolbar.enabled', False):
353 # disabled debugtoolbar handle all exceptions via the error_handlers
353 # disabled debugtoolbar handle all exceptions via the error_handlers
354 config.add_view(error_handler, context=Exception)
354 config.add_view(error_handler, context=Exception)
355
355
356 config.add_view(error_handler, context=HTTPError)
356 config.add_view(error_handler, context=HTTPError)
357
357
358
358
359 def includeme_first(config):
359 def includeme_first(config):
360 # redirect automatic browser favicon.ico requests to correct place
360 # redirect automatic browser favicon.ico requests to correct place
361 def favicon_redirect(context, request):
361 def favicon_redirect(context, request):
362 return HTTPFound(
362 return HTTPFound(
363 request.static_path('rhodecode:public/images/favicon.ico'))
363 request.static_path('rhodecode:public/images/favicon.ico'))
364
364
365 config.add_view(favicon_redirect, route_name='favicon')
365 config.add_view(favicon_redirect, route_name='favicon')
366 config.add_route('favicon', '/favicon.ico')
366 config.add_route('favicon', '/favicon.ico')
367
367
368 def robots_redirect(context, request):
368 def robots_redirect(context, request):
369 return HTTPFound(
369 return HTTPFound(
370 request.static_path('rhodecode:public/robots.txt'))
370 request.static_path('rhodecode:public/robots.txt'))
371
371
372 config.add_view(robots_redirect, route_name='robots')
372 config.add_view(robots_redirect, route_name='robots')
373 config.add_route('robots', '/robots.txt')
373 config.add_route('robots', '/robots.txt')
374
374
375 config.add_static_view(
375 config.add_static_view(
376 '_static/deform', 'deform:static')
376 '_static/deform', 'deform:static')
377 config.add_static_view(
377 config.add_static_view(
378 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
378 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
379
379
380
380
381 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
381 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
382 """
382 """
383 Apply outer WSGI middlewares around the application.
383 Apply outer WSGI middlewares around the application.
384
384
385 Part of this has been moved up from the Pylons layer, so that the
385 Part of this has been moved up from the Pylons layer, so that the
386 data is also available if old Pylons code is hit through an already ported
386 data is also available if old Pylons code is hit through an already ported
387 view.
387 view.
388 """
388 """
389 settings = config.registry.settings
389 settings = config.registry.settings
390
390
391 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
391 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
392 pyramid_app = HttpsFixup(pyramid_app, settings)
392 pyramid_app = HttpsFixup(pyramid_app, settings)
393
393
394 # Add RoutesMiddleware to support the pylons compatibility tween during
394 # Add RoutesMiddleware to support the pylons compatibility tween during
395 # migration to pyramid.
395 # migration to pyramid.
396
396
397 # TODO(marcink): remove after migration to pyramid
397 # TODO(marcink): remove after migration to pyramid
398 if hasattr(config.registry, '_pylons_compat_config'):
398 if hasattr(config.registry, '_pylons_compat_config'):
399 routes_map = config.registry._pylons_compat_config['routes.map']
399 routes_map = config.registry._pylons_compat_config['routes.map']
400 pyramid_app = SkippableRoutesMiddleware(
400 pyramid_app = SkippableRoutesMiddleware(
401 pyramid_app, routes_map,
401 pyramid_app, routes_map,
402 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
402 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
403
403
404 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
404 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
405
405
406 if settings['gzip_responses']:
406 if settings['gzip_responses']:
407 pyramid_app = make_gzip_middleware(
407 pyramid_app = make_gzip_middleware(
408 pyramid_app, settings, compress_level=1)
408 pyramid_app, settings, compress_level=1)
409
409
410 # this should be the outer most middleware in the wsgi stack since
410 # this should be the outer most middleware in the wsgi stack since
411 # middleware like Routes make database calls
411 # middleware like Routes make database calls
412 def pyramid_app_with_cleanup(environ, start_response):
412 def pyramid_app_with_cleanup(environ, start_response):
413 try:
413 try:
414 return pyramid_app(environ, start_response)
414 return pyramid_app(environ, start_response)
415 finally:
415 finally:
416 # Dispose current database session and rollback uncommitted
416 # Dispose current database session and rollback uncommitted
417 # transactions.
417 # transactions.
418 meta.Session.remove()
418 meta.Session.remove()
419
419
420 # In a single threaded mode server, on non sqlite db we should have
420 # In a single threaded mode server, on non sqlite db we should have
421 # '0 Current Checked out connections' at the end of a request,
421 # '0 Current Checked out connections' at the end of a request,
422 # if not, then something, somewhere is leaving a connection open
422 # if not, then something, somewhere is leaving a connection open
423 pool = meta.Base.metadata.bind.engine.pool
423 pool = meta.Base.metadata.bind.engine.pool
424 log.debug('sa pool status: %s', pool.status())
424 log.debug('sa pool status: %s', pool.status())
425
425
426 return pyramid_app_with_cleanup
426 return pyramid_app_with_cleanup
427
427
428
428
429 def sanitize_settings_and_apply_defaults(settings):
429 def sanitize_settings_and_apply_defaults(settings):
430 """
430 """
431 Applies settings defaults and does all type conversion.
431 Applies settings defaults and does all type conversion.
432
432
433 We would move all settings parsing and preparation into this place, so that
433 We would move all settings parsing and preparation into this place, so that
434 we have only one place left which deals with this part. The remaining parts
434 we have only one place left which deals with this part. The remaining parts
435 of the application would start to rely fully on well prepared settings.
435 of the application would start to rely fully on well prepared settings.
436
436
437 This piece would later be split up per topic to avoid a big fat monster
437 This piece would later be split up per topic to avoid a big fat monster
438 function.
438 function.
439 """
439 """
440
440
441 # Pyramid's mako renderer has to search in the templates folder so that the
441 # Pyramid's mako renderer has to search in the templates folder so that the
442 # old templates still work. Ported and new templates are expected to use
442 # old templates still work. Ported and new templates are expected to use
443 # real asset specifications for the includes.
443 # real asset specifications for the includes.
444 mako_directories = settings.setdefault('mako.directories', [
444 mako_directories = settings.setdefault('mako.directories', [
445 # Base templates of the original Pylons application
445 # Base templates of the original Pylons application
446 'rhodecode:templates',
446 'rhodecode:templates',
447 ])
447 ])
448 log.debug(
448 log.debug(
449 "Using the following Mako template directories: %s",
449 "Using the following Mako template directories: %s",
450 mako_directories)
450 mako_directories)
451
451
452 # Default includes, possible to change as a user
452 # Default includes, possible to change as a user
453 pyramid_includes = settings.setdefault('pyramid.includes', [
453 pyramid_includes = settings.setdefault('pyramid.includes', [
454 'rhodecode.lib.middleware.request_wrapper',
454 'rhodecode.lib.middleware.request_wrapper',
455 ])
455 ])
456 log.debug(
456 log.debug(
457 "Using the following pyramid.includes: %s",
457 "Using the following pyramid.includes: %s",
458 pyramid_includes)
458 pyramid_includes)
459
459
460 # TODO: johbo: Re-think this, usually the call to config.include
460 # TODO: johbo: Re-think this, usually the call to config.include
461 # should allow to pass in a prefix.
461 # should allow to pass in a prefix.
462 settings.setdefault('rhodecode.api.url', '/_admin/api')
462 settings.setdefault('rhodecode.api.url', '/_admin/api')
463
463
464 # Sanitize generic settings.
464 # Sanitize generic settings.
465 _list_setting(settings, 'default_encoding', 'UTF-8')
465 _list_setting(settings, 'default_encoding', 'UTF-8')
466 _bool_setting(settings, 'is_test', 'false')
466 _bool_setting(settings, 'is_test', 'false')
467 _bool_setting(settings, 'gzip_responses', 'false')
467 _bool_setting(settings, 'gzip_responses', 'false')
468
468
469 # Call split out functions that sanitize settings for each topic.
469 # Call split out functions that sanitize settings for each topic.
470 _sanitize_appenlight_settings(settings)
470 _sanitize_appenlight_settings(settings)
471 _sanitize_vcs_settings(settings)
471 _sanitize_vcs_settings(settings)
472
472
473 return settings
473 return settings
474
474
475
475
476 def _sanitize_appenlight_settings(settings):
476 def _sanitize_appenlight_settings(settings):
477 _bool_setting(settings, 'appenlight', 'false')
477 _bool_setting(settings, 'appenlight', 'false')
478
478
479
479
480 def _sanitize_vcs_settings(settings):
480 def _sanitize_vcs_settings(settings):
481 """
481 """
482 Applies settings defaults and does type conversion for all VCS related
482 Applies settings defaults and does type conversion for all VCS related
483 settings.
483 settings.
484 """
484 """
485 _string_setting(settings, 'vcs.svn.compatible_version', '')
485 _string_setting(settings, 'vcs.svn.compatible_version', '')
486 _string_setting(settings, 'git_rev_filter', '--all')
486 _string_setting(settings, 'git_rev_filter', '--all')
487 _string_setting(settings, 'vcs.hooks.protocol', 'http')
487 _string_setting(settings, 'vcs.hooks.protocol', 'http')
488 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
488 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
489 _string_setting(settings, 'vcs.server', '')
489 _string_setting(settings, 'vcs.server', '')
490 _string_setting(settings, 'vcs.server.log_level', 'debug')
490 _string_setting(settings, 'vcs.server.log_level', 'debug')
491 _string_setting(settings, 'vcs.server.protocol', 'http')
491 _string_setting(settings, 'vcs.server.protocol', 'http')
492 _bool_setting(settings, 'startup.import_repos', 'false')
492 _bool_setting(settings, 'startup.import_repos', 'false')
493 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
493 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
494 _bool_setting(settings, 'vcs.server.enable', 'true')
494 _bool_setting(settings, 'vcs.server.enable', 'true')
495 _bool_setting(settings, 'vcs.start_server', 'false')
495 _bool_setting(settings, 'vcs.start_server', 'false')
496 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
496 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
497 _int_setting(settings, 'vcs.connection_timeout', 3600)
497 _int_setting(settings, 'vcs.connection_timeout', 3600)
498
498
499 # Support legacy values of vcs.scm_app_implementation. Legacy
499 # Support legacy values of vcs.scm_app_implementation. Legacy
500 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
500 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
501 # which is now mapped to 'http'.
501 # which is now mapped to 'http'.
502 scm_app_impl = settings['vcs.scm_app_implementation']
502 scm_app_impl = settings['vcs.scm_app_implementation']
503 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
503 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
504 settings['vcs.scm_app_implementation'] = 'http'
504 settings['vcs.scm_app_implementation'] = 'http'
505
505
506
506
507 def _int_setting(settings, name, default):
507 def _int_setting(settings, name, default):
508 settings[name] = int(settings.get(name, default))
508 settings[name] = int(settings.get(name, default))
509
509
510
510
511 def _bool_setting(settings, name, default):
511 def _bool_setting(settings, name, default):
512 input = settings.get(name, default)
512 input = settings.get(name, default)
513 if isinstance(input, unicode):
513 if isinstance(input, unicode):
514 input = input.encode('utf8')
514 input = input.encode('utf8')
515 settings[name] = asbool(input)
515 settings[name] = asbool(input)
516
516
517
517
518 def _list_setting(settings, name, default):
518 def _list_setting(settings, name, default):
519 raw_value = settings.get(name, default)
519 raw_value = settings.get(name, default)
520
520
521 old_separator = ','
521 old_separator = ','
522 if old_separator in raw_value:
522 if old_separator in raw_value:
523 # If we get a comma separated list, pass it to our own function.
523 # If we get a comma separated list, pass it to our own function.
524 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
524 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
525 else:
525 else:
526 # Otherwise we assume it uses pyramids space/newline separation.
526 # Otherwise we assume it uses pyramids space/newline separation.
527 settings[name] = aslist(raw_value)
527 settings[name] = aslist(raw_value)
528
528
529
529
530 def _string_setting(settings, name, default, lower=True):
530 def _string_setting(settings, name, default, lower=True):
531 value = settings.get(name, default)
531 value = settings.get(name, default)
532 if lower:
532 if lower:
533 value = value.lower()
533 value = value.lower()
534 settings[name] = value
534 settings[name] = value
@@ -1,62 +1,62 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2012-2017 RhodeCode GmbH
3 # Copyright (C) 2012-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 rhodecode.integrations.registry import IntegrationTypeRegistry
23 from rhodecode.integrations.registry import IntegrationTypeRegistry
24 from rhodecode.integrations.types import webhook, slack, hipchat, email
24 from rhodecode.integrations.types import webhook, slack, hipchat, email
25
25
26 log = logging.getLogger(__name__)
26 log = logging.getLogger(__name__)
27
27
28
28
29 # TODO: dan: This is currently global until we figure out what to do about
29 # TODO: dan: This is currently global until we figure out what to do about
30 # VCS's not having a pyramid context - move it to pyramid app configuration
30 # VCS's not having a pyramid context - move it to pyramid app configuration
31 # includeme level later to allow per instance integration setup
31 # includeme level later to allow per instance integration setup
32 integration_type_registry = IntegrationTypeRegistry()
32 integration_type_registry = IntegrationTypeRegistry()
33
33
34 integration_type_registry.register_integration_type(
34 integration_type_registry.register_integration_type(
35 webhook.WebhookIntegrationType)
35 webhook.WebhookIntegrationType)
36 integration_type_registry.register_integration_type(
36 integration_type_registry.register_integration_type(
37 slack.SlackIntegrationType)
37 slack.SlackIntegrationType)
38 integration_type_registry.register_integration_type(
38 integration_type_registry.register_integration_type(
39 hipchat.HipchatIntegrationType)
39 hipchat.HipchatIntegrationType)
40 integration_type_registry.register_integration_type(
40 integration_type_registry.register_integration_type(
41 email.EmailIntegrationType)
41 email.EmailIntegrationType)
42
42
43
43
44 def integrations_event_handler(event):
44 def integrations_event_handler(event):
45 """
45 """
46 Takes an event and passes it to all enabled integrations
46 Takes an event and passes it to all enabled integrations
47 """
47 """
48 from rhodecode.model.integration import IntegrationModel
48 from rhodecode.model.integration import IntegrationModel
49
49
50 integration_model = IntegrationModel()
50 integration_model = IntegrationModel()
51 integrations = integration_model.get_for_event(event)
51 integrations = integration_model.get_for_event(event)
52 for integration in integrations:
52 for integration in integrations:
53 try:
53 try:
54 integration_model.send_event(integration, event)
54 integration_model.send_event(integration, event)
55 except Exception:
55 except Exception:
56 log.exception(
56 log.exception(
57 'failure occured when sending event %s to integration %s' % (
57 'failure occurred when sending event %s to integration %s' % (
58 event, integration))
58 event, integration))
59
59
60
60
61 def includeme(config):
61 def includeme(config):
62 config.include('rhodecode.integrations.routes')
62 config.include('rhodecode.integrations.routes')
@@ -1,1994 +1,1997 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-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 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import inspect
26 import inspect
27 import collections
27 import collections
28 import fnmatch
28 import fnmatch
29 import hashlib
29 import hashlib
30 import itertools
30 import itertools
31 import logging
31 import logging
32 import random
32 import random
33 import traceback
33 import traceback
34 from functools import wraps
34 from functools import wraps
35
35
36 import ipaddress
36 import ipaddress
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
38 from pylons.i18n.translation import _
38 from pylons.i18n.translation import _
39 # NOTE(marcink): this has to be removed only after pyramid migration,
39 # NOTE(marcink): this has to be removed only after pyramid migration,
40 # replace with _ = request.translate
40 # replace with _ = request.translate
41 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm.exc import ObjectDeletedError
42 from sqlalchemy.orm import joinedload
42 from sqlalchemy.orm import joinedload
43 from zope.cachedescriptors.property import Lazy as LazyProperty
43 from zope.cachedescriptors.property import Lazy as LazyProperty
44
44
45 import rhodecode
45 import rhodecode
46 from rhodecode.model import meta
46 from rhodecode.model import meta
47 from rhodecode.model.meta import Session
47 from rhodecode.model.meta import Session
48 from rhodecode.model.user import UserModel
48 from rhodecode.model.user import UserModel
49 from rhodecode.model.db import (
49 from rhodecode.model.db import (
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 UserIpMap, UserApiKeys, RepoGroup)
51 UserIpMap, UserApiKeys, RepoGroup)
52 from rhodecode.lib import caches
52 from rhodecode.lib import caches
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 from rhodecode.lib.utils import (
54 from rhodecode.lib.utils import (
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 from rhodecode.lib.caching_query import FromCache
56 from rhodecode.lib.caching_query import FromCache
57
57
58
58
59 if rhodecode.is_unix:
59 if rhodecode.is_unix:
60 import bcrypt
60 import bcrypt
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64 csrf_token_key = "csrf_token"
64 csrf_token_key = "csrf_token"
65
65
66
66
67 class PasswordGenerator(object):
67 class PasswordGenerator(object):
68 """
68 """
69 This is a simple class for generating password from different sets of
69 This is a simple class for generating password from different sets of
70 characters
70 characters
71 usage::
71 usage::
72
72
73 passwd_gen = PasswordGenerator()
73 passwd_gen = PasswordGenerator()
74 #print 8-letter password containing only big and small letters
74 #print 8-letter password containing only big and small letters
75 of alphabet
75 of alphabet
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 """
77 """
78 ALPHABETS_NUM = r'''1234567890'''
78 ALPHABETS_NUM = r'''1234567890'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88
88
89 def __init__(self, passwd=''):
89 def __init__(self, passwd=''):
90 self.passwd = passwd
90 self.passwd = passwd
91
91
92 def gen_password(self, length, type_=None):
92 def gen_password(self, length, type_=None):
93 if type_ is None:
93 if type_ is None:
94 type_ = self.ALPHABETS_FULL
94 type_ = self.ALPHABETS_FULL
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 return self.passwd
96 return self.passwd
97
97
98
98
99 class _RhodeCodeCryptoBase(object):
99 class _RhodeCodeCryptoBase(object):
100 ENC_PREF = None
100 ENC_PREF = None
101
101
102 def hash_create(self, str_):
102 def hash_create(self, str_):
103 """
103 """
104 hash the string using
104 hash the string using
105
105
106 :param str_: password to hash
106 :param str_: password to hash
107 """
107 """
108 raise NotImplementedError
108 raise NotImplementedError
109
109
110 def hash_check_with_upgrade(self, password, hashed):
110 def hash_check_with_upgrade(self, password, hashed):
111 """
111 """
112 Returns tuple in which first element is boolean that states that
112 Returns tuple in which first element is boolean that states that
113 given password matches it's hashed version, and the second is new hash
113 given password matches it's hashed version, and the second is new hash
114 of the password, in case this password should be migrated to new
114 of the password, in case this password should be migrated to new
115 cipher.
115 cipher.
116 """
116 """
117 checked_hash = self.hash_check(password, hashed)
117 checked_hash = self.hash_check(password, hashed)
118 return checked_hash, None
118 return checked_hash, None
119
119
120 def hash_check(self, password, hashed):
120 def hash_check(self, password, hashed):
121 """
121 """
122 Checks matching password with it's hashed value.
122 Checks matching password with it's hashed value.
123
123
124 :param password: password
124 :param password: password
125 :param hashed: password in hashed form
125 :param hashed: password in hashed form
126 """
126 """
127 raise NotImplementedError
127 raise NotImplementedError
128
128
129 def _assert_bytes(self, value):
129 def _assert_bytes(self, value):
130 """
130 """
131 Passing in an `unicode` object can lead to hard to detect issues
131 Passing in an `unicode` object can lead to hard to detect issues
132 if passwords contain non-ascii characters. Doing a type check
132 if passwords contain non-ascii characters. Doing a type check
133 during runtime, so that such mistakes are detected early on.
133 during runtime, so that such mistakes are detected early on.
134 """
134 """
135 if not isinstance(value, str):
135 if not isinstance(value, str):
136 raise TypeError(
136 raise TypeError(
137 "Bytestring required as input, got %r." % (value, ))
137 "Bytestring required as input, got %r." % (value, ))
138
138
139
139
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 ENC_PREF = ('$2a$10', '$2b$10')
141 ENC_PREF = ('$2a$10', '$2b$10')
142
142
143 def hash_create(self, str_):
143 def hash_create(self, str_):
144 self._assert_bytes(str_)
144 self._assert_bytes(str_)
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146
146
147 def hash_check_with_upgrade(self, password, hashed):
147 def hash_check_with_upgrade(self, password, hashed):
148 """
148 """
149 Returns tuple in which first element is boolean that states that
149 Returns tuple in which first element is boolean that states that
150 given password matches it's hashed version, and the second is new hash
150 given password matches it's hashed version, and the second is new hash
151 of the password, in case this password should be migrated to new
151 of the password, in case this password should be migrated to new
152 cipher.
152 cipher.
153
153
154 This implements special upgrade logic which works like that:
154 This implements special upgrade logic which works like that:
155 - check if the given password == bcrypted hash, if yes then we
155 - check if the given password == bcrypted hash, if yes then we
156 properly used password and it was already in bcrypt. Proceed
156 properly used password and it was already in bcrypt. Proceed
157 without any changes
157 without any changes
158 - if bcrypt hash check is not working try with sha256. If hash compare
158 - if bcrypt hash check is not working try with sha256. If hash compare
159 is ok, it means we using correct but old hashed password. indicate
159 is ok, it means we using correct but old hashed password. indicate
160 hash change and proceed
160 hash change and proceed
161 """
161 """
162
162
163 new_hash = None
163 new_hash = None
164
164
165 # regular pw check
165 # regular pw check
166 password_match_bcrypt = self.hash_check(password, hashed)
166 password_match_bcrypt = self.hash_check(password, hashed)
167
167
168 # now we want to know if the password was maybe from sha256
168 # now we want to know if the password was maybe from sha256
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 if not password_match_bcrypt:
170 if not password_match_bcrypt:
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 new_hash = self.hash_create(password) # make new bcrypt hash
172 new_hash = self.hash_create(password) # make new bcrypt hash
173 password_match_bcrypt = True
173 password_match_bcrypt = True
174
174
175 return password_match_bcrypt, new_hash
175 return password_match_bcrypt, new_hash
176
176
177 def hash_check(self, password, hashed):
177 def hash_check(self, password, hashed):
178 """
178 """
179 Checks matching password with it's hashed value.
179 Checks matching password with it's hashed value.
180
180
181 :param password: password
181 :param password: password
182 :param hashed: password in hashed form
182 :param hashed: password in hashed form
183 """
183 """
184 self._assert_bytes(password)
184 self._assert_bytes(password)
185 try:
185 try:
186 return bcrypt.hashpw(password, hashed) == hashed
186 return bcrypt.hashpw(password, hashed) == hashed
187 except ValueError as e:
187 except ValueError as e:
188 # we're having a invalid salt here probably, we should not crash
188 # we're having a invalid salt here probably, we should not crash
189 # just return with False as it would be a wrong password.
189 # just return with False as it would be a wrong password.
190 log.debug('Failed to check password hash using bcrypt %s',
190 log.debug('Failed to check password hash using bcrypt %s',
191 safe_str(e))
191 safe_str(e))
192
192
193 return False
193 return False
194
194
195
195
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 ENC_PREF = '_'
197 ENC_PREF = '_'
198
198
199 def hash_create(self, str_):
199 def hash_create(self, str_):
200 self._assert_bytes(str_)
200 self._assert_bytes(str_)
201 return hashlib.sha256(str_).hexdigest()
201 return hashlib.sha256(str_).hexdigest()
202
202
203 def hash_check(self, password, hashed):
203 def hash_check(self, password, hashed):
204 """
204 """
205 Checks matching password with it's hashed value.
205 Checks matching password with it's hashed value.
206
206
207 :param password: password
207 :param password: password
208 :param hashed: password in hashed form
208 :param hashed: password in hashed form
209 """
209 """
210 self._assert_bytes(password)
210 self._assert_bytes(password)
211 return hashlib.sha256(password).hexdigest() == hashed
211 return hashlib.sha256(password).hexdigest() == hashed
212
212
213
213
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 ENC_PREF = '_'
215 ENC_PREF = '_'
216
216
217 def hash_create(self, str_):
217 def hash_create(self, str_):
218 self._assert_bytes(str_)
218 self._assert_bytes(str_)
219 return hashlib.md5(str_).hexdigest()
219 return hashlib.md5(str_).hexdigest()
220
220
221 def hash_check(self, password, hashed):
221 def hash_check(self, password, hashed):
222 """
222 """
223 Checks matching password with it's hashed value.
223 Checks matching password with it's hashed value.
224
224
225 :param password: password
225 :param password: password
226 :param hashed: password in hashed form
226 :param hashed: password in hashed form
227 """
227 """
228 self._assert_bytes(password)
228 self._assert_bytes(password)
229 return hashlib.md5(password).hexdigest() == hashed
229 return hashlib.md5(password).hexdigest() == hashed
230
230
231
231
232 def crypto_backend():
232 def crypto_backend():
233 """
233 """
234 Return the matching crypto backend.
234 Return the matching crypto backend.
235
235
236 Selection is based on if we run tests or not, we pick md5 backend to run
236 Selection is based on if we run tests or not, we pick md5 backend to run
237 tests faster since BCRYPT is expensive to calculate
237 tests faster since BCRYPT is expensive to calculate
238 """
238 """
239 if rhodecode.is_test:
239 if rhodecode.is_test:
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 else:
241 else:
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243
243
244 return RhodeCodeCrypto
244 return RhodeCodeCrypto
245
245
246
246
247 def get_crypt_password(password):
247 def get_crypt_password(password):
248 """
248 """
249 Create the hash of `password` with the active crypto backend.
249 Create the hash of `password` with the active crypto backend.
250
250
251 :param password: The cleartext password.
251 :param password: The cleartext password.
252 :type password: unicode
252 :type password: unicode
253 """
253 """
254 password = safe_str(password)
254 password = safe_str(password)
255 return crypto_backend().hash_create(password)
255 return crypto_backend().hash_create(password)
256
256
257
257
258 def check_password(password, hashed):
258 def check_password(password, hashed):
259 """
259 """
260 Check if the value in `password` matches the hash in `hashed`.
260 Check if the value in `password` matches the hash in `hashed`.
261
261
262 :param password: The cleartext password.
262 :param password: The cleartext password.
263 :type password: unicode
263 :type password: unicode
264
264
265 :param hashed: The expected hashed version of the password.
265 :param hashed: The expected hashed version of the password.
266 :type hashed: The hash has to be passed in in text representation.
266 :type hashed: The hash has to be passed in in text representation.
267 """
267 """
268 password = safe_str(password)
268 password = safe_str(password)
269 return crypto_backend().hash_check(password, hashed)
269 return crypto_backend().hash_check(password, hashed)
270
270
271
271
272 def generate_auth_token(data, salt=None):
272 def generate_auth_token(data, salt=None):
273 """
273 """
274 Generates API KEY from given string
274 Generates API KEY from given string
275 """
275 """
276
276
277 if salt is None:
277 if salt is None:
278 salt = os.urandom(16)
278 salt = os.urandom(16)
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280
280
281
281
282 class CookieStoreWrapper(object):
282 class CookieStoreWrapper(object):
283
283
284 def __init__(self, cookie_store):
284 def __init__(self, cookie_store):
285 self.cookie_store = cookie_store
285 self.cookie_store = cookie_store
286
286
287 def __repr__(self):
287 def __repr__(self):
288 return 'CookieStore<%s>' % (self.cookie_store)
288 return 'CookieStore<%s>' % (self.cookie_store)
289
289
290 def get(self, key, other=None):
290 def get(self, key, other=None):
291 if isinstance(self.cookie_store, dict):
291 if isinstance(self.cookie_store, dict):
292 return self.cookie_store.get(key, other)
292 return self.cookie_store.get(key, other)
293 elif isinstance(self.cookie_store, AuthUser):
293 elif isinstance(self.cookie_store, AuthUser):
294 return self.cookie_store.__dict__.get(key, other)
294 return self.cookie_store.__dict__.get(key, other)
295
295
296
296
297 def _cached_perms_data(user_id, scope, user_is_admin,
297 def _cached_perms_data(user_id, scope, user_is_admin,
298 user_inherit_default_permissions, explicit, algo):
298 user_inherit_default_permissions, explicit, algo):
299
299
300 permissions = PermissionCalculator(
300 permissions = PermissionCalculator(
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
302 explicit, algo)
302 explicit, algo)
303 return permissions.calculate()
303 return permissions.calculate()
304
304
305
305
306 class PermOrigin(object):
306 class PermOrigin(object):
307 ADMIN = 'superadmin'
307 ADMIN = 'superadmin'
308
308
309 REPO_USER = 'user:%s'
309 REPO_USER = 'user:%s'
310 REPO_USERGROUP = 'usergroup:%s'
310 REPO_USERGROUP = 'usergroup:%s'
311 REPO_OWNER = 'repo.owner'
311 REPO_OWNER = 'repo.owner'
312 REPO_DEFAULT = 'repo.default'
312 REPO_DEFAULT = 'repo.default'
313 REPO_PRIVATE = 'repo.private'
313 REPO_PRIVATE = 'repo.private'
314
314
315 REPOGROUP_USER = 'user:%s'
315 REPOGROUP_USER = 'user:%s'
316 REPOGROUP_USERGROUP = 'usergroup:%s'
316 REPOGROUP_USERGROUP = 'usergroup:%s'
317 REPOGROUP_OWNER = 'group.owner'
317 REPOGROUP_OWNER = 'group.owner'
318 REPOGROUP_DEFAULT = 'group.default'
318 REPOGROUP_DEFAULT = 'group.default'
319
319
320 USERGROUP_USER = 'user:%s'
320 USERGROUP_USER = 'user:%s'
321 USERGROUP_USERGROUP = 'usergroup:%s'
321 USERGROUP_USERGROUP = 'usergroup:%s'
322 USERGROUP_OWNER = 'usergroup.owner'
322 USERGROUP_OWNER = 'usergroup.owner'
323 USERGROUP_DEFAULT = 'usergroup.default'
323 USERGROUP_DEFAULT = 'usergroup.default'
324
324
325
325
326 class PermOriginDict(dict):
326 class PermOriginDict(dict):
327 """
327 """
328 A special dict used for tracking permissions along with their origins.
328 A special dict used for tracking permissions along with their origins.
329
329
330 `__setitem__` has been overridden to expect a tuple(perm, origin)
330 `__setitem__` has been overridden to expect a tuple(perm, origin)
331 `__getitem__` will return only the perm
331 `__getitem__` will return only the perm
332 `.perm_origin_stack` will return the stack of (perm, origin) set per key
332 `.perm_origin_stack` will return the stack of (perm, origin) set per key
333
333
334 >>> perms = PermOriginDict()
334 >>> perms = PermOriginDict()
335 >>> perms['resource'] = 'read', 'default'
335 >>> perms['resource'] = 'read', 'default'
336 >>> perms['resource']
336 >>> perms['resource']
337 'read'
337 'read'
338 >>> perms['resource'] = 'write', 'admin'
338 >>> perms['resource'] = 'write', 'admin'
339 >>> perms['resource']
339 >>> perms['resource']
340 'write'
340 'write'
341 >>> perms.perm_origin_stack
341 >>> perms.perm_origin_stack
342 {'resource': [('read', 'default'), ('write', 'admin')]}
342 {'resource': [('read', 'default'), ('write', 'admin')]}
343 """
343 """
344
344
345 def __init__(self, *args, **kw):
345 def __init__(self, *args, **kw):
346 dict.__init__(self, *args, **kw)
346 dict.__init__(self, *args, **kw)
347 self.perm_origin_stack = {}
347 self.perm_origin_stack = {}
348
348
349 def __setitem__(self, key, (perm, origin)):
349 def __setitem__(self, key, (perm, origin)):
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
351 dict.__setitem__(self, key, perm)
351 dict.__setitem__(self, key, perm)
352
352
353
353
354 class PermissionCalculator(object):
354 class PermissionCalculator(object):
355
355
356 def __init__(
356 def __init__(
357 self, user_id, scope, user_is_admin,
357 self, user_id, scope, user_is_admin,
358 user_inherit_default_permissions, explicit, algo):
358 user_inherit_default_permissions, explicit, algo):
359 self.user_id = user_id
359 self.user_id = user_id
360 self.user_is_admin = user_is_admin
360 self.user_is_admin = user_is_admin
361 self.inherit_default_permissions = user_inherit_default_permissions
361 self.inherit_default_permissions = user_inherit_default_permissions
362 self.explicit = explicit
362 self.explicit = explicit
363 self.algo = algo
363 self.algo = algo
364
364
365 scope = scope or {}
365 scope = scope or {}
366 self.scope_repo_id = scope.get('repo_id')
366 self.scope_repo_id = scope.get('repo_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
369
369
370 self.default_user_id = User.get_default_user(cache=True).user_id
370 self.default_user_id = User.get_default_user(cache=True).user_id
371
371
372 self.permissions_repositories = PermOriginDict()
372 self.permissions_repositories = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
375 self.permissions_global = set()
375 self.permissions_global = set()
376
376
377 self.default_repo_perms = Permission.get_default_repo_perms(
377 self.default_repo_perms = Permission.get_default_repo_perms(
378 self.default_user_id, self.scope_repo_id)
378 self.default_user_id, self.scope_repo_id)
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
380 self.default_user_id, self.scope_repo_group_id)
380 self.default_user_id, self.scope_repo_group_id)
381 self.default_user_group_perms = \
381 self.default_user_group_perms = \
382 Permission.get_default_user_group_perms(
382 Permission.get_default_user_group_perms(
383 self.default_user_id, self.scope_user_group_id)
383 self.default_user_id, self.scope_user_group_id)
384
384
385 def calculate(self):
385 def calculate(self):
386 if self.user_is_admin:
386 if self.user_is_admin:
387 return self._admin_permissions()
387 return self._admin_permissions()
388
388
389 self._calculate_global_default_permissions()
389 self._calculate_global_default_permissions()
390 self._calculate_global_permissions()
390 self._calculate_global_permissions()
391 self._calculate_default_permissions()
391 self._calculate_default_permissions()
392 self._calculate_repository_permissions()
392 self._calculate_repository_permissions()
393 self._calculate_repository_group_permissions()
393 self._calculate_repository_group_permissions()
394 self._calculate_user_group_permissions()
394 self._calculate_user_group_permissions()
395 return self._permission_structure()
395 return self._permission_structure()
396
396
397 def _admin_permissions(self):
397 def _admin_permissions(self):
398 """
398 """
399 admin user have all default rights for repositories
399 admin user have all default rights for repositories
400 and groups set to admin
400 and groups set to admin
401 """
401 """
402 self.permissions_global.add('hg.admin')
402 self.permissions_global.add('hg.admin')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
404
404
405 # repositories
405 # repositories
406 for perm in self.default_repo_perms:
406 for perm in self.default_repo_perms:
407 r_k = perm.UserRepoToPerm.repository.repo_name
407 r_k = perm.UserRepoToPerm.repository.repo_name
408 p = 'repository.admin'
408 p = 'repository.admin'
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
410
410
411 # repository groups
411 # repository groups
412 for perm in self.default_repo_groups_perms:
412 for perm in self.default_repo_groups_perms:
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
414 p = 'group.admin'
414 p = 'group.admin'
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
416
416
417 # user groups
417 # user groups
418 for perm in self.default_user_group_perms:
418 for perm in self.default_user_group_perms:
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
420 p = 'usergroup.admin'
420 p = 'usergroup.admin'
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
422
422
423 return self._permission_structure()
423 return self._permission_structure()
424
424
425 def _calculate_global_default_permissions(self):
425 def _calculate_global_default_permissions(self):
426 """
426 """
427 global permissions taken from the default user
427 global permissions taken from the default user
428 """
428 """
429 default_global_perms = UserToPerm.query()\
429 default_global_perms = UserToPerm.query()\
430 .filter(UserToPerm.user_id == self.default_user_id)\
430 .filter(UserToPerm.user_id == self.default_user_id)\
431 .options(joinedload(UserToPerm.permission))
431 .options(joinedload(UserToPerm.permission))
432
432
433 for perm in default_global_perms:
433 for perm in default_global_perms:
434 self.permissions_global.add(perm.permission.permission_name)
434 self.permissions_global.add(perm.permission.permission_name)
435
435
436 def _calculate_global_permissions(self):
436 def _calculate_global_permissions(self):
437 """
437 """
438 Set global system permissions with user permissions or permissions
438 Set global system permissions with user permissions or permissions
439 taken from the user groups of the current user.
439 taken from the user groups of the current user.
440
440
441 The permissions include repo creating, repo group creating, forking
441 The permissions include repo creating, repo group creating, forking
442 etc.
442 etc.
443 """
443 """
444
444
445 # now we read the defined permissions and overwrite what we have set
445 # now we read the defined permissions and overwrite what we have set
446 # before those can be configured from groups or users explicitly.
446 # before those can be configured from groups or users explicitly.
447
447
448 # TODO: johbo: This seems to be out of sync, find out the reason
448 # TODO: johbo: This seems to be out of sync, find out the reason
449 # for the comment below and update it.
449 # for the comment below and update it.
450
450
451 # In case we want to extend this list we should be always in sync with
451 # In case we want to extend this list we should be always in sync with
452 # User.DEFAULT_USER_PERMISSIONS definitions
452 # User.DEFAULT_USER_PERMISSIONS definitions
453 _configurable = frozenset([
453 _configurable = frozenset([
454 'hg.fork.none', 'hg.fork.repository',
454 'hg.fork.none', 'hg.fork.repository',
455 'hg.create.none', 'hg.create.repository',
455 'hg.create.none', 'hg.create.repository',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
458 'hg.create.write_on_repogroup.false',
458 'hg.create.write_on_repogroup.false',
459 'hg.create.write_on_repogroup.true',
459 'hg.create.write_on_repogroup.true',
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
461 ])
461 ])
462
462
463 # USER GROUPS comes first user group global permissions
463 # USER GROUPS comes first user group global permissions
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
465 .options(joinedload(UserGroupToPerm.permission))\
465 .options(joinedload(UserGroupToPerm.permission))\
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
467 UserGroupMember.users_group_id))\
467 UserGroupMember.users_group_id))\
468 .filter(UserGroupMember.user_id == self.user_id)\
468 .filter(UserGroupMember.user_id == self.user_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
470 .all()
470 .all()
471
471
472 # need to group here by groups since user can be in more than
472 # need to group here by groups since user can be in more than
473 # one group, so we get all groups
473 # one group, so we get all groups
474 _explicit_grouped_perms = [
474 _explicit_grouped_perms = [
475 [x, list(y)] for x, y in
475 [x, list(y)] for x, y in
476 itertools.groupby(user_perms_from_users_groups,
476 itertools.groupby(user_perms_from_users_groups,
477 lambda _x: _x.users_group)]
477 lambda _x: _x.users_group)]
478
478
479 for gr, perms in _explicit_grouped_perms:
479 for gr, perms in _explicit_grouped_perms:
480 # since user can be in multiple groups iterate over them and
480 # since user can be in multiple groups iterate over them and
481 # select the lowest permissions first (more explicit)
481 # select the lowest permissions first (more explicit)
482 # TODO: marcink: do this^^
482 # TODO: marcink: do this^^
483
483
484 # group doesn't inherit default permissions so we actually set them
484 # group doesn't inherit default permissions so we actually set them
485 if not gr.inherit_default_permissions:
485 if not gr.inherit_default_permissions:
486 # NEED TO IGNORE all previously set configurable permissions
486 # NEED TO IGNORE all previously set configurable permissions
487 # and replace them with explicitly set from this user
487 # and replace them with explicitly set from this user
488 # group permissions
488 # group permissions
489 self.permissions_global = self.permissions_global.difference(
489 self.permissions_global = self.permissions_global.difference(
490 _configurable)
490 _configurable)
491 for perm in perms:
491 for perm in perms:
492 self.permissions_global.add(perm.permission.permission_name)
492 self.permissions_global.add(perm.permission.permission_name)
493
493
494 # user explicit global permissions
494 # user explicit global permissions
495 user_perms = Session().query(UserToPerm)\
495 user_perms = Session().query(UserToPerm)\
496 .options(joinedload(UserToPerm.permission))\
496 .options(joinedload(UserToPerm.permission))\
497 .filter(UserToPerm.user_id == self.user_id).all()
497 .filter(UserToPerm.user_id == self.user_id).all()
498
498
499 if not self.inherit_default_permissions:
499 if not self.inherit_default_permissions:
500 # NEED TO IGNORE all configurable permissions and
500 # NEED TO IGNORE all configurable permissions and
501 # replace them with explicitly set from this user permissions
501 # replace them with explicitly set from this user permissions
502 self.permissions_global = self.permissions_global.difference(
502 self.permissions_global = self.permissions_global.difference(
503 _configurable)
503 _configurable)
504 for perm in user_perms:
504 for perm in user_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 def _calculate_default_permissions(self):
507 def _calculate_default_permissions(self):
508 """
508 """
509 Set default user permissions for repositories, repository groups
509 Set default user permissions for repositories, repository groups
510 taken from the default user.
510 taken from the default user.
511
511
512 Calculate inheritance of object permissions based on what we have now
512 Calculate inheritance of object permissions based on what we have now
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
514 explicitly set. Inherit is the opposite of .false being there.
514 explicitly set. Inherit is the opposite of .false being there.
515
515
516 .. note::
516 .. note::
517
517
518 the syntax is little bit odd but what we need to check here is
518 the syntax is little bit odd but what we need to check here is
519 the opposite of .false permission being in the list so even for
519 the opposite of .false permission being in the list so even for
520 inconsistent state when both .true/.false is there
520 inconsistent state when both .true/.false is there
521 .false is more important
521 .false is more important
522
522
523 """
523 """
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
525 in self.permissions_global)
525 in self.permissions_global)
526
526
527 # defaults for repositories, taken from `default` user permissions
527 # defaults for repositories, taken from `default` user permissions
528 # on given repo
528 # on given repo
529 for perm in self.default_repo_perms:
529 for perm in self.default_repo_perms:
530 r_k = perm.UserRepoToPerm.repository.repo_name
530 r_k = perm.UserRepoToPerm.repository.repo_name
531 o = PermOrigin.REPO_DEFAULT
531 o = PermOrigin.REPO_DEFAULT
532 if perm.Repository.private and not (
532 if perm.Repository.private and not (
533 perm.Repository.user_id == self.user_id):
533 perm.Repository.user_id == self.user_id):
534 # disable defaults for private repos,
534 # disable defaults for private repos,
535 p = 'repository.none'
535 p = 'repository.none'
536 o = PermOrigin.REPO_PRIVATE
536 o = PermOrigin.REPO_PRIVATE
537 elif perm.Repository.user_id == self.user_id:
537 elif perm.Repository.user_id == self.user_id:
538 # set admin if owner
538 # set admin if owner
539 p = 'repository.admin'
539 p = 'repository.admin'
540 o = PermOrigin.REPO_OWNER
540 o = PermOrigin.REPO_OWNER
541 else:
541 else:
542 p = perm.Permission.permission_name
542 p = perm.Permission.permission_name
543 # if we decide this user isn't inheriting permissions from
543 # if we decide this user isn't inheriting permissions from
544 # default user we set him to .none so only explicit
544 # default user we set him to .none so only explicit
545 # permissions work
545 # permissions work
546 if not user_inherit_object_permissions:
546 if not user_inherit_object_permissions:
547 p = 'repository.none'
547 p = 'repository.none'
548 self.permissions_repositories[r_k] = p, o
548 self.permissions_repositories[r_k] = p, o
549
549
550 # defaults for repository groups taken from `default` user permission
550 # defaults for repository groups taken from `default` user permission
551 # on given group
551 # on given group
552 for perm in self.default_repo_groups_perms:
552 for perm in self.default_repo_groups_perms:
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
554 o = PermOrigin.REPOGROUP_DEFAULT
554 o = PermOrigin.REPOGROUP_DEFAULT
555 if perm.RepoGroup.user_id == self.user_id:
555 if perm.RepoGroup.user_id == self.user_id:
556 # set admin if owner
556 # set admin if owner
557 p = 'group.admin'
557 p = 'group.admin'
558 o = PermOrigin.REPOGROUP_OWNER
558 o = PermOrigin.REPOGROUP_OWNER
559 else:
559 else:
560 p = perm.Permission.permission_name
560 p = perm.Permission.permission_name
561
561
562 # if we decide this user isn't inheriting permissions from default
562 # if we decide this user isn't inheriting permissions from default
563 # user we set him to .none so only explicit permissions work
563 # user we set him to .none so only explicit permissions work
564 if not user_inherit_object_permissions:
564 if not user_inherit_object_permissions:
565 p = 'group.none'
565 p = 'group.none'
566 self.permissions_repository_groups[rg_k] = p, o
566 self.permissions_repository_groups[rg_k] = p, o
567
567
568 # defaults for user groups taken from `default` user permission
568 # defaults for user groups taken from `default` user permission
569 # on given user group
569 # on given user group
570 for perm in self.default_user_group_perms:
570 for perm in self.default_user_group_perms:
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
572 o = PermOrigin.USERGROUP_DEFAULT
572 o = PermOrigin.USERGROUP_DEFAULT
573 if perm.UserGroup.user_id == self.user_id:
573 if perm.UserGroup.user_id == self.user_id:
574 # set admin if owner
574 # set admin if owner
575 p = 'usergroup.admin'
575 p = 'usergroup.admin'
576 o = PermOrigin.USERGROUP_OWNER
576 o = PermOrigin.USERGROUP_OWNER
577 else:
577 else:
578 p = perm.Permission.permission_name
578 p = perm.Permission.permission_name
579
579
580 # if we decide this user isn't inheriting permissions from default
580 # if we decide this user isn't inheriting permissions from default
581 # user we set him to .none so only explicit permissions work
581 # user we set him to .none so only explicit permissions work
582 if not user_inherit_object_permissions:
582 if not user_inherit_object_permissions:
583 p = 'usergroup.none'
583 p = 'usergroup.none'
584 self.permissions_user_groups[u_k] = p, o
584 self.permissions_user_groups[u_k] = p, o
585
585
586 def _calculate_repository_permissions(self):
586 def _calculate_repository_permissions(self):
587 """
587 """
588 Repository permissions for the current user.
588 Repository permissions for the current user.
589
589
590 Check if the user is part of user groups for this repository and
590 Check if the user is part of user groups for this repository and
591 fill in the permission from it. `_choose_permission` decides of which
591 fill in the permission from it. `_choose_permission` decides of which
592 permission should be selected based on selected method.
592 permission should be selected based on selected method.
593 """
593 """
594
594
595 # user group for repositories permissions
595 # user group for repositories permissions
596 user_repo_perms_from_user_group = Permission\
596 user_repo_perms_from_user_group = Permission\
597 .get_default_repo_perms_from_user_group(
597 .get_default_repo_perms_from_user_group(
598 self.user_id, self.scope_repo_id)
598 self.user_id, self.scope_repo_id)
599
599
600 multiple_counter = collections.defaultdict(int)
600 multiple_counter = collections.defaultdict(int)
601 for perm in user_repo_perms_from_user_group:
601 for perm in user_repo_perms_from_user_group:
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
604 multiple_counter[r_k] += 1
604 multiple_counter[r_k] += 1
605 p = perm.Permission.permission_name
605 p = perm.Permission.permission_name
606 o = PermOrigin.REPO_USERGROUP % ug_k
606 o = PermOrigin.REPO_USERGROUP % ug_k
607
607
608 if perm.Repository.user_id == self.user_id:
608 if perm.Repository.user_id == self.user_id:
609 # set admin if owner
609 # set admin if owner
610 p = 'repository.admin'
610 p = 'repository.admin'
611 o = PermOrigin.REPO_OWNER
611 o = PermOrigin.REPO_OWNER
612 else:
612 else:
613 if multiple_counter[r_k] > 1:
613 if multiple_counter[r_k] > 1:
614 cur_perm = self.permissions_repositories[r_k]
614 cur_perm = self.permissions_repositories[r_k]
615 p = self._choose_permission(p, cur_perm)
615 p = self._choose_permission(p, cur_perm)
616 self.permissions_repositories[r_k] = p, o
616 self.permissions_repositories[r_k] = p, o
617
617
618 # user explicit permissions for repositories, overrides any specified
618 # user explicit permissions for repositories, overrides any specified
619 # by the group permission
619 # by the group permission
620 user_repo_perms = Permission.get_default_repo_perms(
620 user_repo_perms = Permission.get_default_repo_perms(
621 self.user_id, self.scope_repo_id)
621 self.user_id, self.scope_repo_id)
622 for perm in user_repo_perms:
622 for perm in user_repo_perms:
623 r_k = perm.UserRepoToPerm.repository.repo_name
623 r_k = perm.UserRepoToPerm.repository.repo_name
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
625 # set admin if owner
625 # set admin if owner
626 if perm.Repository.user_id == self.user_id:
626 if perm.Repository.user_id == self.user_id:
627 p = 'repository.admin'
627 p = 'repository.admin'
628 o = PermOrigin.REPO_OWNER
628 o = PermOrigin.REPO_OWNER
629 else:
629 else:
630 p = perm.Permission.permission_name
630 p = perm.Permission.permission_name
631 if not self.explicit:
631 if not self.explicit:
632 cur_perm = self.permissions_repositories.get(
632 cur_perm = self.permissions_repositories.get(
633 r_k, 'repository.none')
633 r_k, 'repository.none')
634 p = self._choose_permission(p, cur_perm)
634 p = self._choose_permission(p, cur_perm)
635 self.permissions_repositories[r_k] = p, o
635 self.permissions_repositories[r_k] = p, o
636
636
637 def _calculate_repository_group_permissions(self):
637 def _calculate_repository_group_permissions(self):
638 """
638 """
639 Repository group permissions for the current user.
639 Repository group permissions for the current user.
640
640
641 Check if the user is part of user groups for repository groups and
641 Check if the user is part of user groups for repository groups and
642 fill in the permissions from it. `_choose_permmission` decides of which
642 fill in the permissions from it. `_choose_permmission` decides of which
643 permission should be selected based on selected method.
643 permission should be selected based on selected method.
644 """
644 """
645 # user group for repo groups permissions
645 # user group for repo groups permissions
646 user_repo_group_perms_from_user_group = Permission\
646 user_repo_group_perms_from_user_group = Permission\
647 .get_default_group_perms_from_user_group(
647 .get_default_group_perms_from_user_group(
648 self.user_id, self.scope_repo_group_id)
648 self.user_id, self.scope_repo_group_id)
649
649
650 multiple_counter = collections.defaultdict(int)
650 multiple_counter = collections.defaultdict(int)
651 for perm in user_repo_group_perms_from_user_group:
651 for perm in user_repo_group_perms_from_user_group:
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
655 multiple_counter[g_k] += 1
655 multiple_counter[g_k] += 1
656 p = perm.Permission.permission_name
656 p = perm.Permission.permission_name
657 if perm.RepoGroup.user_id == self.user_id:
657 if perm.RepoGroup.user_id == self.user_id:
658 # set admin if owner, even for member of other user group
658 # set admin if owner, even for member of other user group
659 p = 'group.admin'
659 p = 'group.admin'
660 o = PermOrigin.REPOGROUP_OWNER
660 o = PermOrigin.REPOGROUP_OWNER
661 else:
661 else:
662 if multiple_counter[g_k] > 1:
662 if multiple_counter[g_k] > 1:
663 cur_perm = self.permissions_repository_groups[g_k]
663 cur_perm = self.permissions_repository_groups[g_k]
664 p = self._choose_permission(p, cur_perm)
664 p = self._choose_permission(p, cur_perm)
665 self.permissions_repository_groups[g_k] = p, o
665 self.permissions_repository_groups[g_k] = p, o
666
666
667 # user explicit permissions for repository groups
667 # user explicit permissions for repository groups
668 user_repo_groups_perms = Permission.get_default_group_perms(
668 user_repo_groups_perms = Permission.get_default_group_perms(
669 self.user_id, self.scope_repo_group_id)
669 self.user_id, self.scope_repo_group_id)
670 for perm in user_repo_groups_perms:
670 for perm in user_repo_groups_perms:
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
672 u_k = perm.UserRepoGroupToPerm.user.username
672 u_k = perm.UserRepoGroupToPerm.user.username
673 o = PermOrigin.REPOGROUP_USER % u_k
673 o = PermOrigin.REPOGROUP_USER % u_k
674
674
675 if perm.RepoGroup.user_id == self.user_id:
675 if perm.RepoGroup.user_id == self.user_id:
676 # set admin if owner
676 # set admin if owner
677 p = 'group.admin'
677 p = 'group.admin'
678 o = PermOrigin.REPOGROUP_OWNER
678 o = PermOrigin.REPOGROUP_OWNER
679 else:
679 else:
680 p = perm.Permission.permission_name
680 p = perm.Permission.permission_name
681 if not self.explicit:
681 if not self.explicit:
682 cur_perm = self.permissions_repository_groups.get(
682 cur_perm = self.permissions_repository_groups.get(
683 rg_k, 'group.none')
683 rg_k, 'group.none')
684 p = self._choose_permission(p, cur_perm)
684 p = self._choose_permission(p, cur_perm)
685 self.permissions_repository_groups[rg_k] = p, o
685 self.permissions_repository_groups[rg_k] = p, o
686
686
687 def _calculate_user_group_permissions(self):
687 def _calculate_user_group_permissions(self):
688 """
688 """
689 User group permissions for the current user.
689 User group permissions for the current user.
690 """
690 """
691 # user group for user group permissions
691 # user group for user group permissions
692 user_group_from_user_group = Permission\
692 user_group_from_user_group = Permission\
693 .get_default_user_group_perms_from_user_group(
693 .get_default_user_group_perms_from_user_group(
694 self.user_id, self.scope_user_group_id)
694 self.user_id, self.scope_user_group_id)
695
695
696 multiple_counter = collections.defaultdict(int)
696 multiple_counter = collections.defaultdict(int)
697 for perm in user_group_from_user_group:
697 for perm in user_group_from_user_group:
698 g_k = perm.UserGroupUserGroupToPerm\
698 g_k = perm.UserGroupUserGroupToPerm\
699 .target_user_group.users_group_name
699 .target_user_group.users_group_name
700 u_k = perm.UserGroupUserGroupToPerm\
700 u_k = perm.UserGroupUserGroupToPerm\
701 .user_group.users_group_name
701 .user_group.users_group_name
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
703 multiple_counter[g_k] += 1
703 multiple_counter[g_k] += 1
704 p = perm.Permission.permission_name
704 p = perm.Permission.permission_name
705
705
706 if perm.UserGroup.user_id == self.user_id:
706 if perm.UserGroup.user_id == self.user_id:
707 # set admin if owner, even for member of other user group
707 # set admin if owner, even for member of other user group
708 p = 'usergroup.admin'
708 p = 'usergroup.admin'
709 o = PermOrigin.USERGROUP_OWNER
709 o = PermOrigin.USERGROUP_OWNER
710 else:
710 else:
711 if multiple_counter[g_k] > 1:
711 if multiple_counter[g_k] > 1:
712 cur_perm = self.permissions_user_groups[g_k]
712 cur_perm = self.permissions_user_groups[g_k]
713 p = self._choose_permission(p, cur_perm)
713 p = self._choose_permission(p, cur_perm)
714 self.permissions_user_groups[g_k] = p, o
714 self.permissions_user_groups[g_k] = p, o
715
715
716 # user explicit permission for user groups
716 # user explicit permission for user groups
717 user_user_groups_perms = Permission.get_default_user_group_perms(
717 user_user_groups_perms = Permission.get_default_user_group_perms(
718 self.user_id, self.scope_user_group_id)
718 self.user_id, self.scope_user_group_id)
719 for perm in user_user_groups_perms:
719 for perm in user_user_groups_perms:
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
721 u_k = perm.UserUserGroupToPerm.user.username
721 u_k = perm.UserUserGroupToPerm.user.username
722 o = PermOrigin.USERGROUP_USER % u_k
722 o = PermOrigin.USERGROUP_USER % u_k
723
723
724 if perm.UserGroup.user_id == self.user_id:
724 if perm.UserGroup.user_id == self.user_id:
725 # set admin if owner
725 # set admin if owner
726 p = 'usergroup.admin'
726 p = 'usergroup.admin'
727 o = PermOrigin.USERGROUP_OWNER
727 o = PermOrigin.USERGROUP_OWNER
728 else:
728 else:
729 p = perm.Permission.permission_name
729 p = perm.Permission.permission_name
730 if not self.explicit:
730 if not self.explicit:
731 cur_perm = self.permissions_user_groups.get(
731 cur_perm = self.permissions_user_groups.get(
732 ug_k, 'usergroup.none')
732 ug_k, 'usergroup.none')
733 p = self._choose_permission(p, cur_perm)
733 p = self._choose_permission(p, cur_perm)
734 self.permissions_user_groups[ug_k] = p, o
734 self.permissions_user_groups[ug_k] = p, o
735
735
736 def _choose_permission(self, new_perm, cur_perm):
736 def _choose_permission(self, new_perm, cur_perm):
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
739 if self.algo == 'higherwin':
739 if self.algo == 'higherwin':
740 if new_perm_val > cur_perm_val:
740 if new_perm_val > cur_perm_val:
741 return new_perm
741 return new_perm
742 return cur_perm
742 return cur_perm
743 elif self.algo == 'lowerwin':
743 elif self.algo == 'lowerwin':
744 if new_perm_val < cur_perm_val:
744 if new_perm_val < cur_perm_val:
745 return new_perm
745 return new_perm
746 return cur_perm
746 return cur_perm
747
747
748 def _permission_structure(self):
748 def _permission_structure(self):
749 return {
749 return {
750 'global': self.permissions_global,
750 'global': self.permissions_global,
751 'repositories': self.permissions_repositories,
751 'repositories': self.permissions_repositories,
752 'repositories_groups': self.permissions_repository_groups,
752 'repositories_groups': self.permissions_repository_groups,
753 'user_groups': self.permissions_user_groups,
753 'user_groups': self.permissions_user_groups,
754 }
754 }
755
755
756
756
757 def allowed_auth_token_access(view_name, whitelist=None, auth_token=None):
757 def allowed_auth_token_access(view_name, whitelist=None, auth_token=None):
758 """
758 """
759 Check if given controller_name is in whitelist of auth token access
759 Check if given controller_name is in whitelist of auth token access
760 """
760 """
761 if not whitelist:
761 if not whitelist:
762 from rhodecode import CONFIG
762 from rhodecode import CONFIG
763 whitelist = aslist(
763 whitelist = aslist(
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
765 log.debug(
765 log.debug(
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
767
767
768 auth_token_access_valid = False
768 auth_token_access_valid = False
769 for entry in whitelist:
769 for entry in whitelist:
770 if fnmatch.fnmatch(view_name, entry):
770 if fnmatch.fnmatch(view_name, entry):
771 auth_token_access_valid = True
771 auth_token_access_valid = True
772 break
772 break
773
773
774 if auth_token_access_valid:
774 if auth_token_access_valid:
775 log.debug('view: `%s` matches entry in whitelist: %s'
775 log.debug('view: `%s` matches entry in whitelist: %s'
776 % (view_name, whitelist))
776 % (view_name, whitelist))
777 else:
777 else:
778 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
778 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
779 % (view_name, whitelist))
779 % (view_name, whitelist))
780 if auth_token:
780 if auth_token:
781 # if we use auth token key and don't have access it's a warning
781 # if we use auth token key and don't have access it's a warning
782 log.warning(msg)
782 log.warning(msg)
783 else:
783 else:
784 log.debug(msg)
784 log.debug(msg)
785
785
786 return auth_token_access_valid
786 return auth_token_access_valid
787
787
788
788
789 class AuthUser(object):
789 class AuthUser(object):
790 """
790 """
791 A simple object that handles all attributes of user in RhodeCode
791 A simple object that handles all attributes of user in RhodeCode
792
792
793 It does lookup based on API key,given user, or user present in session
793 It does lookup based on API key,given user, or user present in session
794 Then it fills all required information for such user. It also checks if
794 Then it fills all required information for such user. It also checks if
795 anonymous access is enabled and if so, it returns default user as logged in
795 anonymous access is enabled and if so, it returns default user as logged in
796 """
796 """
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
798
798
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
800
800
801 self.user_id = user_id
801 self.user_id = user_id
802 self._api_key = api_key
802 self._api_key = api_key
803
803
804 self.api_key = None
804 self.api_key = None
805 self.feed_token = ''
805 self.feed_token = ''
806 self.username = username
806 self.username = username
807 self.ip_addr = ip_addr
807 self.ip_addr = ip_addr
808 self.name = ''
808 self.name = ''
809 self.lastname = ''
809 self.lastname = ''
810 self.first_name = ''
810 self.first_name = ''
811 self.last_name = ''
811 self.last_name = ''
812 self.email = ''
812 self.email = ''
813 self.is_authenticated = False
813 self.is_authenticated = False
814 self.admin = False
814 self.admin = False
815 self.inherit_default_permissions = False
815 self.inherit_default_permissions = False
816 self.password = ''
816 self.password = ''
817
817
818 self.anonymous_user = None # propagated on propagate_data
818 self.anonymous_user = None # propagated on propagate_data
819 self.propagate_data()
819 self.propagate_data()
820 self._instance = None
820 self._instance = None
821 self._permissions_scoped_cache = {} # used to bind scoped calculation
821 self._permissions_scoped_cache = {} # used to bind scoped calculation
822
822
823 @LazyProperty
823 @LazyProperty
824 def permissions(self):
824 def permissions(self):
825 return self.get_perms(user=self, cache=False)
825 return self.get_perms(user=self, cache=False)
826
826
827 def permissions_with_scope(self, scope):
827 def permissions_with_scope(self, scope):
828 """
828 """
829 Call the get_perms function with scoped data. The scope in that function
829 Call the get_perms function with scoped data. The scope in that function
830 narrows the SQL calls to the given ID of objects resulting in fetching
830 narrows the SQL calls to the given ID of objects resulting in fetching
831 Just particular permission we want to obtain. If scope is an empty dict
831 Just particular permission we want to obtain. If scope is an empty dict
832 then it basically narrows the scope to GLOBAL permissions only.
832 then it basically narrows the scope to GLOBAL permissions only.
833
833
834 :param scope: dict
834 :param scope: dict
835 """
835 """
836 if 'repo_name' in scope:
836 if 'repo_name' in scope:
837 obj = Repository.get_by_repo_name(scope['repo_name'])
837 obj = Repository.get_by_repo_name(scope['repo_name'])
838 if obj:
838 if obj:
839 scope['repo_id'] = obj.repo_id
839 scope['repo_id'] = obj.repo_id
840 _scope = {
840 _scope = {
841 'repo_id': -1,
841 'repo_id': -1,
842 'user_group_id': -1,
842 'user_group_id': -1,
843 'repo_group_id': -1,
843 'repo_group_id': -1,
844 }
844 }
845 _scope.update(scope)
845 _scope.update(scope)
846 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
846 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
847 _scope.items())))
847 _scope.items())))
848 if cache_key not in self._permissions_scoped_cache:
848 if cache_key not in self._permissions_scoped_cache:
849 # store in cache to mimic how the @LazyProperty works,
849 # store in cache to mimic how the @LazyProperty works,
850 # the difference here is that we use the unique key calculated
850 # the difference here is that we use the unique key calculated
851 # from params and values
851 # from params and values
852 res = self.get_perms(user=self, cache=False, scope=_scope)
852 res = self.get_perms(user=self, cache=False, scope=_scope)
853 self._permissions_scoped_cache[cache_key] = res
853 self._permissions_scoped_cache[cache_key] = res
854 return self._permissions_scoped_cache[cache_key]
854 return self._permissions_scoped_cache[cache_key]
855
855
856 def get_instance(self):
856 def get_instance(self):
857 return User.get(self.user_id)
857 return User.get(self.user_id)
858
858
859 def update_lastactivity(self):
859 def update_lastactivity(self):
860 if self.user_id:
860 if self.user_id:
861 User.get(self.user_id).update_lastactivity()
861 User.get(self.user_id).update_lastactivity()
862
862
863 def propagate_data(self):
863 def propagate_data(self):
864 """
864 """
865 Fills in user data and propagates values to this instance. Maps fetched
865 Fills in user data and propagates values to this instance. Maps fetched
866 user attributes to this class instance attributes
866 user attributes to this class instance attributes
867 """
867 """
868 log.debug('AuthUser: starting data propagation for new potential user')
868 log.debug('AuthUser: starting data propagation for new potential user')
869 user_model = UserModel()
869 user_model = UserModel()
870 anon_user = self.anonymous_user = User.get_default_user(cache=True)
870 anon_user = self.anonymous_user = User.get_default_user(cache=True)
871 is_user_loaded = False
871 is_user_loaded = False
872
872
873 # lookup by userid
873 # lookup by userid
874 if self.user_id is not None and self.user_id != anon_user.user_id:
874 if self.user_id is not None and self.user_id != anon_user.user_id:
875 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
875 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
876 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
876 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
877
877
878 # try go get user by api key
878 # try go get user by api key
879 elif self._api_key and self._api_key != anon_user.api_key:
879 elif self._api_key and self._api_key != anon_user.api_key:
880 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
880 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
881 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
881 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
882
882
883 # lookup by username
883 # lookup by username
884 elif self.username:
884 elif self.username:
885 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
885 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
886 is_user_loaded = user_model.fill_data(self, username=self.username)
886 is_user_loaded = user_model.fill_data(self, username=self.username)
887 else:
887 else:
888 log.debug('No data in %s that could been used to log in', self)
888 log.debug('No data in %s that could been used to log in', self)
889
889
890 if not is_user_loaded:
890 if not is_user_loaded:
891 log.debug('Failed to load user. Fallback to default user')
891 log.debug('Failed to load user. Fallback to default user')
892 # if we cannot authenticate user try anonymous
892 # if we cannot authenticate user try anonymous
893 if anon_user.active:
893 if anon_user.active:
894 user_model.fill_data(self, user_id=anon_user.user_id)
894 user_model.fill_data(self, user_id=anon_user.user_id)
895 # then we set this user is logged in
895 # then we set this user is logged in
896 self.is_authenticated = True
896 self.is_authenticated = True
897 else:
897 else:
898 # in case of disabled anonymous user we reset some of the
898 # in case of disabled anonymous user we reset some of the
899 # parameters so such user is "corrupted", skipping the fill_data
899 # parameters so such user is "corrupted", skipping the fill_data
900 for attr in ['user_id', 'username', 'admin', 'active']:
900 for attr in ['user_id', 'username', 'admin', 'active']:
901 setattr(self, attr, None)
901 setattr(self, attr, None)
902 self.is_authenticated = False
902 self.is_authenticated = False
903
903
904 if not self.username:
904 if not self.username:
905 self.username = 'None'
905 self.username = 'None'
906
906
907 log.debug('AuthUser: propagated user is now %s', self)
907 log.debug('AuthUser: propagated user is now %s', self)
908
908
909 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
909 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
910 cache=False):
910 cache=False):
911 """
911 """
912 Fills user permission attribute with permissions taken from database
912 Fills user permission attribute with permissions taken from database
913 works for permissions given for repositories, and for permissions that
913 works for permissions given for repositories, and for permissions that
914 are granted to groups
914 are granted to groups
915
915
916 :param user: instance of User object from database
916 :param user: instance of User object from database
917 :param explicit: In case there are permissions both for user and a group
917 :param explicit: In case there are permissions both for user and a group
918 that user is part of, explicit flag will defiine if user will
918 that user is part of, explicit flag will defiine if user will
919 explicitly override permissions from group, if it's False it will
919 explicitly override permissions from group, if it's False it will
920 make decision based on the algo
920 make decision based on the algo
921 :param algo: algorithm to decide what permission should be choose if
921 :param algo: algorithm to decide what permission should be choose if
922 it's multiple defined, eg user in two different groups. It also
922 it's multiple defined, eg user in two different groups. It also
923 decides if explicit flag is turned off how to specify the permission
923 decides if explicit flag is turned off how to specify the permission
924 for case when user is in a group + have defined separate permission
924 for case when user is in a group + have defined separate permission
925 """
925 """
926 user_id = user.user_id
926 user_id = user.user_id
927 user_is_admin = user.is_admin
927 user_is_admin = user.is_admin
928
928
929 # inheritance of global permissions like create repo/fork repo etc
929 # inheritance of global permissions like create repo/fork repo etc
930 user_inherit_default_permissions = user.inherit_default_permissions
930 user_inherit_default_permissions = user.inherit_default_permissions
931
931
932 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
932 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
933 compute = caches.conditional_cache(
933 compute = caches.conditional_cache(
934 'short_term', 'cache_desc',
934 'short_term', 'cache_desc',
935 condition=cache, func=_cached_perms_data)
935 condition=cache, func=_cached_perms_data)
936 result = compute(user_id, scope, user_is_admin,
936 result = compute(user_id, scope, user_is_admin,
937 user_inherit_default_permissions, explicit, algo)
937 user_inherit_default_permissions, explicit, algo)
938
938
939 result_repr = []
939 result_repr = []
940 for k in result:
940 for k in result:
941 result_repr.append((k, len(result[k])))
941 result_repr.append((k, len(result[k])))
942
942
943 log.debug('PERMISSION tree computed %s' % (result_repr,))
943 log.debug('PERMISSION tree computed %s' % (result_repr,))
944 return result
944 return result
945
945
946 @property
946 @property
947 def is_default(self):
947 def is_default(self):
948 return self.username == User.DEFAULT_USER
948 return self.username == User.DEFAULT_USER
949
949
950 @property
950 @property
951 def is_admin(self):
951 def is_admin(self):
952 return self.admin
952 return self.admin
953
953
954 @property
954 @property
955 def is_user_object(self):
955 def is_user_object(self):
956 return self.user_id is not None
956 return self.user_id is not None
957
957
958 @property
958 @property
959 def repositories_admin(self):
959 def repositories_admin(self):
960 """
960 """
961 Returns list of repositories you're an admin of
961 Returns list of repositories you're an admin of
962 """
962 """
963 return [
963 return [
964 x[0] for x in self.permissions['repositories'].iteritems()
964 x[0] for x in self.permissions['repositories'].iteritems()
965 if x[1] == 'repository.admin']
965 if x[1] == 'repository.admin']
966
966
967 @property
967 @property
968 def repository_groups_admin(self):
968 def repository_groups_admin(self):
969 """
969 """
970 Returns list of repository groups you're an admin of
970 Returns list of repository groups you're an admin of
971 """
971 """
972 return [
972 return [
973 x[0] for x in self.permissions['repositories_groups'].iteritems()
973 x[0] for x in self.permissions['repositories_groups'].iteritems()
974 if x[1] == 'group.admin']
974 if x[1] == 'group.admin']
975
975
976 @property
976 @property
977 def user_groups_admin(self):
977 def user_groups_admin(self):
978 """
978 """
979 Returns list of user groups you're an admin of
979 Returns list of user groups you're an admin of
980 """
980 """
981 return [
981 return [
982 x[0] for x in self.permissions['user_groups'].iteritems()
982 x[0] for x in self.permissions['user_groups'].iteritems()
983 if x[1] == 'usergroup.admin']
983 if x[1] == 'usergroup.admin']
984
984
985 @property
985 @property
986 def ip_allowed(self):
986 def ip_allowed(self):
987 """
987 """
988 Checks if ip_addr used in constructor is allowed from defined list of
988 Checks if ip_addr used in constructor is allowed from defined list of
989 allowed ip_addresses for user
989 allowed ip_addresses for user
990
990
991 :returns: boolean, True if ip is in allowed ip range
991 :returns: boolean, True if ip is in allowed ip range
992 """
992 """
993 # check IP
993 # check IP
994 inherit = self.inherit_default_permissions
994 inherit = self.inherit_default_permissions
995 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
995 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
996 inherit_from_default=inherit)
996 inherit_from_default=inherit)
997 @property
997 @property
998 def personal_repo_group(self):
998 def personal_repo_group(self):
999 return RepoGroup.get_user_personal_repo_group(self.user_id)
999 return RepoGroup.get_user_personal_repo_group(self.user_id)
1000
1000
1001 @classmethod
1001 @classmethod
1002 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1002 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1003 allowed_ips = AuthUser.get_allowed_ips(
1003 allowed_ips = AuthUser.get_allowed_ips(
1004 user_id, cache=True, inherit_from_default=inherit_from_default)
1004 user_id, cache=True, inherit_from_default=inherit_from_default)
1005 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1005 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1006 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1006 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1007 return True
1007 return True
1008 else:
1008 else:
1009 log.info('Access for IP:%s forbidden, '
1009 log.info('Access for IP:%s forbidden, '
1010 'not in %s' % (ip_addr, allowed_ips))
1010 'not in %s' % (ip_addr, allowed_ips))
1011 return False
1011 return False
1012
1012
1013 def __repr__(self):
1013 def __repr__(self):
1014 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1014 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1015 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1015 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1016
1016
1017 def set_authenticated(self, authenticated=True):
1017 def set_authenticated(self, authenticated=True):
1018 if self.user_id != self.anonymous_user.user_id:
1018 if self.user_id != self.anonymous_user.user_id:
1019 self.is_authenticated = authenticated
1019 self.is_authenticated = authenticated
1020
1020
1021 def get_cookie_store(self):
1021 def get_cookie_store(self):
1022 return {
1022 return {
1023 'username': self.username,
1023 'username': self.username,
1024 'password': md5(self.password),
1024 'password': md5(self.password),
1025 'user_id': self.user_id,
1025 'user_id': self.user_id,
1026 'is_authenticated': self.is_authenticated
1026 'is_authenticated': self.is_authenticated
1027 }
1027 }
1028
1028
1029 @classmethod
1029 @classmethod
1030 def from_cookie_store(cls, cookie_store):
1030 def from_cookie_store(cls, cookie_store):
1031 """
1031 """
1032 Creates AuthUser from a cookie store
1032 Creates AuthUser from a cookie store
1033
1033
1034 :param cls:
1034 :param cls:
1035 :param cookie_store:
1035 :param cookie_store:
1036 """
1036 """
1037 user_id = cookie_store.get('user_id')
1037 user_id = cookie_store.get('user_id')
1038 username = cookie_store.get('username')
1038 username = cookie_store.get('username')
1039 api_key = cookie_store.get('api_key')
1039 api_key = cookie_store.get('api_key')
1040 return AuthUser(user_id, api_key, username)
1040 return AuthUser(user_id, api_key, username)
1041
1041
1042 @classmethod
1042 @classmethod
1043 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1043 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1044 _set = set()
1044 _set = set()
1045
1045
1046 if inherit_from_default:
1046 if inherit_from_default:
1047 default_ips = UserIpMap.query().filter(
1047 default_ips = UserIpMap.query().filter(
1048 UserIpMap.user == User.get_default_user(cache=True))
1048 UserIpMap.user == User.get_default_user(cache=True))
1049 if cache:
1049 if cache:
1050 default_ips = default_ips.options(
1050 default_ips = default_ips.options(
1051 FromCache("sql_cache_short", "get_user_ips_default"))
1051 FromCache("sql_cache_short", "get_user_ips_default"))
1052
1052
1053 # populate from default user
1053 # populate from default user
1054 for ip in default_ips:
1054 for ip in default_ips:
1055 try:
1055 try:
1056 _set.add(ip.ip_addr)
1056 _set.add(ip.ip_addr)
1057 except ObjectDeletedError:
1057 except ObjectDeletedError:
1058 # since we use heavy caching sometimes it happens that
1058 # since we use heavy caching sometimes it happens that
1059 # we get deleted objects here, we just skip them
1059 # we get deleted objects here, we just skip them
1060 pass
1060 pass
1061
1061
1062 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1062 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1063 if cache:
1063 if cache:
1064 user_ips = user_ips.options(
1064 user_ips = user_ips.options(
1065 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1065 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1066
1066
1067 for ip in user_ips:
1067 for ip in user_ips:
1068 try:
1068 try:
1069 _set.add(ip.ip_addr)
1069 _set.add(ip.ip_addr)
1070 except ObjectDeletedError:
1070 except ObjectDeletedError:
1071 # since we use heavy caching sometimes it happens that we get
1071 # since we use heavy caching sometimes it happens that we get
1072 # deleted objects here, we just skip them
1072 # deleted objects here, we just skip them
1073 pass
1073 pass
1074 return _set or set(['0.0.0.0/0', '::/0'])
1074 return _set or set(['0.0.0.0/0', '::/0'])
1075
1075
1076
1076
1077 def set_available_permissions(config):
1077 def set_available_permissions(config):
1078 """
1078 """
1079 This function will propagate pylons globals with all available defined
1079 This function will propagate pylons globals with all available defined
1080 permission given in db. We don't want to check each time from db for new
1080 permission given in db. We don't want to check each time from db for new
1081 permissions since adding a new permission also requires application restart
1081 permissions since adding a new permission also requires application restart
1082 ie. to decorate new views with the newly created permission
1082 ie. to decorate new views with the newly created permission
1083
1083
1084 :param config: current pylons config instance
1084 :param config: current pylons config instance
1085
1085
1086 """
1086 """
1087 log.info('getting information about all available permissions')
1087 log.info('getting information about all available permissions')
1088 try:
1088 try:
1089 sa = meta.Session
1089 sa = meta.Session
1090 all_perms = sa.query(Permission).all()
1090 all_perms = sa.query(Permission).all()
1091 config['available_permissions'] = [x.permission_name for x in all_perms]
1091 config['available_permissions'] = [x.permission_name for x in all_perms]
1092 except Exception:
1092 except Exception:
1093 log.error(traceback.format_exc())
1093 log.error(traceback.format_exc())
1094 finally:
1094 finally:
1095 meta.Session.remove()
1095 meta.Session.remove()
1096
1096
1097
1097
1098 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1098 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1099 """
1099 """
1100 Return the current authentication token, creating one if one doesn't
1100 Return the current authentication token, creating one if one doesn't
1101 already exist and the save_if_missing flag is present.
1101 already exist and the save_if_missing flag is present.
1102
1102
1103 :param session: pass in the pylons session, else we use the global ones
1103 :param session: pass in the pylons session, else we use the global ones
1104 :param force_new: force to re-generate the token and store it in session
1104 :param force_new: force to re-generate the token and store it in session
1105 :param save_if_missing: save the newly generated token if it's missing in
1105 :param save_if_missing: save the newly generated token if it's missing in
1106 session
1106 session
1107 """
1107 """
1108 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1108 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1109 # from pyramid.csrf import get_csrf_token
1109 # from pyramid.csrf import get_csrf_token
1110
1110
1111 if not session:
1111 if not session:
1112 from pylons import session
1112 from pylons import session
1113
1113
1114 if (csrf_token_key not in session and save_if_missing) or force_new:
1114 if (csrf_token_key not in session and save_if_missing) or force_new:
1115 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1115 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1116 session[csrf_token_key] = token
1116 session[csrf_token_key] = token
1117 if hasattr(session, 'save'):
1117 if hasattr(session, 'save'):
1118 session.save()
1118 session.save()
1119 return session.get(csrf_token_key)
1119 return session.get(csrf_token_key)
1120
1120
1121
1121
1122 def get_request(perm_class):
1122 def get_request(perm_class):
1123 from pyramid.threadlocal import get_current_request
1123 from pyramid.threadlocal import get_current_request
1124 pyramid_request = get_current_request()
1124 pyramid_request = get_current_request()
1125 if not pyramid_request:
1125 if not pyramid_request:
1126 # return global request of pylons in case pyramid isn't available
1126 # return global request of pylons in case pyramid isn't available
1127 # NOTE(marcink): this should be removed after migration to pyramid
1127 # NOTE(marcink): this should be removed after migration to pyramid
1128 from pylons import request
1128 from pylons import request
1129 return request
1129 return request
1130 return pyramid_request
1130 return pyramid_request
1131
1131
1132
1132
1133 # CHECK DECORATORS
1133 # CHECK DECORATORS
1134 class CSRFRequired(object):
1134 class CSRFRequired(object):
1135 """
1135 """
1136 Decorator for authenticating a form
1136 Decorator for authenticating a form
1137
1137
1138 This decorator uses an authorization token stored in the client's
1138 This decorator uses an authorization token stored in the client's
1139 session for prevention of certain Cross-site request forgery (CSRF)
1139 session for prevention of certain Cross-site request forgery (CSRF)
1140 attacks (See
1140 attacks (See
1141 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1141 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1142 information).
1142 information).
1143
1143
1144 For use with the ``webhelpers.secure_form`` helper functions.
1144 For use with the ``webhelpers.secure_form`` helper functions.
1145
1145
1146 """
1146 """
1147 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1147 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1148 except_methods=None):
1148 except_methods=None):
1149 self.token = token
1149 self.token = token
1150 self.header = header
1150 self.header = header
1151 self.except_methods = except_methods or []
1151 self.except_methods = except_methods or []
1152
1152
1153 def __call__(self, func):
1153 def __call__(self, func):
1154 return get_cython_compat_decorator(self.__wrapper, func)
1154 return get_cython_compat_decorator(self.__wrapper, func)
1155
1155
1156 def _get_csrf(self, _request):
1156 def _get_csrf(self, _request):
1157 return _request.POST.get(self.token, _request.headers.get(self.header))
1157 return _request.POST.get(self.token, _request.headers.get(self.header))
1158
1158
1159 def check_csrf(self, _request, cur_token):
1159 def check_csrf(self, _request, cur_token):
1160 supplied_token = self._get_csrf(_request)
1160 supplied_token = self._get_csrf(_request)
1161 return supplied_token and supplied_token == cur_token
1161 return supplied_token and supplied_token == cur_token
1162
1162
1163 def _get_request(self):
1163 def _get_request(self):
1164 return get_request(self)
1164 return get_request(self)
1165
1165
1166 def __wrapper(self, func, *fargs, **fkwargs):
1166 def __wrapper(self, func, *fargs, **fkwargs):
1167 request = self._get_request()
1167 request = self._get_request()
1168
1168
1169 if request.method in self.except_methods:
1169 if request.method in self.except_methods:
1170 return func(*fargs, **fkwargs)
1170 return func(*fargs, **fkwargs)
1171
1171
1172 cur_token = get_csrf_token(save_if_missing=False)
1172 cur_token = get_csrf_token(save_if_missing=False)
1173 if self.check_csrf(request, cur_token):
1173 if self.check_csrf(request, cur_token):
1174 if request.POST.get(self.token):
1174 if request.POST.get(self.token):
1175 del request.POST[self.token]
1175 del request.POST[self.token]
1176 return func(*fargs, **fkwargs)
1176 return func(*fargs, **fkwargs)
1177 else:
1177 else:
1178 reason = 'token-missing'
1178 reason = 'token-missing'
1179 supplied_token = self._get_csrf(request)
1179 supplied_token = self._get_csrf(request)
1180 if supplied_token and cur_token != supplied_token:
1180 if supplied_token and cur_token != supplied_token:
1181 reason = 'token-mismatch [%s:%s]' % (
1181 reason = 'token-mismatch [%s:%s]' % (
1182 cur_token or ''[:6], supplied_token or ''[:6])
1182 cur_token or ''[:6], supplied_token or ''[:6])
1183
1183
1184 csrf_message = \
1184 csrf_message = \
1185 ("Cross-site request forgery detected, request denied. See "
1185 ("Cross-site request forgery detected, request denied. See "
1186 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1186 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1187 "more information.")
1187 "more information.")
1188 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1188 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1189 'REMOTE_ADDR:%s, HEADERS:%s' % (
1189 'REMOTE_ADDR:%s, HEADERS:%s' % (
1190 request, reason, request.remote_addr, request.headers))
1190 request, reason, request.remote_addr, request.headers))
1191
1191
1192 raise HTTPForbidden(explanation=csrf_message)
1192 raise HTTPForbidden(explanation=csrf_message)
1193
1193
1194
1194
1195 class LoginRequired(object):
1195 class LoginRequired(object):
1196 """
1196 """
1197 Must be logged in to execute this function else
1197 Must be logged in to execute this function else
1198 redirect to login page
1198 redirect to login page
1199
1199
1200 :param api_access: if enabled this checks only for valid auth token
1200 :param api_access: if enabled this checks only for valid auth token
1201 and grants access based on valid token
1201 and grants access based on valid token
1202 """
1202 """
1203 def __init__(self, auth_token_access=None):
1203 def __init__(self, auth_token_access=None):
1204 self.auth_token_access = auth_token_access
1204 self.auth_token_access = auth_token_access
1205
1205
1206 def __call__(self, func):
1206 def __call__(self, func):
1207 return get_cython_compat_decorator(self.__wrapper, func)
1207 return get_cython_compat_decorator(self.__wrapper, func)
1208
1208
1209 def _get_request(self):
1209 def _get_request(self):
1210 return get_request(self)
1210 return get_request(self)
1211
1211
1212 def __wrapper(self, func, *fargs, **fkwargs):
1212 def __wrapper(self, func, *fargs, **fkwargs):
1213 from rhodecode.lib import helpers as h
1213 from rhodecode.lib import helpers as h
1214 cls = fargs[0]
1214 cls = fargs[0]
1215 user = cls._rhodecode_user
1215 user = cls._rhodecode_user
1216 request = self._get_request()
1216 request = self._get_request()
1217
1217
1218 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1218 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1219 log.debug('Starting login restriction checks for user: %s' % (user,))
1219 log.debug('Starting login restriction checks for user: %s' % (user,))
1220 # check if our IP is allowed
1220 # check if our IP is allowed
1221 ip_access_valid = True
1221 ip_access_valid = True
1222 if not user.ip_allowed:
1222 if not user.ip_allowed:
1223 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1223 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1224 category='warning')
1224 category='warning')
1225 ip_access_valid = False
1225 ip_access_valid = False
1226
1226
1227 # check if we used an APIKEY and it's a valid one
1227 # check if we used an APIKEY and it's a valid one
1228 # defined white-list of controllers which API access will be enabled
1228 # defined white-list of controllers which API access will be enabled
1229 _auth_token = request.GET.get(
1229 _auth_token = request.GET.get(
1230 'auth_token', '') or request.GET.get('api_key', '')
1230 'auth_token', '') or request.GET.get('api_key', '')
1231 auth_token_access_valid = allowed_auth_token_access(
1231 auth_token_access_valid = allowed_auth_token_access(
1232 loc, auth_token=_auth_token)
1232 loc, auth_token=_auth_token)
1233
1233
1234 # explicit controller is enabled or API is in our whitelist
1234 # explicit controller is enabled or API is in our whitelist
1235 if self.auth_token_access or auth_token_access_valid:
1235 if self.auth_token_access or auth_token_access_valid:
1236 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1236 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1237 db_user = user.get_instance()
1237 db_user = user.get_instance()
1238
1238
1239 if db_user:
1239 if db_user:
1240 if self.auth_token_access:
1240 if self.auth_token_access:
1241 roles = self.auth_token_access
1241 roles = self.auth_token_access
1242 else:
1242 else:
1243 roles = [UserApiKeys.ROLE_HTTP]
1243 roles = [UserApiKeys.ROLE_HTTP]
1244 token_match = db_user.authenticate_by_token(
1244 token_match = db_user.authenticate_by_token(
1245 _auth_token, roles=roles)
1245 _auth_token, roles=roles)
1246 else:
1246 else:
1247 log.debug('Unable to fetch db instance for auth user: %s', user)
1247 log.debug('Unable to fetch db instance for auth user: %s', user)
1248 token_match = False
1248 token_match = False
1249
1249
1250 if _auth_token and token_match:
1250 if _auth_token and token_match:
1251 auth_token_access_valid = True
1251 auth_token_access_valid = True
1252 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1252 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1253 else:
1253 else:
1254 auth_token_access_valid = False
1254 auth_token_access_valid = False
1255 if not _auth_token:
1255 if not _auth_token:
1256 log.debug("AUTH TOKEN *NOT* present in request")
1256 log.debug("AUTH TOKEN *NOT* present in request")
1257 else:
1257 else:
1258 log.warning(
1258 log.warning(
1259 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1259 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1260
1260
1261 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1261 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1262 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1262 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1263 else 'AUTH_TOKEN_AUTH'
1263 else 'AUTH_TOKEN_AUTH'
1264
1264
1265 if ip_access_valid and (
1265 if ip_access_valid and (
1266 user.is_authenticated or auth_token_access_valid):
1266 user.is_authenticated or auth_token_access_valid):
1267 log.info(
1267 log.info(
1268 'user %s authenticating with:%s IS authenticated on func %s'
1268 'user %s authenticating with:%s IS authenticated on func %s'
1269 % (user, reason, loc))
1269 % (user, reason, loc))
1270
1270
1271 # update user data to check last activity
1271 # update user data to check last activity
1272 user.update_lastactivity()
1272 user.update_lastactivity()
1273 Session().commit()
1273 Session().commit()
1274 return func(*fargs, **fkwargs)
1274 return func(*fargs, **fkwargs)
1275 else:
1275 else:
1276 log.warning(
1276 log.warning(
1277 'user %s authenticating with:%s NOT authenticated on '
1277 'user %s authenticating with:%s NOT authenticated on '
1278 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1278 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1279 % (user, reason, loc, ip_access_valid,
1279 % (user, reason, loc, ip_access_valid,
1280 auth_token_access_valid))
1280 auth_token_access_valid))
1281 # we preserve the get PARAM
1281 # we preserve the get PARAM
1282 came_from = request.path_qs
1282 came_from = request.path_qs
1283 log.debug('redirecting to login page with %s' % (came_from,))
1283 log.debug('redirecting to login page with %s' % (came_from,))
1284 raise HTTPFound(
1284 raise HTTPFound(
1285 h.route_path('login', _query={'came_from': came_from}))
1285 h.route_path('login', _query={'came_from': came_from}))
1286
1286
1287
1287
1288 class NotAnonymous(object):
1288 class NotAnonymous(object):
1289 """
1289 """
1290 Must be logged in to execute this function else
1290 Must be logged in to execute this function else
1291 redirect to login page
1291 redirect to login page
1292 """
1292 """
1293
1293
1294 def __call__(self, func):
1294 def __call__(self, func):
1295 return get_cython_compat_decorator(self.__wrapper, func)
1295 return get_cython_compat_decorator(self.__wrapper, func)
1296
1296
1297 def _get_request(self):
1297 def _get_request(self):
1298 return get_request(self)
1298 return get_request(self)
1299
1299
1300 def __wrapper(self, func, *fargs, **fkwargs):
1300 def __wrapper(self, func, *fargs, **fkwargs):
1301 import rhodecode.lib.helpers as h
1301 import rhodecode.lib.helpers as h
1302 cls = fargs[0]
1302 cls = fargs[0]
1303 self.user = cls._rhodecode_user
1303 self.user = cls._rhodecode_user
1304 request = self._get_request()
1304 request = self._get_request()
1305
1305
1306 log.debug('Checking if user is not anonymous @%s' % cls)
1306 log.debug('Checking if user is not anonymous @%s' % cls)
1307
1307
1308 anonymous = self.user.username == User.DEFAULT_USER
1308 anonymous = self.user.username == User.DEFAULT_USER
1309
1309
1310 if anonymous:
1310 if anonymous:
1311 came_from = request.path_qs
1311 came_from = request.path_qs
1312 h.flash(_('You need to be a registered user to '
1312 h.flash(_('You need to be a registered user to '
1313 'perform this action'),
1313 'perform this action'),
1314 category='warning')
1314 category='warning')
1315 raise HTTPFound(
1315 raise HTTPFound(
1316 h.route_path('login', _query={'came_from': came_from}))
1316 h.route_path('login', _query={'came_from': came_from}))
1317 else:
1317 else:
1318 return func(*fargs, **fkwargs)
1318 return func(*fargs, **fkwargs)
1319
1319
1320
1320
1321 class XHRRequired(object):
1321 class XHRRequired(object):
1322 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1322 # TODO(marcink): remove this in favor of the predicates in pyramid routes
1323
1323
1324 def __call__(self, func):
1324 def __call__(self, func):
1325 return get_cython_compat_decorator(self.__wrapper, func)
1325 return get_cython_compat_decorator(self.__wrapper, func)
1326
1326
1327 def _get_request(self):
1327 def _get_request(self):
1328 return get_request(self)
1328 return get_request(self)
1329
1329
1330 def __wrapper(self, func, *fargs, **fkwargs):
1330 def __wrapper(self, func, *fargs, **fkwargs):
1331 from pylons.controllers.util import abort
1331 from pylons.controllers.util import abort
1332 request = self._get_request()
1332 request = self._get_request()
1333
1333
1334 log.debug('Checking if request is XMLHttpRequest (XHR)')
1334 log.debug('Checking if request is XMLHttpRequest (XHR)')
1335 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1335 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1336
1336
1337 if not request.is_xhr:
1337 if not request.is_xhr:
1338 abort(400, detail=xhr_message)
1338 abort(400, detail=xhr_message)
1339
1339
1340 return func(*fargs, **fkwargs)
1340 return func(*fargs, **fkwargs)
1341
1341
1342
1342
1343 class PermsDecorator(object):
1343 class PermsDecorator(object):
1344 """
1344 """
1345 Base class for controller decorators, we extract the current user from
1345 Base class for controller decorators, we extract the current user from
1346 the class itself, which has it stored in base controllers
1346 the class itself, which has it stored in base controllers
1347 """
1347 """
1348
1348
1349 def __init__(self, *required_perms):
1349 def __init__(self, *required_perms):
1350 self.required_perms = set(required_perms)
1350 self.required_perms = set(required_perms)
1351
1351
1352 def __call__(self, func):
1352 def __call__(self, func):
1353 return get_cython_compat_decorator(self.__wrapper, func)
1353 return get_cython_compat_decorator(self.__wrapper, func)
1354
1354
1355 def _get_request(self):
1355 def _get_request(self):
1356 return get_request(self)
1356 return get_request(self)
1357
1357
1358 def _get_came_from(self):
1358 def _get_came_from(self):
1359 _request = self._get_request()
1359 _request = self._get_request()
1360
1360
1361 # both pylons/pyramid has this attribute
1361 # both pylons/pyramid has this attribute
1362 return _request.path_qs
1362 return _request.path_qs
1363
1363
1364 def __wrapper(self, func, *fargs, **fkwargs):
1364 def __wrapper(self, func, *fargs, **fkwargs):
1365 import rhodecode.lib.helpers as h
1365 import rhodecode.lib.helpers as h
1366 cls = fargs[0]
1366 cls = fargs[0]
1367 _user = cls._rhodecode_user
1367 _user = cls._rhodecode_user
1368
1368
1369 log.debug('checking %s permissions %s for %s %s',
1369 log.debug('checking %s permissions %s for %s %s',
1370 self.__class__.__name__, self.required_perms, cls, _user)
1370 self.__class__.__name__, self.required_perms, cls, _user)
1371
1371
1372 if self.check_permissions(_user):
1372 if self.check_permissions(_user):
1373 log.debug('Permission granted for %s %s', cls, _user)
1373 log.debug('Permission granted for %s %s', cls, _user)
1374 return func(*fargs, **fkwargs)
1374 return func(*fargs, **fkwargs)
1375
1375
1376 else:
1376 else:
1377 log.debug('Permission denied for %s %s', cls, _user)
1377 log.debug('Permission denied for %s %s', cls, _user)
1378 anonymous = _user.username == User.DEFAULT_USER
1378 anonymous = _user.username == User.DEFAULT_USER
1379
1379
1380 if anonymous:
1380 if anonymous:
1381 came_from = self._get_came_from()
1381 came_from = self._get_came_from()
1382 h.flash(_('You need to be signed in to view this page'),
1382 h.flash(_('You need to be signed in to view this page'),
1383 category='warning')
1383 category='warning')
1384 raise HTTPFound(
1384 raise HTTPFound(
1385 h.route_path('login', _query={'came_from': came_from}))
1385 h.route_path('login', _query={'came_from': came_from}))
1386
1386
1387 else:
1387 else:
1388 # redirect with 404 to prevent resource discovery
1388 # redirect with 404 to prevent resource discovery
1389 raise HTTPNotFound()
1389 raise HTTPNotFound()
1390
1390
1391 def check_permissions(self, user):
1391 def check_permissions(self, user):
1392 """Dummy function for overriding"""
1392 """Dummy function for overriding"""
1393 raise NotImplementedError(
1393 raise NotImplementedError(
1394 'You have to write this function in child class')
1394 'You have to write this function in child class')
1395
1395
1396
1396
1397 class HasPermissionAllDecorator(PermsDecorator):
1397 class HasPermissionAllDecorator(PermsDecorator):
1398 """
1398 """
1399 Checks for access permission for all given predicates. All of them
1399 Checks for access permission for all given predicates. All of them
1400 have to be meet in order to fulfill the request
1400 have to be meet in order to fulfill the request
1401 """
1401 """
1402
1402
1403 def check_permissions(self, user):
1403 def check_permissions(self, user):
1404 perms = user.permissions_with_scope({})
1404 perms = user.permissions_with_scope({})
1405 if self.required_perms.issubset(perms['global']):
1405 if self.required_perms.issubset(perms['global']):
1406 return True
1406 return True
1407 return False
1407 return False
1408
1408
1409
1409
1410 class HasPermissionAnyDecorator(PermsDecorator):
1410 class HasPermissionAnyDecorator(PermsDecorator):
1411 """
1411 """
1412 Checks for access permission for any of given predicates. In order to
1412 Checks for access permission for any of given predicates. In order to
1413 fulfill the request any of predicates must be meet
1413 fulfill the request any of predicates must be meet
1414 """
1414 """
1415
1415
1416 def check_permissions(self, user):
1416 def check_permissions(self, user):
1417 perms = user.permissions_with_scope({})
1417 perms = user.permissions_with_scope({})
1418 if self.required_perms.intersection(perms['global']):
1418 if self.required_perms.intersection(perms['global']):
1419 return True
1419 return True
1420 return False
1420 return False
1421
1421
1422
1422
1423 class HasRepoPermissionAllDecorator(PermsDecorator):
1423 class HasRepoPermissionAllDecorator(PermsDecorator):
1424 """
1424 """
1425 Checks for access permission for all given predicates for specific
1425 Checks for access permission for all given predicates for specific
1426 repository. All of them have to be meet in order to fulfill the request
1426 repository. All of them have to be meet in order to fulfill the request
1427 """
1427 """
1428 def _get_repo_name(self):
1428 def _get_repo_name(self):
1429 _request = self._get_request()
1429 _request = self._get_request()
1430 return get_repo_slug(_request)
1430 return get_repo_slug(_request)
1431
1431
1432 def check_permissions(self, user):
1432 def check_permissions(self, user):
1433 perms = user.permissions
1433 perms = user.permissions
1434 repo_name = self._get_repo_name()
1434 repo_name = self._get_repo_name()
1435
1435
1436 try:
1436 try:
1437 user_perms = set([perms['repositories'][repo_name]])
1437 user_perms = set([perms['repositories'][repo_name]])
1438 except KeyError:
1438 except KeyError:
1439 log.debug('cannot locate repo with name: `%s` in permissions defs',
1439 log.debug('cannot locate repo with name: `%s` in permissions defs',
1440 repo_name)
1440 repo_name)
1441 return False
1441 return False
1442
1442
1443 log.debug('checking `%s` permissions for repo `%s`',
1443 log.debug('checking `%s` permissions for repo `%s`',
1444 user_perms, repo_name)
1444 user_perms, repo_name)
1445 if self.required_perms.issubset(user_perms):
1445 if self.required_perms.issubset(user_perms):
1446 return True
1446 return True
1447 return False
1447 return False
1448
1448
1449
1449
1450 class HasRepoPermissionAnyDecorator(PermsDecorator):
1450 class HasRepoPermissionAnyDecorator(PermsDecorator):
1451 """
1451 """
1452 Checks for access permission for any of given predicates for specific
1452 Checks for access permission for any of given predicates for specific
1453 repository. In order to fulfill the request any of predicates must be meet
1453 repository. In order to fulfill the request any of predicates must be meet
1454 """
1454 """
1455 def _get_repo_name(self):
1455 def _get_repo_name(self):
1456 _request = self._get_request()
1456 _request = self._get_request()
1457 return get_repo_slug(_request)
1457 return get_repo_slug(_request)
1458
1458
1459 def check_permissions(self, user):
1459 def check_permissions(self, user):
1460 perms = user.permissions
1460 perms = user.permissions
1461 repo_name = self._get_repo_name()
1461 repo_name = self._get_repo_name()
1462
1462
1463 try:
1463 try:
1464 user_perms = set([perms['repositories'][repo_name]])
1464 user_perms = set([perms['repositories'][repo_name]])
1465 except KeyError:
1465 except KeyError:
1466 log.debug('cannot locate repo with name: `%s` in permissions defs',
1466 log.debug(
1467 repo_name)
1467 'cannot locate repo with name: `%s` in permissions defs',
1468 repo_name)
1468 return False
1469 return False
1469
1470
1470 log.debug('checking `%s` permissions for repo `%s`',
1471 log.debug('checking `%s` permissions for repo `%s`',
1471 user_perms, repo_name)
1472 user_perms, repo_name)
1472 if self.required_perms.intersection(user_perms):
1473 if self.required_perms.intersection(user_perms):
1473 return True
1474 return True
1474 return False
1475 return False
1475
1476
1476
1477
1477 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1478 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1478 """
1479 """
1479 Checks for access permission for all given predicates for specific
1480 Checks for access permission for all given predicates for specific
1480 repository group. All of them have to be meet in order to
1481 repository group. All of them have to be meet in order to
1481 fulfill the request
1482 fulfill the request
1482 """
1483 """
1483 def _get_repo_group_name(self):
1484 def _get_repo_group_name(self):
1484 _request = self._get_request()
1485 _request = self._get_request()
1485 return get_repo_group_slug(_request)
1486 return get_repo_group_slug(_request)
1486
1487
1487 def check_permissions(self, user):
1488 def check_permissions(self, user):
1488 perms = user.permissions
1489 perms = user.permissions
1489 group_name = self._get_repo_group_name()
1490 group_name = self._get_repo_group_name()
1490 try:
1491 try:
1491 user_perms = set([perms['repositories_groups'][group_name]])
1492 user_perms = set([perms['repositories_groups'][group_name]])
1492 except KeyError:
1493 except KeyError:
1493 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1494 log.debug(
1494 group_name)
1495 'cannot locate repo group with name: `%s` in permissions defs',
1496 group_name)
1495 return False
1497 return False
1496
1498
1497 log.debug('checking `%s` permissions for repo group `%s`',
1499 log.debug('checking `%s` permissions for repo group `%s`',
1498 user_perms, group_name)
1500 user_perms, group_name)
1499 if self.required_perms.issubset(user_perms):
1501 if self.required_perms.issubset(user_perms):
1500 return True
1502 return True
1501 return False
1503 return False
1502
1504
1503
1505
1504 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1506 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1505 """
1507 """
1506 Checks for access permission for any of given predicates for specific
1508 Checks for access permission for any of given predicates for specific
1507 repository group. In order to fulfill the request any
1509 repository group. In order to fulfill the request any
1508 of predicates must be met
1510 of predicates must be met
1509 """
1511 """
1510 def _get_repo_group_name(self):
1512 def _get_repo_group_name(self):
1511 _request = self._get_request()
1513 _request = self._get_request()
1512 return get_repo_group_slug(_request)
1514 return get_repo_group_slug(_request)
1513
1515
1514 def check_permissions(self, user):
1516 def check_permissions(self, user):
1515 perms = user.permissions
1517 perms = user.permissions
1516 group_name = self._get_repo_group_name()
1518 group_name = self._get_repo_group_name()
1517
1519
1518 try:
1520 try:
1519 user_perms = set([perms['repositories_groups'][group_name]])
1521 user_perms = set([perms['repositories_groups'][group_name]])
1520 except KeyError:
1522 except KeyError:
1521 log.debug('cannot locate repo group with name: `%s` in permissions defs',
1523 log.debug(
1522 group_name)
1524 'cannot locate repo group with name: `%s` in permissions defs',
1525 group_name)
1523 return False
1526 return False
1524
1527
1525 log.debug('checking `%s` permissions for repo group `%s`',
1528 log.debug('checking `%s` permissions for repo group `%s`',
1526 user_perms, group_name)
1529 user_perms, group_name)
1527 if self.required_perms.intersection(user_perms):
1530 if self.required_perms.intersection(user_perms):
1528 return True
1531 return True
1529 return False
1532 return False
1530
1533
1531
1534
1532 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1535 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1533 """
1536 """
1534 Checks for access permission for all given predicates for specific
1537 Checks for access permission for all given predicates for specific
1535 user group. All of them have to be meet in order to fulfill the request
1538 user group. All of them have to be meet in order to fulfill the request
1536 """
1539 """
1537 def _get_user_group_name(self):
1540 def _get_user_group_name(self):
1538 _request = self._get_request()
1541 _request = self._get_request()
1539 return get_user_group_slug(_request)
1542 return get_user_group_slug(_request)
1540
1543
1541 def check_permissions(self, user):
1544 def check_permissions(self, user):
1542 perms = user.permissions
1545 perms = user.permissions
1543 group_name = self._get_user_group_name()
1546 group_name = self._get_user_group_name()
1544 try:
1547 try:
1545 user_perms = set([perms['user_groups'][group_name]])
1548 user_perms = set([perms['user_groups'][group_name]])
1546 except KeyError:
1549 except KeyError:
1547 return False
1550 return False
1548
1551
1549 if self.required_perms.issubset(user_perms):
1552 if self.required_perms.issubset(user_perms):
1550 return True
1553 return True
1551 return False
1554 return False
1552
1555
1553
1556
1554 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1557 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1555 """
1558 """
1556 Checks for access permission for any of given predicates for specific
1559 Checks for access permission for any of given predicates for specific
1557 user group. In order to fulfill the request any of predicates must be meet
1560 user group. In order to fulfill the request any of predicates must be meet
1558 """
1561 """
1559 def _get_user_group_name(self):
1562 def _get_user_group_name(self):
1560 _request = self._get_request()
1563 _request = self._get_request()
1561 return get_user_group_slug(_request)
1564 return get_user_group_slug(_request)
1562
1565
1563 def check_permissions(self, user):
1566 def check_permissions(self, user):
1564 perms = user.permissions
1567 perms = user.permissions
1565 group_name = self._get_user_group_name()
1568 group_name = self._get_user_group_name()
1566 try:
1569 try:
1567 user_perms = set([perms['user_groups'][group_name]])
1570 user_perms = set([perms['user_groups'][group_name]])
1568 except KeyError:
1571 except KeyError:
1569 return False
1572 return False
1570
1573
1571 if self.required_perms.intersection(user_perms):
1574 if self.required_perms.intersection(user_perms):
1572 return True
1575 return True
1573 return False
1576 return False
1574
1577
1575
1578
1576 # CHECK FUNCTIONS
1579 # CHECK FUNCTIONS
1577 class PermsFunction(object):
1580 class PermsFunction(object):
1578 """Base function for other check functions"""
1581 """Base function for other check functions"""
1579
1582
1580 def __init__(self, *perms):
1583 def __init__(self, *perms):
1581 self.required_perms = set(perms)
1584 self.required_perms = set(perms)
1582 self.repo_name = None
1585 self.repo_name = None
1583 self.repo_group_name = None
1586 self.repo_group_name = None
1584 self.user_group_name = None
1587 self.user_group_name = None
1585
1588
1586 def __bool__(self):
1589 def __bool__(self):
1587 frame = inspect.currentframe()
1590 frame = inspect.currentframe()
1588 stack_trace = traceback.format_stack(frame)
1591 stack_trace = traceback.format_stack(frame)
1589 log.error('Checking bool value on a class instance of perm '
1592 log.error('Checking bool value on a class instance of perm '
1590 'function is not allowed: %s' % ''.join(stack_trace))
1593 'function is not allowed: %s' % ''.join(stack_trace))
1591 # rather than throwing errors, here we always return False so if by
1594 # rather than throwing errors, here we always return False so if by
1592 # accident someone checks truth for just an instance it will always end
1595 # accident someone checks truth for just an instance it will always end
1593 # up in returning False
1596 # up in returning False
1594 return False
1597 return False
1595 __nonzero__ = __bool__
1598 __nonzero__ = __bool__
1596
1599
1597 def __call__(self, check_location='', user=None):
1600 def __call__(self, check_location='', user=None):
1598 if not user:
1601 if not user:
1599 log.debug('Using user attribute from global request')
1602 log.debug('Using user attribute from global request')
1600 # TODO: remove this someday,put as user as attribute here
1603 # TODO: remove this someday,put as user as attribute here
1601 request = self._get_request()
1604 request = self._get_request()
1602 user = request.user
1605 user = request.user
1603
1606
1604 # init auth user if not already given
1607 # init auth user if not already given
1605 if not isinstance(user, AuthUser):
1608 if not isinstance(user, AuthUser):
1606 log.debug('Wrapping user %s into AuthUser', user)
1609 log.debug('Wrapping user %s into AuthUser', user)
1607 user = AuthUser(user.user_id)
1610 user = AuthUser(user.user_id)
1608
1611
1609 cls_name = self.__class__.__name__
1612 cls_name = self.__class__.__name__
1610 check_scope = self._get_check_scope(cls_name)
1613 check_scope = self._get_check_scope(cls_name)
1611 check_location = check_location or 'unspecified location'
1614 check_location = check_location or 'unspecified location'
1612
1615
1613 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1616 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1614 self.required_perms, user, check_scope, check_location)
1617 self.required_perms, user, check_scope, check_location)
1615 if not user:
1618 if not user:
1616 log.warning('Empty user given for permission check')
1619 log.warning('Empty user given for permission check')
1617 return False
1620 return False
1618
1621
1619 if self.check_permissions(user):
1622 if self.check_permissions(user):
1620 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1623 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1621 check_scope, user, check_location)
1624 check_scope, user, check_location)
1622 return True
1625 return True
1623
1626
1624 else:
1627 else:
1625 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1628 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1626 check_scope, user, check_location)
1629 check_scope, user, check_location)
1627 return False
1630 return False
1628
1631
1629 def _get_request(self):
1632 def _get_request(self):
1630 return get_request(self)
1633 return get_request(self)
1631
1634
1632 def _get_check_scope(self, cls_name):
1635 def _get_check_scope(self, cls_name):
1633 return {
1636 return {
1634 'HasPermissionAll': 'GLOBAL',
1637 'HasPermissionAll': 'GLOBAL',
1635 'HasPermissionAny': 'GLOBAL',
1638 'HasPermissionAny': 'GLOBAL',
1636 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1639 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1637 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1640 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1638 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1641 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1639 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1642 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1640 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1643 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1641 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1644 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1642 }.get(cls_name, '?:%s' % cls_name)
1645 }.get(cls_name, '?:%s' % cls_name)
1643
1646
1644 def check_permissions(self, user):
1647 def check_permissions(self, user):
1645 """Dummy function for overriding"""
1648 """Dummy function for overriding"""
1646 raise Exception('You have to write this function in child class')
1649 raise Exception('You have to write this function in child class')
1647
1650
1648
1651
1649 class HasPermissionAll(PermsFunction):
1652 class HasPermissionAll(PermsFunction):
1650 def check_permissions(self, user):
1653 def check_permissions(self, user):
1651 perms = user.permissions_with_scope({})
1654 perms = user.permissions_with_scope({})
1652 if self.required_perms.issubset(perms.get('global')):
1655 if self.required_perms.issubset(perms.get('global')):
1653 return True
1656 return True
1654 return False
1657 return False
1655
1658
1656
1659
1657 class HasPermissionAny(PermsFunction):
1660 class HasPermissionAny(PermsFunction):
1658 def check_permissions(self, user):
1661 def check_permissions(self, user):
1659 perms = user.permissions_with_scope({})
1662 perms = user.permissions_with_scope({})
1660 if self.required_perms.intersection(perms.get('global')):
1663 if self.required_perms.intersection(perms.get('global')):
1661 return True
1664 return True
1662 return False
1665 return False
1663
1666
1664
1667
1665 class HasRepoPermissionAll(PermsFunction):
1668 class HasRepoPermissionAll(PermsFunction):
1666 def __call__(self, repo_name=None, check_location='', user=None):
1669 def __call__(self, repo_name=None, check_location='', user=None):
1667 self.repo_name = repo_name
1670 self.repo_name = repo_name
1668 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1671 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1669
1672
1670 def _get_repo_name(self):
1673 def _get_repo_name(self):
1671 if not self.repo_name:
1674 if not self.repo_name:
1672 _request = self._get_request()
1675 _request = self._get_request()
1673 self.repo_name = get_repo_slug(_request)
1676 self.repo_name = get_repo_slug(_request)
1674 return self.repo_name
1677 return self.repo_name
1675
1678
1676 def check_permissions(self, user):
1679 def check_permissions(self, user):
1677 self.repo_name = self._get_repo_name()
1680 self.repo_name = self._get_repo_name()
1678 perms = user.permissions
1681 perms = user.permissions
1679 try:
1682 try:
1680 user_perms = set([perms['repositories'][self.repo_name]])
1683 user_perms = set([perms['repositories'][self.repo_name]])
1681 except KeyError:
1684 except KeyError:
1682 return False
1685 return False
1683 if self.required_perms.issubset(user_perms):
1686 if self.required_perms.issubset(user_perms):
1684 return True
1687 return True
1685 return False
1688 return False
1686
1689
1687
1690
1688 class HasRepoPermissionAny(PermsFunction):
1691 class HasRepoPermissionAny(PermsFunction):
1689 def __call__(self, repo_name=None, check_location='', user=None):
1692 def __call__(self, repo_name=None, check_location='', user=None):
1690 self.repo_name = repo_name
1693 self.repo_name = repo_name
1691 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1694 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1692
1695
1693 def _get_repo_name(self):
1696 def _get_repo_name(self):
1694 if not self.repo_name:
1697 if not self.repo_name:
1695 _request = self._get_request()
1698 _request = self._get_request()
1696 self.repo_name = get_repo_slug(_request)
1699 self.repo_name = get_repo_slug(_request)
1697 return self.repo_name
1700 return self.repo_name
1698
1701
1699 def check_permissions(self, user):
1702 def check_permissions(self, user):
1700 self.repo_name = self._get_repo_name()
1703 self.repo_name = self._get_repo_name()
1701 perms = user.permissions
1704 perms = user.permissions
1702 try:
1705 try:
1703 user_perms = set([perms['repositories'][self.repo_name]])
1706 user_perms = set([perms['repositories'][self.repo_name]])
1704 except KeyError:
1707 except KeyError:
1705 return False
1708 return False
1706 if self.required_perms.intersection(user_perms):
1709 if self.required_perms.intersection(user_perms):
1707 return True
1710 return True
1708 return False
1711 return False
1709
1712
1710
1713
1711 class HasRepoGroupPermissionAny(PermsFunction):
1714 class HasRepoGroupPermissionAny(PermsFunction):
1712 def __call__(self, group_name=None, check_location='', user=None):
1715 def __call__(self, group_name=None, check_location='', user=None):
1713 self.repo_group_name = group_name
1716 self.repo_group_name = group_name
1714 return super(HasRepoGroupPermissionAny, self).__call__(
1717 return super(HasRepoGroupPermissionAny, self).__call__(
1715 check_location, user)
1718 check_location, user)
1716
1719
1717 def check_permissions(self, user):
1720 def check_permissions(self, user):
1718 perms = user.permissions
1721 perms = user.permissions
1719 try:
1722 try:
1720 user_perms = set(
1723 user_perms = set(
1721 [perms['repositories_groups'][self.repo_group_name]])
1724 [perms['repositories_groups'][self.repo_group_name]])
1722 except KeyError:
1725 except KeyError:
1723 return False
1726 return False
1724 if self.required_perms.intersection(user_perms):
1727 if self.required_perms.intersection(user_perms):
1725 return True
1728 return True
1726 return False
1729 return False
1727
1730
1728
1731
1729 class HasRepoGroupPermissionAll(PermsFunction):
1732 class HasRepoGroupPermissionAll(PermsFunction):
1730 def __call__(self, group_name=None, check_location='', user=None):
1733 def __call__(self, group_name=None, check_location='', user=None):
1731 self.repo_group_name = group_name
1734 self.repo_group_name = group_name
1732 return super(HasRepoGroupPermissionAll, self).__call__(
1735 return super(HasRepoGroupPermissionAll, self).__call__(
1733 check_location, user)
1736 check_location, user)
1734
1737
1735 def check_permissions(self, user):
1738 def check_permissions(self, user):
1736 perms = user.permissions
1739 perms = user.permissions
1737 try:
1740 try:
1738 user_perms = set(
1741 user_perms = set(
1739 [perms['repositories_groups'][self.repo_group_name]])
1742 [perms['repositories_groups'][self.repo_group_name]])
1740 except KeyError:
1743 except KeyError:
1741 return False
1744 return False
1742 if self.required_perms.issubset(user_perms):
1745 if self.required_perms.issubset(user_perms):
1743 return True
1746 return True
1744 return False
1747 return False
1745
1748
1746
1749
1747 class HasUserGroupPermissionAny(PermsFunction):
1750 class HasUserGroupPermissionAny(PermsFunction):
1748 def __call__(self, user_group_name=None, check_location='', user=None):
1751 def __call__(self, user_group_name=None, check_location='', user=None):
1749 self.user_group_name = user_group_name
1752 self.user_group_name = user_group_name
1750 return super(HasUserGroupPermissionAny, self).__call__(
1753 return super(HasUserGroupPermissionAny, self).__call__(
1751 check_location, user)
1754 check_location, user)
1752
1755
1753 def check_permissions(self, user):
1756 def check_permissions(self, user):
1754 perms = user.permissions
1757 perms = user.permissions
1755 try:
1758 try:
1756 user_perms = set([perms['user_groups'][self.user_group_name]])
1759 user_perms = set([perms['user_groups'][self.user_group_name]])
1757 except KeyError:
1760 except KeyError:
1758 return False
1761 return False
1759 if self.required_perms.intersection(user_perms):
1762 if self.required_perms.intersection(user_perms):
1760 return True
1763 return True
1761 return False
1764 return False
1762
1765
1763
1766
1764 class HasUserGroupPermissionAll(PermsFunction):
1767 class HasUserGroupPermissionAll(PermsFunction):
1765 def __call__(self, user_group_name=None, check_location='', user=None):
1768 def __call__(self, user_group_name=None, check_location='', user=None):
1766 self.user_group_name = user_group_name
1769 self.user_group_name = user_group_name
1767 return super(HasUserGroupPermissionAll, self).__call__(
1770 return super(HasUserGroupPermissionAll, self).__call__(
1768 check_location, user)
1771 check_location, user)
1769
1772
1770 def check_permissions(self, user):
1773 def check_permissions(self, user):
1771 perms = user.permissions
1774 perms = user.permissions
1772 try:
1775 try:
1773 user_perms = set([perms['user_groups'][self.user_group_name]])
1776 user_perms = set([perms['user_groups'][self.user_group_name]])
1774 except KeyError:
1777 except KeyError:
1775 return False
1778 return False
1776 if self.required_perms.issubset(user_perms):
1779 if self.required_perms.issubset(user_perms):
1777 return True
1780 return True
1778 return False
1781 return False
1779
1782
1780
1783
1781 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1784 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1782 class HasPermissionAnyMiddleware(object):
1785 class HasPermissionAnyMiddleware(object):
1783 def __init__(self, *perms):
1786 def __init__(self, *perms):
1784 self.required_perms = set(perms)
1787 self.required_perms = set(perms)
1785
1788
1786 def __call__(self, user, repo_name):
1789 def __call__(self, user, repo_name):
1787 # repo_name MUST be unicode, since we handle keys in permission
1790 # repo_name MUST be unicode, since we handle keys in permission
1788 # dict by unicode
1791 # dict by unicode
1789 repo_name = safe_unicode(repo_name)
1792 repo_name = safe_unicode(repo_name)
1790 user = AuthUser(user.user_id)
1793 user = AuthUser(user.user_id)
1791 log.debug(
1794 log.debug(
1792 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1795 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1793 self.required_perms, user, repo_name)
1796 self.required_perms, user, repo_name)
1794
1797
1795 if self.check_permissions(user, repo_name):
1798 if self.check_permissions(user, repo_name):
1796 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1799 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1797 repo_name, user, 'PermissionMiddleware')
1800 repo_name, user, 'PermissionMiddleware')
1798 return True
1801 return True
1799
1802
1800 else:
1803 else:
1801 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1804 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1802 repo_name, user, 'PermissionMiddleware')
1805 repo_name, user, 'PermissionMiddleware')
1803 return False
1806 return False
1804
1807
1805 def check_permissions(self, user, repo_name):
1808 def check_permissions(self, user, repo_name):
1806 perms = user.permissions_with_scope({'repo_name': repo_name})
1809 perms = user.permissions_with_scope({'repo_name': repo_name})
1807
1810
1808 try:
1811 try:
1809 user_perms = set([perms['repositories'][repo_name]])
1812 user_perms = set([perms['repositories'][repo_name]])
1810 except Exception:
1813 except Exception:
1811 log.exception('Error while accessing user permissions')
1814 log.exception('Error while accessing user permissions')
1812 return False
1815 return False
1813
1816
1814 if self.required_perms.intersection(user_perms):
1817 if self.required_perms.intersection(user_perms):
1815 return True
1818 return True
1816 return False
1819 return False
1817
1820
1818
1821
1819 # SPECIAL VERSION TO HANDLE API AUTH
1822 # SPECIAL VERSION TO HANDLE API AUTH
1820 class _BaseApiPerm(object):
1823 class _BaseApiPerm(object):
1821 def __init__(self, *perms):
1824 def __init__(self, *perms):
1822 self.required_perms = set(perms)
1825 self.required_perms = set(perms)
1823
1826
1824 def __call__(self, check_location=None, user=None, repo_name=None,
1827 def __call__(self, check_location=None, user=None, repo_name=None,
1825 group_name=None, user_group_name=None):
1828 group_name=None, user_group_name=None):
1826 cls_name = self.__class__.__name__
1829 cls_name = self.__class__.__name__
1827 check_scope = 'global:%s' % (self.required_perms,)
1830 check_scope = 'global:%s' % (self.required_perms,)
1828 if repo_name:
1831 if repo_name:
1829 check_scope += ', repo_name:%s' % (repo_name,)
1832 check_scope += ', repo_name:%s' % (repo_name,)
1830
1833
1831 if group_name:
1834 if group_name:
1832 check_scope += ', repo_group_name:%s' % (group_name,)
1835 check_scope += ', repo_group_name:%s' % (group_name,)
1833
1836
1834 if user_group_name:
1837 if user_group_name:
1835 check_scope += ', user_group_name:%s' % (user_group_name,)
1838 check_scope += ', user_group_name:%s' % (user_group_name,)
1836
1839
1837 log.debug(
1840 log.debug(
1838 'checking cls:%s %s %s @ %s'
1841 'checking cls:%s %s %s @ %s'
1839 % (cls_name, self.required_perms, check_scope, check_location))
1842 % (cls_name, self.required_perms, check_scope, check_location))
1840 if not user:
1843 if not user:
1841 log.debug('Empty User passed into arguments')
1844 log.debug('Empty User passed into arguments')
1842 return False
1845 return False
1843
1846
1844 # process user
1847 # process user
1845 if not isinstance(user, AuthUser):
1848 if not isinstance(user, AuthUser):
1846 user = AuthUser(user.user_id)
1849 user = AuthUser(user.user_id)
1847 if not check_location:
1850 if not check_location:
1848 check_location = 'unspecified'
1851 check_location = 'unspecified'
1849 if self.check_permissions(user.permissions, repo_name, group_name,
1852 if self.check_permissions(user.permissions, repo_name, group_name,
1850 user_group_name):
1853 user_group_name):
1851 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1854 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1852 check_scope, user, check_location)
1855 check_scope, user, check_location)
1853 return True
1856 return True
1854
1857
1855 else:
1858 else:
1856 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1859 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1857 check_scope, user, check_location)
1860 check_scope, user, check_location)
1858 return False
1861 return False
1859
1862
1860 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1863 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1861 user_group_name=None):
1864 user_group_name=None):
1862 """
1865 """
1863 implement in child class should return True if permissions are ok,
1866 implement in child class should return True if permissions are ok,
1864 False otherwise
1867 False otherwise
1865
1868
1866 :param perm_defs: dict with permission definitions
1869 :param perm_defs: dict with permission definitions
1867 :param repo_name: repo name
1870 :param repo_name: repo name
1868 """
1871 """
1869 raise NotImplementedError()
1872 raise NotImplementedError()
1870
1873
1871
1874
1872 class HasPermissionAllApi(_BaseApiPerm):
1875 class HasPermissionAllApi(_BaseApiPerm):
1873 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1876 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1874 user_group_name=None):
1877 user_group_name=None):
1875 if self.required_perms.issubset(perm_defs.get('global')):
1878 if self.required_perms.issubset(perm_defs.get('global')):
1876 return True
1879 return True
1877 return False
1880 return False
1878
1881
1879
1882
1880 class HasPermissionAnyApi(_BaseApiPerm):
1883 class HasPermissionAnyApi(_BaseApiPerm):
1881 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1884 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1882 user_group_name=None):
1885 user_group_name=None):
1883 if self.required_perms.intersection(perm_defs.get('global')):
1886 if self.required_perms.intersection(perm_defs.get('global')):
1884 return True
1887 return True
1885 return False
1888 return False
1886
1889
1887
1890
1888 class HasRepoPermissionAllApi(_BaseApiPerm):
1891 class HasRepoPermissionAllApi(_BaseApiPerm):
1889 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1892 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1890 user_group_name=None):
1893 user_group_name=None):
1891 try:
1894 try:
1892 _user_perms = set([perm_defs['repositories'][repo_name]])
1895 _user_perms = set([perm_defs['repositories'][repo_name]])
1893 except KeyError:
1896 except KeyError:
1894 log.warning(traceback.format_exc())
1897 log.warning(traceback.format_exc())
1895 return False
1898 return False
1896 if self.required_perms.issubset(_user_perms):
1899 if self.required_perms.issubset(_user_perms):
1897 return True
1900 return True
1898 return False
1901 return False
1899
1902
1900
1903
1901 class HasRepoPermissionAnyApi(_BaseApiPerm):
1904 class HasRepoPermissionAnyApi(_BaseApiPerm):
1902 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1905 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1903 user_group_name=None):
1906 user_group_name=None):
1904 try:
1907 try:
1905 _user_perms = set([perm_defs['repositories'][repo_name]])
1908 _user_perms = set([perm_defs['repositories'][repo_name]])
1906 except KeyError:
1909 except KeyError:
1907 log.warning(traceback.format_exc())
1910 log.warning(traceback.format_exc())
1908 return False
1911 return False
1909 if self.required_perms.intersection(_user_perms):
1912 if self.required_perms.intersection(_user_perms):
1910 return True
1913 return True
1911 return False
1914 return False
1912
1915
1913
1916
1914 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1917 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1915 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1918 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1916 user_group_name=None):
1919 user_group_name=None):
1917 try:
1920 try:
1918 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1921 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1919 except KeyError:
1922 except KeyError:
1920 log.warning(traceback.format_exc())
1923 log.warning(traceback.format_exc())
1921 return False
1924 return False
1922 if self.required_perms.intersection(_user_perms):
1925 if self.required_perms.intersection(_user_perms):
1923 return True
1926 return True
1924 return False
1927 return False
1925
1928
1926
1929
1927 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1930 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1928 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1931 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1929 user_group_name=None):
1932 user_group_name=None):
1930 try:
1933 try:
1931 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1934 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1932 except KeyError:
1935 except KeyError:
1933 log.warning(traceback.format_exc())
1936 log.warning(traceback.format_exc())
1934 return False
1937 return False
1935 if self.required_perms.issubset(_user_perms):
1938 if self.required_perms.issubset(_user_perms):
1936 return True
1939 return True
1937 return False
1940 return False
1938
1941
1939
1942
1940 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1943 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1941 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1944 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1942 user_group_name=None):
1945 user_group_name=None):
1943 try:
1946 try:
1944 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1947 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1945 except KeyError:
1948 except KeyError:
1946 log.warning(traceback.format_exc())
1949 log.warning(traceback.format_exc())
1947 return False
1950 return False
1948 if self.required_perms.intersection(_user_perms):
1951 if self.required_perms.intersection(_user_perms):
1949 return True
1952 return True
1950 return False
1953 return False
1951
1954
1952
1955
1953 def check_ip_access(source_ip, allowed_ips=None):
1956 def check_ip_access(source_ip, allowed_ips=None):
1954 """
1957 """
1955 Checks if source_ip is a subnet of any of allowed_ips.
1958 Checks if source_ip is a subnet of any of allowed_ips.
1956
1959
1957 :param source_ip:
1960 :param source_ip:
1958 :param allowed_ips: list of allowed ips together with mask
1961 :param allowed_ips: list of allowed ips together with mask
1959 """
1962 """
1960 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1963 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1961 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
1964 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
1962 if isinstance(allowed_ips, (tuple, list, set)):
1965 if isinstance(allowed_ips, (tuple, list, set)):
1963 for ip in allowed_ips:
1966 for ip in allowed_ips:
1964 ip = safe_unicode(ip)
1967 ip = safe_unicode(ip)
1965 try:
1968 try:
1966 network_address = ipaddress.ip_network(ip, strict=False)
1969 network_address = ipaddress.ip_network(ip, strict=False)
1967 if source_ip_address in network_address:
1970 if source_ip_address in network_address:
1968 log.debug('IP %s is network %s' %
1971 log.debug('IP %s is network %s' %
1969 (source_ip_address, network_address))
1972 (source_ip_address, network_address))
1970 return True
1973 return True
1971 # for any case we cannot determine the IP, don't crash just
1974 # for any case we cannot determine the IP, don't crash just
1972 # skip it and log as error, we want to say forbidden still when
1975 # skip it and log as error, we want to say forbidden still when
1973 # sending bad IP
1976 # sending bad IP
1974 except Exception:
1977 except Exception:
1975 log.error(traceback.format_exc())
1978 log.error(traceback.format_exc())
1976 continue
1979 continue
1977 return False
1980 return False
1978
1981
1979
1982
1980 def get_cython_compat_decorator(wrapper, func):
1983 def get_cython_compat_decorator(wrapper, func):
1981 """
1984 """
1982 Creates a cython compatible decorator. The previously used
1985 Creates a cython compatible decorator. The previously used
1983 decorator.decorator() function seems to be incompatible with cython.
1986 decorator.decorator() function seems to be incompatible with cython.
1984
1987
1985 :param wrapper: __wrapper method of the decorator class
1988 :param wrapper: __wrapper method of the decorator class
1986 :param func: decorated function
1989 :param func: decorated function
1987 """
1990 """
1988 @wraps(func)
1991 @wraps(func)
1989 def local_wrapper(*args, **kwds):
1992 def local_wrapper(*args, **kwds):
1990 return wrapper(func, *args, **kwds)
1993 return wrapper(func, *args, **kwds)
1991 local_wrapper.__wrapped__ = func
1994 local_wrapper.__wrapped__ = func
1992 return local_wrapper
1995 return local_wrapper
1993
1996
1994
1997
@@ -1,982 +1,997 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-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 """
21 """
22 Utilities library for RhodeCode
22 Utilities library for RhodeCode
23 """
23 """
24
24
25 import datetime
25 import datetime
26 import decorator
26 import decorator
27 import json
27 import json
28 import logging
28 import logging
29 import os
29 import os
30 import re
30 import re
31 import shutil
31 import shutil
32 import tempfile
32 import tempfile
33 import traceback
33 import traceback
34 import tarfile
34 import tarfile
35 import warnings
35 import warnings
36 import hashlib
36 import hashlib
37 from os.path import join as jn
37 from os.path import join as jn
38
38
39 import paste
39 import paste
40 import pkg_resources
40 import pkg_resources
41 from paste.script.command import Command, BadCommand
41 from paste.script.command import Command, BadCommand
42 from webhelpers.text import collapse, remove_formatting, strip_tags
42 from webhelpers.text import collapse, remove_formatting, strip_tags
43 from mako import exceptions
43 from mako import exceptions
44 from pyramid.threadlocal import get_current_registry
44 from pyramid.threadlocal import get_current_registry
45 from pyramid.request import Request
45 from pyramid.request import Request
46
46
47 from rhodecode.lib.fakemod import create_module
47 from rhodecode.lib.fakemod import create_module
48 from rhodecode.lib.vcs.backends.base import Config
48 from rhodecode.lib.vcs.backends.base import Config
49 from rhodecode.lib.vcs.exceptions import VCSError
49 from rhodecode.lib.vcs.exceptions import VCSError
50 from rhodecode.lib.vcs.utils.helpers import get_scm, get_scm_backend
50 from rhodecode.lib.vcs.utils.helpers import get_scm, get_scm_backend
51 from rhodecode.lib.utils2 import (
51 from rhodecode.lib.utils2 import (
52 safe_str, safe_unicode, get_current_rhodecode_user, md5)
52 safe_str, safe_unicode, get_current_rhodecode_user, md5)
53 from rhodecode.model import meta
53 from rhodecode.model import meta
54 from rhodecode.model.db import (
54 from rhodecode.model.db import (
55 Repository, User, RhodeCodeUi, UserLog, RepoGroup, UserGroup)
55 Repository, User, RhodeCodeUi, UserLog, RepoGroup, UserGroup)
56 from rhodecode.model.meta import Session
56 from rhodecode.model.meta import Session
57
57
58
58
59 log = logging.getLogger(__name__)
59 log = logging.getLogger(__name__)
60
60
61 REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*')
61 REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*')
62
62
63 # String which contains characters that are not allowed in slug names for
63 # String which contains characters that are not allowed in slug names for
64 # repositories or repository groups. It is properly escaped to use it in
64 # repositories or repository groups. It is properly escaped to use it in
65 # regular expressions.
65 # regular expressions.
66 SLUG_BAD_CHARS = re.escape('`?=[]\;\'"<>,/~!@#$%^&*()+{}|:')
66 SLUG_BAD_CHARS = re.escape('`?=[]\;\'"<>,/~!@#$%^&*()+{}|:')
67
67
68 # Regex that matches forbidden characters in repo/group slugs.
68 # Regex that matches forbidden characters in repo/group slugs.
69 SLUG_BAD_CHAR_RE = re.compile('[{}]'.format(SLUG_BAD_CHARS))
69 SLUG_BAD_CHAR_RE = re.compile('[{}]'.format(SLUG_BAD_CHARS))
70
70
71 # Regex that matches allowed characters in repo/group slugs.
71 # Regex that matches allowed characters in repo/group slugs.
72 SLUG_GOOD_CHAR_RE = re.compile('[^{}]'.format(SLUG_BAD_CHARS))
72 SLUG_GOOD_CHAR_RE = re.compile('[^{}]'.format(SLUG_BAD_CHARS))
73
73
74 # Regex that matches whole repo/group slugs.
74 # Regex that matches whole repo/group slugs.
75 SLUG_RE = re.compile('[^{}]+'.format(SLUG_BAD_CHARS))
75 SLUG_RE = re.compile('[^{}]+'.format(SLUG_BAD_CHARS))
76
76
77 _license_cache = None
77 _license_cache = None
78
78
79
79
80 def repo_name_slug(value):
80 def repo_name_slug(value):
81 """
81 """
82 Return slug of name of repository
82 Return slug of name of repository
83 This function is called on each creation/modification
83 This function is called on each creation/modification
84 of repository to prevent bad names in repo
84 of repository to prevent bad names in repo
85 """
85 """
86 replacement_char = '-'
86 replacement_char = '-'
87
87
88 slug = remove_formatting(value)
88 slug = remove_formatting(value)
89 slug = SLUG_BAD_CHAR_RE.sub('', slug)
89 slug = SLUG_BAD_CHAR_RE.sub('', slug)
90 slug = re.sub('[\s]+', '-', slug)
90 slug = re.sub('[\s]+', '-', slug)
91 slug = collapse(slug, replacement_char)
91 slug = collapse(slug, replacement_char)
92 return slug
92 return slug
93
93
94
94
95 #==============================================================================
95 #==============================================================================
96 # PERM DECORATOR HELPERS FOR EXTRACTING NAMES FOR PERM CHECKS
96 # PERM DECORATOR HELPERS FOR EXTRACTING NAMES FOR PERM CHECKS
97 #==============================================================================
97 #==============================================================================
98 def get_repo_slug(request):
98 def get_repo_slug(request):
99 if isinstance(request, Request) and getattr(request, 'db_repo', None):
99 _repo = ''
100 # pyramid
100 if isinstance(request, Request):
101 _repo = request.db_repo.repo_name
101 if hasattr(request, 'db_repo'):
102 else:
102 # if our requests has set db reference use it for name, this
103 # TODO(marcink): remove after pylons migration...
103 # translates the example.com/_<id> into proper repo names
104 _repo = request.db_repo.repo_name
105 elif getattr(request, 'matchdict', None):
106 # pyramid
107 _repo = request.matchdict.get('repo_name')
108
109 # TODO(marcink): remove after pylons migration...
110 if not _repo:
104 _repo = request.environ['pylons.routes_dict'].get('repo_name')
111 _repo = request.environ['pylons.routes_dict'].get('repo_name')
105
112
106 if _repo:
113 if _repo:
107 _repo = _repo.rstrip('/')
114 _repo = _repo.rstrip('/')
108 return _repo
115 return _repo
109
116
110
117
111 def get_repo_group_slug(request):
118 def get_repo_group_slug(request):
112 if isinstance(request, Request) and getattr(request, 'matchdict', None):
119 _group = ''
113 # pyramid
120 if isinstance(request, Request):
114 _group = request.matchdict.get('repo_group_name')
121 if hasattr(request, 'db_repo_group'):
115 else:
122 # if our requests has set db reference use it for name, this
123 # translates the example.com/_<id> into proper repo group names
124 _group = request.db_repo_group.group_name
125 elif getattr(request, 'matchdict', None):
126 # pyramid
127 _group = request.matchdict.get('repo_group_name')
128
129 # TODO(marcink): remove after pylons migration...
130 if not _group:
116 _group = request.environ['pylons.routes_dict'].get('group_name')
131 _group = request.environ['pylons.routes_dict'].get('group_name')
117
132
118 if _group:
133 if _group:
119 _group = _group.rstrip('/')
134 _group = _group.rstrip('/')
120 return _group
135 return _group
121
136
122
137
123 def get_user_group_slug(request):
138 def get_user_group_slug(request):
124 if isinstance(request, Request) and getattr(request, 'matchdict', None):
139 if isinstance(request, Request) and getattr(request, 'matchdict', None):
125 # pyramid
140 # pyramid
126 _group = request.matchdict.get('user_group_id')
141 _group = request.matchdict.get('user_group_id')
127 else:
142 else:
128 _group = request.environ['pylons.routes_dict'].get('user_group_id')
143 _group = request.environ['pylons.routes_dict'].get('user_group_id')
129
144
130 try:
145 try:
131 _group = UserGroup.get(_group)
146 _group = UserGroup.get(_group)
132 if _group:
147 if _group:
133 _group = _group.users_group_name
148 _group = _group.users_group_name
134 except Exception:
149 except Exception:
135 log.exception('Failed to get user group by id')
150 log.exception('Failed to get user group by id')
136 # catch all failures here
151 # catch all failures here
137 return None
152 return None
138
153
139 return _group
154 return _group
140
155
141
156
142 def get_filesystem_repos(path, recursive=False, skip_removed_repos=True):
157 def get_filesystem_repos(path, recursive=False, skip_removed_repos=True):
143 """
158 """
144 Scans given path for repos and return (name,(type,path)) tuple
159 Scans given path for repos and return (name,(type,path)) tuple
145
160
146 :param path: path to scan for repositories
161 :param path: path to scan for repositories
147 :param recursive: recursive search and return names with subdirs in front
162 :param recursive: recursive search and return names with subdirs in front
148 """
163 """
149
164
150 # remove ending slash for better results
165 # remove ending slash for better results
151 path = path.rstrip(os.sep)
166 path = path.rstrip(os.sep)
152 log.debug('now scanning in %s location recursive:%s...', path, recursive)
167 log.debug('now scanning in %s location recursive:%s...', path, recursive)
153
168
154 def _get_repos(p):
169 def _get_repos(p):
155 dirpaths = _get_dirpaths(p)
170 dirpaths = _get_dirpaths(p)
156 if not _is_dir_writable(p):
171 if not _is_dir_writable(p):
157 log.warning('repo path without write access: %s', p)
172 log.warning('repo path without write access: %s', p)
158
173
159 for dirpath in dirpaths:
174 for dirpath in dirpaths:
160 if os.path.isfile(os.path.join(p, dirpath)):
175 if os.path.isfile(os.path.join(p, dirpath)):
161 continue
176 continue
162 cur_path = os.path.join(p, dirpath)
177 cur_path = os.path.join(p, dirpath)
163
178
164 # skip removed repos
179 # skip removed repos
165 if skip_removed_repos and REMOVED_REPO_PAT.match(dirpath):
180 if skip_removed_repos and REMOVED_REPO_PAT.match(dirpath):
166 continue
181 continue
167
182
168 #skip .<somethin> dirs
183 #skip .<somethin> dirs
169 if dirpath.startswith('.'):
184 if dirpath.startswith('.'):
170 continue
185 continue
171
186
172 try:
187 try:
173 scm_info = get_scm(cur_path)
188 scm_info = get_scm(cur_path)
174 yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info
189 yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info
175 except VCSError:
190 except VCSError:
176 if not recursive:
191 if not recursive:
177 continue
192 continue
178 #check if this dir containts other repos for recursive scan
193 #check if this dir containts other repos for recursive scan
179 rec_path = os.path.join(p, dirpath)
194 rec_path = os.path.join(p, dirpath)
180 if os.path.isdir(rec_path):
195 if os.path.isdir(rec_path):
181 for inner_scm in _get_repos(rec_path):
196 for inner_scm in _get_repos(rec_path):
182 yield inner_scm
197 yield inner_scm
183
198
184 return _get_repos(path)
199 return _get_repos(path)
185
200
186
201
187 def _get_dirpaths(p):
202 def _get_dirpaths(p):
188 try:
203 try:
189 # OS-independable way of checking if we have at least read-only
204 # OS-independable way of checking if we have at least read-only
190 # access or not.
205 # access or not.
191 dirpaths = os.listdir(p)
206 dirpaths = os.listdir(p)
192 except OSError:
207 except OSError:
193 log.warning('ignoring repo path without read access: %s', p)
208 log.warning('ignoring repo path without read access: %s', p)
194 return []
209 return []
195
210
196 # os.listpath has a tweak: If a unicode is passed into it, then it tries to
211 # os.listpath has a tweak: If a unicode is passed into it, then it tries to
197 # decode paths and suddenly returns unicode objects itself. The items it
212 # decode paths and suddenly returns unicode objects itself. The items it
198 # cannot decode are returned as strings and cause issues.
213 # cannot decode are returned as strings and cause issues.
199 #
214 #
200 # Those paths are ignored here until a solid solution for path handling has
215 # Those paths are ignored here until a solid solution for path handling has
201 # been built.
216 # been built.
202 expected_type = type(p)
217 expected_type = type(p)
203
218
204 def _has_correct_type(item):
219 def _has_correct_type(item):
205 if type(item) is not expected_type:
220 if type(item) is not expected_type:
206 log.error(
221 log.error(
207 u"Ignoring path %s since it cannot be decoded into unicode.",
222 u"Ignoring path %s since it cannot be decoded into unicode.",
208 # Using "repr" to make sure that we see the byte value in case
223 # Using "repr" to make sure that we see the byte value in case
209 # of support.
224 # of support.
210 repr(item))
225 repr(item))
211 return False
226 return False
212 return True
227 return True
213
228
214 dirpaths = [item for item in dirpaths if _has_correct_type(item)]
229 dirpaths = [item for item in dirpaths if _has_correct_type(item)]
215
230
216 return dirpaths
231 return dirpaths
217
232
218
233
219 def _is_dir_writable(path):
234 def _is_dir_writable(path):
220 """
235 """
221 Probe if `path` is writable.
236 Probe if `path` is writable.
222
237
223 Due to trouble on Cygwin / Windows, this is actually probing if it is
238 Due to trouble on Cygwin / Windows, this is actually probing if it is
224 possible to create a file inside of `path`, stat does not produce reliable
239 possible to create a file inside of `path`, stat does not produce reliable
225 results in this case.
240 results in this case.
226 """
241 """
227 try:
242 try:
228 with tempfile.TemporaryFile(dir=path):
243 with tempfile.TemporaryFile(dir=path):
229 pass
244 pass
230 except OSError:
245 except OSError:
231 return False
246 return False
232 return True
247 return True
233
248
234
249
235 def is_valid_repo(repo_name, base_path, expect_scm=None, explicit_scm=None):
250 def is_valid_repo(repo_name, base_path, expect_scm=None, explicit_scm=None):
236 """
251 """
237 Returns True if given path is a valid repository False otherwise.
252 Returns True if given path is a valid repository False otherwise.
238 If expect_scm param is given also, compare if given scm is the same
253 If expect_scm param is given also, compare if given scm is the same
239 as expected from scm parameter. If explicit_scm is given don't try to
254 as expected from scm parameter. If explicit_scm is given don't try to
240 detect the scm, just use the given one to check if repo is valid
255 detect the scm, just use the given one to check if repo is valid
241
256
242 :param repo_name:
257 :param repo_name:
243 :param base_path:
258 :param base_path:
244 :param expect_scm:
259 :param expect_scm:
245 :param explicit_scm:
260 :param explicit_scm:
246
261
247 :return True: if given path is a valid repository
262 :return True: if given path is a valid repository
248 """
263 """
249 full_path = os.path.join(safe_str(base_path), safe_str(repo_name))
264 full_path = os.path.join(safe_str(base_path), safe_str(repo_name))
250 log.debug('Checking if `%s` is a valid path for repository. '
265 log.debug('Checking if `%s` is a valid path for repository. '
251 'Explicit type: %s', repo_name, explicit_scm)
266 'Explicit type: %s', repo_name, explicit_scm)
252
267
253 try:
268 try:
254 if explicit_scm:
269 if explicit_scm:
255 detected_scms = [get_scm_backend(explicit_scm)]
270 detected_scms = [get_scm_backend(explicit_scm)]
256 else:
271 else:
257 detected_scms = get_scm(full_path)
272 detected_scms = get_scm(full_path)
258
273
259 if expect_scm:
274 if expect_scm:
260 return detected_scms[0] == expect_scm
275 return detected_scms[0] == expect_scm
261 log.debug('path: %s is an vcs object:%s', full_path, detected_scms)
276 log.debug('path: %s is an vcs object:%s', full_path, detected_scms)
262 return True
277 return True
263 except VCSError:
278 except VCSError:
264 log.debug('path: %s is not a valid repo !', full_path)
279 log.debug('path: %s is not a valid repo !', full_path)
265 return False
280 return False
266
281
267
282
268 def is_valid_repo_group(repo_group_name, base_path, skip_path_check=False):
283 def is_valid_repo_group(repo_group_name, base_path, skip_path_check=False):
269 """
284 """
270 Returns True if given path is a repository group, False otherwise
285 Returns True if given path is a repository group, False otherwise
271
286
272 :param repo_name:
287 :param repo_name:
273 :param base_path:
288 :param base_path:
274 """
289 """
275 full_path = os.path.join(safe_str(base_path), safe_str(repo_group_name))
290 full_path = os.path.join(safe_str(base_path), safe_str(repo_group_name))
276 log.debug('Checking if `%s` is a valid path for repository group',
291 log.debug('Checking if `%s` is a valid path for repository group',
277 repo_group_name)
292 repo_group_name)
278
293
279 # check if it's not a repo
294 # check if it's not a repo
280 if is_valid_repo(repo_group_name, base_path):
295 if is_valid_repo(repo_group_name, base_path):
281 log.debug('Repo called %s exist, it is not a valid '
296 log.debug('Repo called %s exist, it is not a valid '
282 'repo group' % repo_group_name)
297 'repo group' % repo_group_name)
283 return False
298 return False
284
299
285 try:
300 try:
286 # we need to check bare git repos at higher level
301 # we need to check bare git repos at higher level
287 # since we might match branches/hooks/info/objects or possible
302 # since we might match branches/hooks/info/objects or possible
288 # other things inside bare git repo
303 # other things inside bare git repo
289 scm_ = get_scm(os.path.dirname(full_path))
304 scm_ = get_scm(os.path.dirname(full_path))
290 log.debug('path: %s is a vcs object:%s, not valid '
305 log.debug('path: %s is a vcs object:%s, not valid '
291 'repo group' % (full_path, scm_))
306 'repo group' % (full_path, scm_))
292 return False
307 return False
293 except VCSError:
308 except VCSError:
294 pass
309 pass
295
310
296 # check if it's a valid path
311 # check if it's a valid path
297 if skip_path_check or os.path.isdir(full_path):
312 if skip_path_check or os.path.isdir(full_path):
298 log.debug('path: %s is a valid repo group !', full_path)
313 log.debug('path: %s is a valid repo group !', full_path)
299 return True
314 return True
300
315
301 log.debug('path: %s is not a valid repo group !', full_path)
316 log.debug('path: %s is not a valid repo group !', full_path)
302 return False
317 return False
303
318
304
319
305 def ask_ok(prompt, retries=4, complaint='[y]es or [n]o please!'):
320 def ask_ok(prompt, retries=4, complaint='[y]es or [n]o please!'):
306 while True:
321 while True:
307 ok = raw_input(prompt)
322 ok = raw_input(prompt)
308 if ok.lower() in ('y', 'ye', 'yes'):
323 if ok.lower() in ('y', 'ye', 'yes'):
309 return True
324 return True
310 if ok.lower() in ('n', 'no', 'nop', 'nope'):
325 if ok.lower() in ('n', 'no', 'nop', 'nope'):
311 return False
326 return False
312 retries = retries - 1
327 retries = retries - 1
313 if retries < 0:
328 if retries < 0:
314 raise IOError
329 raise IOError
315 print(complaint)
330 print(complaint)
316
331
317 # propagated from mercurial documentation
332 # propagated from mercurial documentation
318 ui_sections = [
333 ui_sections = [
319 'alias', 'auth',
334 'alias', 'auth',
320 'decode/encode', 'defaults',
335 'decode/encode', 'defaults',
321 'diff', 'email',
336 'diff', 'email',
322 'extensions', 'format',
337 'extensions', 'format',
323 'merge-patterns', 'merge-tools',
338 'merge-patterns', 'merge-tools',
324 'hooks', 'http_proxy',
339 'hooks', 'http_proxy',
325 'smtp', 'patch',
340 'smtp', 'patch',
326 'paths', 'profiling',
341 'paths', 'profiling',
327 'server', 'trusted',
342 'server', 'trusted',
328 'ui', 'web', ]
343 'ui', 'web', ]
329
344
330
345
331 def config_data_from_db(clear_session=True, repo=None):
346 def config_data_from_db(clear_session=True, repo=None):
332 """
347 """
333 Read the configuration data from the database and return configuration
348 Read the configuration data from the database and return configuration
334 tuples.
349 tuples.
335 """
350 """
336 from rhodecode.model.settings import VcsSettingsModel
351 from rhodecode.model.settings import VcsSettingsModel
337
352
338 config = []
353 config = []
339
354
340 sa = meta.Session()
355 sa = meta.Session()
341 settings_model = VcsSettingsModel(repo=repo, sa=sa)
356 settings_model = VcsSettingsModel(repo=repo, sa=sa)
342
357
343 ui_settings = settings_model.get_ui_settings()
358 ui_settings = settings_model.get_ui_settings()
344
359
345 for setting in ui_settings:
360 for setting in ui_settings:
346 if setting.active:
361 if setting.active:
347 log.debug(
362 log.debug(
348 'settings ui from db: [%s] %s=%s',
363 'settings ui from db: [%s] %s=%s',
349 setting.section, setting.key, setting.value)
364 setting.section, setting.key, setting.value)
350 config.append((
365 config.append((
351 safe_str(setting.section), safe_str(setting.key),
366 safe_str(setting.section), safe_str(setting.key),
352 safe_str(setting.value)))
367 safe_str(setting.value)))
353 if setting.key == 'push_ssl':
368 if setting.key == 'push_ssl':
354 # force set push_ssl requirement to False, rhodecode
369 # force set push_ssl requirement to False, rhodecode
355 # handles that
370 # handles that
356 config.append((
371 config.append((
357 safe_str(setting.section), safe_str(setting.key), False))
372 safe_str(setting.section), safe_str(setting.key), False))
358 if clear_session:
373 if clear_session:
359 meta.Session.remove()
374 meta.Session.remove()
360
375
361 # TODO: mikhail: probably it makes no sense to re-read hooks information.
376 # TODO: mikhail: probably it makes no sense to re-read hooks information.
362 # It's already there and activated/deactivated
377 # It's already there and activated/deactivated
363 skip_entries = []
378 skip_entries = []
364 enabled_hook_classes = get_enabled_hook_classes(ui_settings)
379 enabled_hook_classes = get_enabled_hook_classes(ui_settings)
365 if 'pull' not in enabled_hook_classes:
380 if 'pull' not in enabled_hook_classes:
366 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PULL))
381 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PULL))
367 if 'push' not in enabled_hook_classes:
382 if 'push' not in enabled_hook_classes:
368 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PUSH))
383 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PUSH))
369 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRETX_PUSH))
384 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRETX_PUSH))
370 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PUSH_KEY))
385 skip_entries.append(('hooks', RhodeCodeUi.HOOK_PUSH_KEY))
371
386
372 config = [entry for entry in config if entry[:2] not in skip_entries]
387 config = [entry for entry in config if entry[:2] not in skip_entries]
373
388
374 return config
389 return config
375
390
376
391
377 def make_db_config(clear_session=True, repo=None):
392 def make_db_config(clear_session=True, repo=None):
378 """
393 """
379 Create a :class:`Config` instance based on the values in the database.
394 Create a :class:`Config` instance based on the values in the database.
380 """
395 """
381 config = Config()
396 config = Config()
382 config_data = config_data_from_db(clear_session=clear_session, repo=repo)
397 config_data = config_data_from_db(clear_session=clear_session, repo=repo)
383 for section, option, value in config_data:
398 for section, option, value in config_data:
384 config.set(section, option, value)
399 config.set(section, option, value)
385 return config
400 return config
386
401
387
402
388 def get_enabled_hook_classes(ui_settings):
403 def get_enabled_hook_classes(ui_settings):
389 """
404 """
390 Return the enabled hook classes.
405 Return the enabled hook classes.
391
406
392 :param ui_settings: List of ui_settings as returned
407 :param ui_settings: List of ui_settings as returned
393 by :meth:`VcsSettingsModel.get_ui_settings`
408 by :meth:`VcsSettingsModel.get_ui_settings`
394
409
395 :return: a list with the enabled hook classes. The order is not guaranteed.
410 :return: a list with the enabled hook classes. The order is not guaranteed.
396 :rtype: list
411 :rtype: list
397 """
412 """
398 enabled_hooks = []
413 enabled_hooks = []
399 active_hook_keys = [
414 active_hook_keys = [
400 key for section, key, value, active in ui_settings
415 key for section, key, value, active in ui_settings
401 if section == 'hooks' and active]
416 if section == 'hooks' and active]
402
417
403 hook_names = {
418 hook_names = {
404 RhodeCodeUi.HOOK_PUSH: 'push',
419 RhodeCodeUi.HOOK_PUSH: 'push',
405 RhodeCodeUi.HOOK_PULL: 'pull',
420 RhodeCodeUi.HOOK_PULL: 'pull',
406 RhodeCodeUi.HOOK_REPO_SIZE: 'repo_size'
421 RhodeCodeUi.HOOK_REPO_SIZE: 'repo_size'
407 }
422 }
408
423
409 for key in active_hook_keys:
424 for key in active_hook_keys:
410 hook = hook_names.get(key)
425 hook = hook_names.get(key)
411 if hook:
426 if hook:
412 enabled_hooks.append(hook)
427 enabled_hooks.append(hook)
413
428
414 return enabled_hooks
429 return enabled_hooks
415
430
416
431
417 def set_rhodecode_config(config):
432 def set_rhodecode_config(config):
418 """
433 """
419 Updates pylons config with new settings from database
434 Updates pylons config with new settings from database
420
435
421 :param config:
436 :param config:
422 """
437 """
423 from rhodecode.model.settings import SettingsModel
438 from rhodecode.model.settings import SettingsModel
424 app_settings = SettingsModel().get_all_settings()
439 app_settings = SettingsModel().get_all_settings()
425
440
426 for k, v in app_settings.items():
441 for k, v in app_settings.items():
427 config[k] = v
442 config[k] = v
428
443
429
444
430 def get_rhodecode_realm():
445 def get_rhodecode_realm():
431 """
446 """
432 Return the rhodecode realm from database.
447 Return the rhodecode realm from database.
433 """
448 """
434 from rhodecode.model.settings import SettingsModel
449 from rhodecode.model.settings import SettingsModel
435 realm = SettingsModel().get_setting_by_name('realm')
450 realm = SettingsModel().get_setting_by_name('realm')
436 return safe_str(realm.app_settings_value)
451 return safe_str(realm.app_settings_value)
437
452
438
453
439 def get_rhodecode_base_path():
454 def get_rhodecode_base_path():
440 """
455 """
441 Returns the base path. The base path is the filesystem path which points
456 Returns the base path. The base path is the filesystem path which points
442 to the repository store.
457 to the repository store.
443 """
458 """
444 from rhodecode.model.settings import SettingsModel
459 from rhodecode.model.settings import SettingsModel
445 paths_ui = SettingsModel().get_ui_by_section_and_key('paths', '/')
460 paths_ui = SettingsModel().get_ui_by_section_and_key('paths', '/')
446 return safe_str(paths_ui.ui_value)
461 return safe_str(paths_ui.ui_value)
447
462
448
463
449 def map_groups(path):
464 def map_groups(path):
450 """
465 """
451 Given a full path to a repository, create all nested groups that this
466 Given a full path to a repository, create all nested groups that this
452 repo is inside. This function creates parent-child relationships between
467 repo is inside. This function creates parent-child relationships between
453 groups and creates default perms for all new groups.
468 groups and creates default perms for all new groups.
454
469
455 :param paths: full path to repository
470 :param paths: full path to repository
456 """
471 """
457 from rhodecode.model.repo_group import RepoGroupModel
472 from rhodecode.model.repo_group import RepoGroupModel
458 sa = meta.Session()
473 sa = meta.Session()
459 groups = path.split(Repository.NAME_SEP)
474 groups = path.split(Repository.NAME_SEP)
460 parent = None
475 parent = None
461 group = None
476 group = None
462
477
463 # last element is repo in nested groups structure
478 # last element is repo in nested groups structure
464 groups = groups[:-1]
479 groups = groups[:-1]
465 rgm = RepoGroupModel(sa)
480 rgm = RepoGroupModel(sa)
466 owner = User.get_first_super_admin()
481 owner = User.get_first_super_admin()
467 for lvl, group_name in enumerate(groups):
482 for lvl, group_name in enumerate(groups):
468 group_name = '/'.join(groups[:lvl] + [group_name])
483 group_name = '/'.join(groups[:lvl] + [group_name])
469 group = RepoGroup.get_by_group_name(group_name)
484 group = RepoGroup.get_by_group_name(group_name)
470 desc = '%s group' % group_name
485 desc = '%s group' % group_name
471
486
472 # skip folders that are now removed repos
487 # skip folders that are now removed repos
473 if REMOVED_REPO_PAT.match(group_name):
488 if REMOVED_REPO_PAT.match(group_name):
474 break
489 break
475
490
476 if group is None:
491 if group is None:
477 log.debug('creating group level: %s group_name: %s',
492 log.debug('creating group level: %s group_name: %s',
478 lvl, group_name)
493 lvl, group_name)
479 group = RepoGroup(group_name, parent)
494 group = RepoGroup(group_name, parent)
480 group.group_description = desc
495 group.group_description = desc
481 group.user = owner
496 group.user = owner
482 sa.add(group)
497 sa.add(group)
483 perm_obj = rgm._create_default_perms(group)
498 perm_obj = rgm._create_default_perms(group)
484 sa.add(perm_obj)
499 sa.add(perm_obj)
485 sa.flush()
500 sa.flush()
486
501
487 parent = group
502 parent = group
488 return group
503 return group
489
504
490
505
491 def repo2db_mapper(initial_repo_list, remove_obsolete=False):
506 def repo2db_mapper(initial_repo_list, remove_obsolete=False):
492 """
507 """
493 maps all repos given in initial_repo_list, non existing repositories
508 maps all repos given in initial_repo_list, non existing repositories
494 are created, if remove_obsolete is True it also checks for db entries
509 are created, if remove_obsolete is True it also checks for db entries
495 that are not in initial_repo_list and removes them.
510 that are not in initial_repo_list and removes them.
496
511
497 :param initial_repo_list: list of repositories found by scanning methods
512 :param initial_repo_list: list of repositories found by scanning methods
498 :param remove_obsolete: check for obsolete entries in database
513 :param remove_obsolete: check for obsolete entries in database
499 """
514 """
500 from rhodecode.model.repo import RepoModel
515 from rhodecode.model.repo import RepoModel
501 from rhodecode.model.scm import ScmModel
516 from rhodecode.model.scm import ScmModel
502 from rhodecode.model.repo_group import RepoGroupModel
517 from rhodecode.model.repo_group import RepoGroupModel
503 from rhodecode.model.settings import SettingsModel
518 from rhodecode.model.settings import SettingsModel
504
519
505 sa = meta.Session()
520 sa = meta.Session()
506 repo_model = RepoModel()
521 repo_model = RepoModel()
507 user = User.get_first_super_admin()
522 user = User.get_first_super_admin()
508 added = []
523 added = []
509
524
510 # creation defaults
525 # creation defaults
511 defs = SettingsModel().get_default_repo_settings(strip_prefix=True)
526 defs = SettingsModel().get_default_repo_settings(strip_prefix=True)
512 enable_statistics = defs.get('repo_enable_statistics')
527 enable_statistics = defs.get('repo_enable_statistics')
513 enable_locking = defs.get('repo_enable_locking')
528 enable_locking = defs.get('repo_enable_locking')
514 enable_downloads = defs.get('repo_enable_downloads')
529 enable_downloads = defs.get('repo_enable_downloads')
515 private = defs.get('repo_private')
530 private = defs.get('repo_private')
516
531
517 for name, repo in initial_repo_list.items():
532 for name, repo in initial_repo_list.items():
518 group = map_groups(name)
533 group = map_groups(name)
519 unicode_name = safe_unicode(name)
534 unicode_name = safe_unicode(name)
520 db_repo = repo_model.get_by_repo_name(unicode_name)
535 db_repo = repo_model.get_by_repo_name(unicode_name)
521 # found repo that is on filesystem not in RhodeCode database
536 # found repo that is on filesystem not in RhodeCode database
522 if not db_repo:
537 if not db_repo:
523 log.info('repository %s not found, creating now', name)
538 log.info('repository %s not found, creating now', name)
524 added.append(name)
539 added.append(name)
525 desc = (repo.description
540 desc = (repo.description
526 if repo.description != 'unknown'
541 if repo.description != 'unknown'
527 else '%s repository' % name)
542 else '%s repository' % name)
528
543
529 db_repo = repo_model._create_repo(
544 db_repo = repo_model._create_repo(
530 repo_name=name,
545 repo_name=name,
531 repo_type=repo.alias,
546 repo_type=repo.alias,
532 description=desc,
547 description=desc,
533 repo_group=getattr(group, 'group_id', None),
548 repo_group=getattr(group, 'group_id', None),
534 owner=user,
549 owner=user,
535 enable_locking=enable_locking,
550 enable_locking=enable_locking,
536 enable_downloads=enable_downloads,
551 enable_downloads=enable_downloads,
537 enable_statistics=enable_statistics,
552 enable_statistics=enable_statistics,
538 private=private,
553 private=private,
539 state=Repository.STATE_CREATED
554 state=Repository.STATE_CREATED
540 )
555 )
541 sa.commit()
556 sa.commit()
542 # we added that repo just now, and make sure we updated server info
557 # we added that repo just now, and make sure we updated server info
543 if db_repo.repo_type == 'git':
558 if db_repo.repo_type == 'git':
544 git_repo = db_repo.scm_instance()
559 git_repo = db_repo.scm_instance()
545 # update repository server-info
560 # update repository server-info
546 log.debug('Running update server info')
561 log.debug('Running update server info')
547 git_repo._update_server_info()
562 git_repo._update_server_info()
548
563
549 db_repo.update_commit_cache()
564 db_repo.update_commit_cache()
550
565
551 config = db_repo._config
566 config = db_repo._config
552 config.set('extensions', 'largefiles', '')
567 config.set('extensions', 'largefiles', '')
553 ScmModel().install_hooks(
568 ScmModel().install_hooks(
554 db_repo.scm_instance(config=config),
569 db_repo.scm_instance(config=config),
555 repo_type=db_repo.repo_type)
570 repo_type=db_repo.repo_type)
556
571
557 removed = []
572 removed = []
558 if remove_obsolete:
573 if remove_obsolete:
559 # remove from database those repositories that are not in the filesystem
574 # remove from database those repositories that are not in the filesystem
560 for repo in sa.query(Repository).all():
575 for repo in sa.query(Repository).all():
561 if repo.repo_name not in initial_repo_list.keys():
576 if repo.repo_name not in initial_repo_list.keys():
562 log.debug("Removing non-existing repository found in db `%s`",
577 log.debug("Removing non-existing repository found in db `%s`",
563 repo.repo_name)
578 repo.repo_name)
564 try:
579 try:
565 RepoModel(sa).delete(repo, forks='detach', fs_remove=False)
580 RepoModel(sa).delete(repo, forks='detach', fs_remove=False)
566 sa.commit()
581 sa.commit()
567 removed.append(repo.repo_name)
582 removed.append(repo.repo_name)
568 except Exception:
583 except Exception:
569 # don't hold further removals on error
584 # don't hold further removals on error
570 log.error(traceback.format_exc())
585 log.error(traceback.format_exc())
571 sa.rollback()
586 sa.rollback()
572
587
573 def splitter(full_repo_name):
588 def splitter(full_repo_name):
574 _parts = full_repo_name.rsplit(RepoGroup.url_sep(), 1)
589 _parts = full_repo_name.rsplit(RepoGroup.url_sep(), 1)
575 gr_name = None
590 gr_name = None
576 if len(_parts) == 2:
591 if len(_parts) == 2:
577 gr_name = _parts[0]
592 gr_name = _parts[0]
578 return gr_name
593 return gr_name
579
594
580 initial_repo_group_list = [splitter(x) for x in
595 initial_repo_group_list = [splitter(x) for x in
581 initial_repo_list.keys() if splitter(x)]
596 initial_repo_list.keys() if splitter(x)]
582
597
583 # remove from database those repository groups that are not in the
598 # remove from database those repository groups that are not in the
584 # filesystem due to parent child relationships we need to delete them
599 # filesystem due to parent child relationships we need to delete them
585 # in a specific order of most nested first
600 # in a specific order of most nested first
586 all_groups = [x.group_name for x in sa.query(RepoGroup).all()]
601 all_groups = [x.group_name for x in sa.query(RepoGroup).all()]
587 nested_sort = lambda gr: len(gr.split('/'))
602 nested_sort = lambda gr: len(gr.split('/'))
588 for group_name in sorted(all_groups, key=nested_sort, reverse=True):
603 for group_name in sorted(all_groups, key=nested_sort, reverse=True):
589 if group_name not in initial_repo_group_list:
604 if group_name not in initial_repo_group_list:
590 repo_group = RepoGroup.get_by_group_name(group_name)
605 repo_group = RepoGroup.get_by_group_name(group_name)
591 if (repo_group.children.all() or
606 if (repo_group.children.all() or
592 not RepoGroupModel().check_exist_filesystem(
607 not RepoGroupModel().check_exist_filesystem(
593 group_name=group_name, exc_on_failure=False)):
608 group_name=group_name, exc_on_failure=False)):
594 continue
609 continue
595
610
596 log.info(
611 log.info(
597 'Removing non-existing repository group found in db `%s`',
612 'Removing non-existing repository group found in db `%s`',
598 group_name)
613 group_name)
599 try:
614 try:
600 RepoGroupModel(sa).delete(group_name, fs_remove=False)
615 RepoGroupModel(sa).delete(group_name, fs_remove=False)
601 sa.commit()
616 sa.commit()
602 removed.append(group_name)
617 removed.append(group_name)
603 except Exception:
618 except Exception:
604 # don't hold further removals on error
619 # don't hold further removals on error
605 log.exception(
620 log.exception(
606 'Unable to remove repository group `%s`',
621 'Unable to remove repository group `%s`',
607 group_name)
622 group_name)
608 sa.rollback()
623 sa.rollback()
609 raise
624 raise
610
625
611 return added, removed
626 return added, removed
612
627
613
628
614 def get_default_cache_settings(settings):
629 def get_default_cache_settings(settings):
615 cache_settings = {}
630 cache_settings = {}
616 for key in settings.keys():
631 for key in settings.keys():
617 for prefix in ['beaker.cache.', 'cache.']:
632 for prefix in ['beaker.cache.', 'cache.']:
618 if key.startswith(prefix):
633 if key.startswith(prefix):
619 name = key.split(prefix)[1].strip()
634 name = key.split(prefix)[1].strip()
620 cache_settings[name] = settings[key].strip()
635 cache_settings[name] = settings[key].strip()
621 return cache_settings
636 return cache_settings
622
637
623
638
624 # set cache regions for beaker so celery can utilise it
639 # set cache regions for beaker so celery can utilise it
625 def add_cache(settings):
640 def add_cache(settings):
626 from rhodecode.lib import caches
641 from rhodecode.lib import caches
627 cache_settings = {'regions': None}
642 cache_settings = {'regions': None}
628 # main cache settings used as default ...
643 # main cache settings used as default ...
629 cache_settings.update(get_default_cache_settings(settings))
644 cache_settings.update(get_default_cache_settings(settings))
630
645
631 if cache_settings['regions']:
646 if cache_settings['regions']:
632 for region in cache_settings['regions'].split(','):
647 for region in cache_settings['regions'].split(','):
633 region = region.strip()
648 region = region.strip()
634 region_settings = {}
649 region_settings = {}
635 for key, value in cache_settings.items():
650 for key, value in cache_settings.items():
636 if key.startswith(region):
651 if key.startswith(region):
637 region_settings[key.split('.')[1]] = value
652 region_settings[key.split('.')[1]] = value
638
653
639 caches.configure_cache_region(
654 caches.configure_cache_region(
640 region, region_settings, cache_settings)
655 region, region_settings, cache_settings)
641
656
642
657
643 def load_rcextensions(root_path):
658 def load_rcextensions(root_path):
644 import rhodecode
659 import rhodecode
645 from rhodecode.config import conf
660 from rhodecode.config import conf
646
661
647 path = os.path.join(root_path, 'rcextensions', '__init__.py')
662 path = os.path.join(root_path, 'rcextensions', '__init__.py')
648 if os.path.isfile(path):
663 if os.path.isfile(path):
649 rcext = create_module('rc', path)
664 rcext = create_module('rc', path)
650 EXT = rhodecode.EXTENSIONS = rcext
665 EXT = rhodecode.EXTENSIONS = rcext
651 log.debug('Found rcextensions now loading %s...', rcext)
666 log.debug('Found rcextensions now loading %s...', rcext)
652
667
653 # Additional mappings that are not present in the pygments lexers
668 # Additional mappings that are not present in the pygments lexers
654 conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {}))
669 conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {}))
655
670
656 # auto check if the module is not missing any data, set to default if is
671 # auto check if the module is not missing any data, set to default if is
657 # this will help autoupdate new feature of rcext module
672 # this will help autoupdate new feature of rcext module
658 #from rhodecode.config import rcextensions
673 #from rhodecode.config import rcextensions
659 #for k in dir(rcextensions):
674 #for k in dir(rcextensions):
660 # if not k.startswith('_') and not hasattr(EXT, k):
675 # if not k.startswith('_') and not hasattr(EXT, k):
661 # setattr(EXT, k, getattr(rcextensions, k))
676 # setattr(EXT, k, getattr(rcextensions, k))
662
677
663
678
664 def get_custom_lexer(extension):
679 def get_custom_lexer(extension):
665 """
680 """
666 returns a custom lexer if it is defined in rcextensions module, or None
681 returns a custom lexer if it is defined in rcextensions module, or None
667 if there's no custom lexer defined
682 if there's no custom lexer defined
668 """
683 """
669 import rhodecode
684 import rhodecode
670 from pygments import lexers
685 from pygments import lexers
671
686
672 # custom override made by RhodeCode
687 # custom override made by RhodeCode
673 if extension in ['mako']:
688 if extension in ['mako']:
674 return lexers.get_lexer_by_name('html+mako')
689 return lexers.get_lexer_by_name('html+mako')
675
690
676 # check if we didn't define this extension as other lexer
691 # check if we didn't define this extension as other lexer
677 extensions = rhodecode.EXTENSIONS and getattr(rhodecode.EXTENSIONS, 'EXTRA_LEXERS', None)
692 extensions = rhodecode.EXTENSIONS and getattr(rhodecode.EXTENSIONS, 'EXTRA_LEXERS', None)
678 if extensions and extension in rhodecode.EXTENSIONS.EXTRA_LEXERS:
693 if extensions and extension in rhodecode.EXTENSIONS.EXTRA_LEXERS:
679 _lexer_name = rhodecode.EXTENSIONS.EXTRA_LEXERS[extension]
694 _lexer_name = rhodecode.EXTENSIONS.EXTRA_LEXERS[extension]
680 return lexers.get_lexer_by_name(_lexer_name)
695 return lexers.get_lexer_by_name(_lexer_name)
681
696
682
697
683 #==============================================================================
698 #==============================================================================
684 # TEST FUNCTIONS AND CREATORS
699 # TEST FUNCTIONS AND CREATORS
685 #==============================================================================
700 #==============================================================================
686 def create_test_index(repo_location, config):
701 def create_test_index(repo_location, config):
687 """
702 """
688 Makes default test index.
703 Makes default test index.
689 """
704 """
690 import rc_testdata
705 import rc_testdata
691
706
692 rc_testdata.extract_search_index(
707 rc_testdata.extract_search_index(
693 'vcs_search_index', os.path.dirname(config['search.location']))
708 'vcs_search_index', os.path.dirname(config['search.location']))
694
709
695
710
696 def create_test_directory(test_path):
711 def create_test_directory(test_path):
697 """
712 """
698 Create test directory if it doesn't exist.
713 Create test directory if it doesn't exist.
699 """
714 """
700 if not os.path.isdir(test_path):
715 if not os.path.isdir(test_path):
701 log.debug('Creating testdir %s', test_path)
716 log.debug('Creating testdir %s', test_path)
702 os.makedirs(test_path)
717 os.makedirs(test_path)
703
718
704
719
705 def create_test_database(test_path, config):
720 def create_test_database(test_path, config):
706 """
721 """
707 Makes a fresh database.
722 Makes a fresh database.
708 """
723 """
709 from rhodecode.lib.db_manage import DbManage
724 from rhodecode.lib.db_manage import DbManage
710
725
711 # PART ONE create db
726 # PART ONE create db
712 dbconf = config['sqlalchemy.db1.url']
727 dbconf = config['sqlalchemy.db1.url']
713 log.debug('making test db %s', dbconf)
728 log.debug('making test db %s', dbconf)
714
729
715 dbmanage = DbManage(log_sql=False, dbconf=dbconf, root=config['here'],
730 dbmanage = DbManage(log_sql=False, dbconf=dbconf, root=config['here'],
716 tests=True, cli_args={'force_ask': True})
731 tests=True, cli_args={'force_ask': True})
717 dbmanage.create_tables(override=True)
732 dbmanage.create_tables(override=True)
718 dbmanage.set_db_version()
733 dbmanage.set_db_version()
719 # for tests dynamically set new root paths based on generated content
734 # for tests dynamically set new root paths based on generated content
720 dbmanage.create_settings(dbmanage.config_prompt(test_path))
735 dbmanage.create_settings(dbmanage.config_prompt(test_path))
721 dbmanage.create_default_user()
736 dbmanage.create_default_user()
722 dbmanage.create_test_admin_and_users()
737 dbmanage.create_test_admin_and_users()
723 dbmanage.create_permissions()
738 dbmanage.create_permissions()
724 dbmanage.populate_default_permissions()
739 dbmanage.populate_default_permissions()
725 Session().commit()
740 Session().commit()
726
741
727
742
728 def create_test_repositories(test_path, config):
743 def create_test_repositories(test_path, config):
729 """
744 """
730 Creates test repositories in the temporary directory. Repositories are
745 Creates test repositories in the temporary directory. Repositories are
731 extracted from archives within the rc_testdata package.
746 extracted from archives within the rc_testdata package.
732 """
747 """
733 import rc_testdata
748 import rc_testdata
734 from rhodecode.tests import HG_REPO, GIT_REPO, SVN_REPO
749 from rhodecode.tests import HG_REPO, GIT_REPO, SVN_REPO
735
750
736 log.debug('making test vcs repositories')
751 log.debug('making test vcs repositories')
737
752
738 idx_path = config['search.location']
753 idx_path = config['search.location']
739 data_path = config['cache_dir']
754 data_path = config['cache_dir']
740
755
741 # clean index and data
756 # clean index and data
742 if idx_path and os.path.exists(idx_path):
757 if idx_path and os.path.exists(idx_path):
743 log.debug('remove %s', idx_path)
758 log.debug('remove %s', idx_path)
744 shutil.rmtree(idx_path)
759 shutil.rmtree(idx_path)
745
760
746 if data_path and os.path.exists(data_path):
761 if data_path and os.path.exists(data_path):
747 log.debug('remove %s', data_path)
762 log.debug('remove %s', data_path)
748 shutil.rmtree(data_path)
763 shutil.rmtree(data_path)
749
764
750 rc_testdata.extract_hg_dump('vcs_test_hg', jn(test_path, HG_REPO))
765 rc_testdata.extract_hg_dump('vcs_test_hg', jn(test_path, HG_REPO))
751 rc_testdata.extract_git_dump('vcs_test_git', jn(test_path, GIT_REPO))
766 rc_testdata.extract_git_dump('vcs_test_git', jn(test_path, GIT_REPO))
752
767
753 # Note: Subversion is in the process of being integrated with the system,
768 # Note: Subversion is in the process of being integrated with the system,
754 # until we have a properly packed version of the test svn repository, this
769 # until we have a properly packed version of the test svn repository, this
755 # tries to copy over the repo from a package "rc_testdata"
770 # tries to copy over the repo from a package "rc_testdata"
756 svn_repo_path = rc_testdata.get_svn_repo_archive()
771 svn_repo_path = rc_testdata.get_svn_repo_archive()
757 with tarfile.open(svn_repo_path) as tar:
772 with tarfile.open(svn_repo_path) as tar:
758 tar.extractall(jn(test_path, SVN_REPO))
773 tar.extractall(jn(test_path, SVN_REPO))
759
774
760
775
761 #==============================================================================
776 #==============================================================================
762 # PASTER COMMANDS
777 # PASTER COMMANDS
763 #==============================================================================
778 #==============================================================================
764 class BasePasterCommand(Command):
779 class BasePasterCommand(Command):
765 """
780 """
766 Abstract Base Class for paster commands.
781 Abstract Base Class for paster commands.
767
782
768 The celery commands are somewhat aggressive about loading
783 The celery commands are somewhat aggressive about loading
769 celery.conf, and since our module sets the `CELERY_LOADER`
784 celery.conf, and since our module sets the `CELERY_LOADER`
770 environment variable to our loader, we have to bootstrap a bit and
785 environment variable to our loader, we have to bootstrap a bit and
771 make sure we've had a chance to load the pylons config off of the
786 make sure we've had a chance to load the pylons config off of the
772 command line, otherwise everything fails.
787 command line, otherwise everything fails.
773 """
788 """
774 min_args = 1
789 min_args = 1
775 min_args_error = "Please provide a paster config file as an argument."
790 min_args_error = "Please provide a paster config file as an argument."
776 takes_config_file = 1
791 takes_config_file = 1
777 requires_config_file = True
792 requires_config_file = True
778
793
779 def notify_msg(self, msg, log=False):
794 def notify_msg(self, msg, log=False):
780 """Make a notification to user, additionally if logger is passed
795 """Make a notification to user, additionally if logger is passed
781 it logs this action using given logger
796 it logs this action using given logger
782
797
783 :param msg: message that will be printed to user
798 :param msg: message that will be printed to user
784 :param log: logging instance, to use to additionally log this message
799 :param log: logging instance, to use to additionally log this message
785
800
786 """
801 """
787 if log and isinstance(log, logging):
802 if log and isinstance(log, logging):
788 log(msg)
803 log(msg)
789
804
790 def run(self, args):
805 def run(self, args):
791 """
806 """
792 Overrides Command.run
807 Overrides Command.run
793
808
794 Checks for a config file argument and loads it.
809 Checks for a config file argument and loads it.
795 """
810 """
796 if len(args) < self.min_args:
811 if len(args) < self.min_args:
797 raise BadCommand(
812 raise BadCommand(
798 self.min_args_error % {'min_args': self.min_args,
813 self.min_args_error % {'min_args': self.min_args,
799 'actual_args': len(args)})
814 'actual_args': len(args)})
800
815
801 # Decrement because we're going to lob off the first argument.
816 # Decrement because we're going to lob off the first argument.
802 # @@ This is hacky
817 # @@ This is hacky
803 self.min_args -= 1
818 self.min_args -= 1
804 self.bootstrap_config(args[0])
819 self.bootstrap_config(args[0])
805 self.update_parser()
820 self.update_parser()
806 return super(BasePasterCommand, self).run(args[1:])
821 return super(BasePasterCommand, self).run(args[1:])
807
822
808 def update_parser(self):
823 def update_parser(self):
809 """
824 """
810 Abstract method. Allows for the class' parser to be updated
825 Abstract method. Allows for the class' parser to be updated
811 before the superclass' `run` method is called. Necessary to
826 before the superclass' `run` method is called. Necessary to
812 allow options/arguments to be passed through to the underlying
827 allow options/arguments to be passed through to the underlying
813 celery command.
828 celery command.
814 """
829 """
815 raise NotImplementedError("Abstract Method.")
830 raise NotImplementedError("Abstract Method.")
816
831
817 def bootstrap_config(self, conf):
832 def bootstrap_config(self, conf):
818 """
833 """
819 Loads the pylons configuration.
834 Loads the pylons configuration.
820 """
835 """
821 from pylons import config as pylonsconfig
836 from pylons import config as pylonsconfig
822
837
823 self.path_to_ini_file = os.path.realpath(conf)
838 self.path_to_ini_file = os.path.realpath(conf)
824 conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
839 conf = paste.deploy.appconfig('config:' + self.path_to_ini_file)
825 pylonsconfig.init_app(conf.global_conf, conf.local_conf)
840 pylonsconfig.init_app(conf.global_conf, conf.local_conf)
826
841
827 def _init_session(self):
842 def _init_session(self):
828 """
843 """
829 Inits SqlAlchemy Session
844 Inits SqlAlchemy Session
830 """
845 """
831 logging.config.fileConfig(self.path_to_ini_file)
846 logging.config.fileConfig(self.path_to_ini_file)
832 from pylons import config
847 from pylons import config
833 from rhodecode.config.utils import initialize_database
848 from rhodecode.config.utils import initialize_database
834
849
835 # get to remove repos !!
850 # get to remove repos !!
836 add_cache(config)
851 add_cache(config)
837 initialize_database(config)
852 initialize_database(config)
838
853
839
854
840 @decorator.decorator
855 @decorator.decorator
841 def jsonify(func, *args, **kwargs):
856 def jsonify(func, *args, **kwargs):
842 """Action decorator that formats output for JSON
857 """Action decorator that formats output for JSON
843
858
844 Given a function that will return content, this decorator will turn
859 Given a function that will return content, this decorator will turn
845 the result into JSON, with a content-type of 'application/json' and
860 the result into JSON, with a content-type of 'application/json' and
846 output it.
861 output it.
847
862
848 """
863 """
849 from pylons.decorators.util import get_pylons
864 from pylons.decorators.util import get_pylons
850 from rhodecode.lib.ext_json import json
865 from rhodecode.lib.ext_json import json
851 pylons = get_pylons(args)
866 pylons = get_pylons(args)
852 pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
867 pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8'
853 data = func(*args, **kwargs)
868 data = func(*args, **kwargs)
854 if isinstance(data, (list, tuple)):
869 if isinstance(data, (list, tuple)):
855 msg = "JSON responses with Array envelopes are susceptible to " \
870 msg = "JSON responses with Array envelopes are susceptible to " \
856 "cross-site data leak attacks, see " \
871 "cross-site data leak attacks, see " \
857 "http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
872 "http://wiki.pylonshq.com/display/pylonsfaq/Warnings"
858 warnings.warn(msg, Warning, 2)
873 warnings.warn(msg, Warning, 2)
859 log.warning(msg)
874 log.warning(msg)
860 log.debug("Returning JSON wrapped action output")
875 log.debug("Returning JSON wrapped action output")
861 return json.dumps(data, encoding='utf-8')
876 return json.dumps(data, encoding='utf-8')
862
877
863
878
864 class PartialRenderer(object):
879 class PartialRenderer(object):
865 """
880 """
866 Partial renderer used to render chunks of html used in datagrids
881 Partial renderer used to render chunks of html used in datagrids
867 use like::
882 use like::
868
883
869 _render = PartialRenderer('data_table/_dt_elements.mako')
884 _render = PartialRenderer('data_table/_dt_elements.mako')
870 _render('quick_menu', args, kwargs)
885 _render('quick_menu', args, kwargs)
871 PartialRenderer.h,
886 PartialRenderer.h,
872 c,
887 c,
873 _,
888 _,
874 ungettext
889 ungettext
875 are the template stuff initialized inside and can be re-used later
890 are the template stuff initialized inside and can be re-used later
876
891
877 :param tmpl_name: template path relate to /templates/ dir
892 :param tmpl_name: template path relate to /templates/ dir
878 """
893 """
879
894
880 def __init__(self, tmpl_name):
895 def __init__(self, tmpl_name):
881 import rhodecode
896 import rhodecode
882 from pylons import request, tmpl_context as c
897 from pylons import request, tmpl_context as c
883 from pylons.i18n.translation import _, ungettext
898 from pylons.i18n.translation import _, ungettext
884 from rhodecode.lib import helpers as h
899 from rhodecode.lib import helpers as h
885
900
886 self.tmpl_name = tmpl_name
901 self.tmpl_name = tmpl_name
887 self.rhodecode = rhodecode
902 self.rhodecode = rhodecode
888 self.c = c
903 self.c = c
889 self._ = _
904 self._ = _
890 self.ungettext = ungettext
905 self.ungettext = ungettext
891 self.h = h
906 self.h = h
892 self.request = request
907 self.request = request
893
908
894 def _mako_lookup(self):
909 def _mako_lookup(self):
895 _tmpl_lookup = self.rhodecode.CONFIG['pylons.app_globals'].mako_lookup
910 _tmpl_lookup = self.rhodecode.CONFIG['pylons.app_globals'].mako_lookup
896 return _tmpl_lookup.get_template(self.tmpl_name)
911 return _tmpl_lookup.get_template(self.tmpl_name)
897
912
898 def _update_kwargs_for_render(self, kwargs):
913 def _update_kwargs_for_render(self, kwargs):
899 """
914 """
900 Inject params required for Mako rendering
915 Inject params required for Mako rendering
901 """
916 """
902 _kwargs = {
917 _kwargs = {
903 '_': self._,
918 '_': self._,
904 'h': self.h,
919 'h': self.h,
905 'c': self.c,
920 'c': self.c,
906 'request': self.request,
921 'request': self.request,
907 '_ungettext': self.ungettext,
922 '_ungettext': self.ungettext,
908 }
923 }
909 _kwargs.update(kwargs)
924 _kwargs.update(kwargs)
910 return _kwargs
925 return _kwargs
911
926
912 def _render_with_exc(self, render_func, args, kwargs):
927 def _render_with_exc(self, render_func, args, kwargs):
913 try:
928 try:
914 return render_func.render(*args, **kwargs)
929 return render_func.render(*args, **kwargs)
915 except:
930 except:
916 log.error(exceptions.text_error_template().render())
931 log.error(exceptions.text_error_template().render())
917 raise
932 raise
918
933
919 def _get_template(self, template_obj, def_name):
934 def _get_template(self, template_obj, def_name):
920 if def_name:
935 if def_name:
921 tmpl = template_obj.get_def(def_name)
936 tmpl = template_obj.get_def(def_name)
922 else:
937 else:
923 tmpl = template_obj
938 tmpl = template_obj
924 return tmpl
939 return tmpl
925
940
926 def render(self, def_name, *args, **kwargs):
941 def render(self, def_name, *args, **kwargs):
927 lookup_obj = self._mako_lookup()
942 lookup_obj = self._mako_lookup()
928 tmpl = self._get_template(lookup_obj, def_name=def_name)
943 tmpl = self._get_template(lookup_obj, def_name=def_name)
929 kwargs = self._update_kwargs_for_render(kwargs)
944 kwargs = self._update_kwargs_for_render(kwargs)
930 return self._render_with_exc(tmpl, args, kwargs)
945 return self._render_with_exc(tmpl, args, kwargs)
931
946
932 def __call__(self, tmpl, *args, **kwargs):
947 def __call__(self, tmpl, *args, **kwargs):
933 return self.render(tmpl, *args, **kwargs)
948 return self.render(tmpl, *args, **kwargs)
934
949
935
950
936 def password_changed(auth_user, session):
951 def password_changed(auth_user, session):
937 # Never report password change in case of default user or anonymous user.
952 # Never report password change in case of default user or anonymous user.
938 if auth_user.username == User.DEFAULT_USER or auth_user.user_id is None:
953 if auth_user.username == User.DEFAULT_USER or auth_user.user_id is None:
939 return False
954 return False
940
955
941 password_hash = md5(auth_user.password) if auth_user.password else None
956 password_hash = md5(auth_user.password) if auth_user.password else None
942 rhodecode_user = session.get('rhodecode_user', {})
957 rhodecode_user = session.get('rhodecode_user', {})
943 session_password_hash = rhodecode_user.get('password', '')
958 session_password_hash = rhodecode_user.get('password', '')
944 return password_hash != session_password_hash
959 return password_hash != session_password_hash
945
960
946
961
947 def read_opensource_licenses():
962 def read_opensource_licenses():
948 global _license_cache
963 global _license_cache
949
964
950 if not _license_cache:
965 if not _license_cache:
951 licenses = pkg_resources.resource_string(
966 licenses = pkg_resources.resource_string(
952 'rhodecode', 'config/licenses.json')
967 'rhodecode', 'config/licenses.json')
953 _license_cache = json.loads(licenses)
968 _license_cache = json.loads(licenses)
954
969
955 return _license_cache
970 return _license_cache
956
971
957
972
958 def get_registry(request):
973 def get_registry(request):
959 """
974 """
960 Utility to get the pyramid registry from a request. During migration to
975 Utility to get the pyramid registry from a request. During migration to
961 pyramid we sometimes want to use the pyramid registry from pylons context.
976 pyramid we sometimes want to use the pyramid registry from pylons context.
962 Therefore this utility returns `request.registry` for pyramid requests and
977 Therefore this utility returns `request.registry` for pyramid requests and
963 uses `get_current_registry()` for pylons requests.
978 uses `get_current_registry()` for pylons requests.
964 """
979 """
965 try:
980 try:
966 return request.registry
981 return request.registry
967 except AttributeError:
982 except AttributeError:
968 return get_current_registry()
983 return get_current_registry()
969
984
970
985
971 def generate_platform_uuid():
986 def generate_platform_uuid():
972 """
987 """
973 Generates platform UUID based on it's name
988 Generates platform UUID based on it's name
974 """
989 """
975 import platform
990 import platform
976
991
977 try:
992 try:
978 uuid_list = [platform.platform()]
993 uuid_list = [platform.platform()]
979 return hashlib.sha256(':'.join(uuid_list)).hexdigest()
994 return hashlib.sha256(':'.join(uuid_list)).hexdigest()
980 except Exception as e:
995 except Exception as e:
981 log.error('Failed to generate host uuid: %s' % e)
996 log.error('Failed to generate host uuid: %s' % e)
982 return 'UNDEFINED'
997 return 'UNDEFINED'
General Comments 0
You need to be logged in to leave comments. Login now